@vkontakte/videoplayer-core 2.0.82 → 2.0.83-dev.65744ed.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esnext.esm.js CHANGED
@@ -1,8 +1,66 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.82
3
- * Mon, 17 Apr 2023 11:27:57 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-82/doc/
2
+ * @vkontakte/videoplayer-core v2.0.83-dev.65744ed.0
3
+ * Wed, 19 Apr 2023 17:05:19 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-83/doc/
5
5
  */
6
- import{ValueSubject as b,Subject as _,Subscription as K,isNonNullable as A,ErrorCategory as D,isNullable as W,fromEvent as B,assertNever as L,merge as C,tap as ns,map as E,observableFrom as $e,filterChanged as ue,assertNonNullable as k,debounce as _e,timeout as ti,combine as Ye,once as pe,mapTo as ot,filter as O,now as ce,Observable as _t,abortable as Ce,getExponentialDelay as os,interval as si,Logger as ii}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as pr,Subject as mr,Subscription as Sr,ValueSubject as gr}from"@vkontakte/videoplayer-shared/esnext.esm.js";import ai from"lodash/debounce.js";const ri="2.0.82",ni="esnext.esm.js";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_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 Ae;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));var Te;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(Te||(Te={}));var Dt;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Dt||(Dt={}));var N;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(N||(N={}));var oi=a=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",a),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class di{connection$=new b(void 0);castState$=new b(Te.NOT_AVAILABLE);errorEvent$=new _;contentId;realCastState$=new b(Te.NOT_AVAILABLE);subscription=new K;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 s=A(window.chrome?.cast),i=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},i||oi("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:D.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();W(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();W(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),s=cast.framework.CastContext.getInstance();this.subscription.add(B(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=s.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 L(i.sessionState)}})).add(C(B(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ns(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),E(i=>i.castState)),$e([s.getCastState()])).pipe(ue(),E(ci),ns(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{const r=i===Te.CONNECTED,n=A(this.connection$.getValue());if(r&&!n){const o=s.getCurrentSession();k(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(W(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(i===Te.CONNECTED?A(this.connection$.getValue())?Te.CONNECTED:Te.AVAILABLE:i)}))}initializeCastApi(){let e,t,s;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:s}),this.initListeners()}catch(i){this.errorEvent$.next({id:"ChromecastInitializer",category:D.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}}const ci=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Te.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Te.AVAILABLE;case cast.framework.CastState.CONNECTING:return Te.CONNECTING;case cast.framework.CastState.CONNECTED:return Te.CONNECTED;default:return L(a)}};var ft;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ft||(ft={}));var pt=(a,e=0,t=ft.OFFSET_P)=>{switch(t){case ft.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ft.PLAYBACK_SHIFT:{if(e===0)return a;const s=new URL(a);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:L(t)}return a},w=(a,e,t=!1)=>{const s=a.getTransition();(t||!s||s.to===e)&&a.setState(e)},se;(function(a){a.INVARIANT="Invariant quality",a.Q_144P="144p",a.Q_240P="240p",a.Q_360P="360p",a.Q_480P="480p",a.Q_720P="720p",a.Q_1080P="1080p",a.Q_1440P="1440p",a.Q_2160P="2160p",a.Q_4320P="4320p"})(se||(se={}));const Le={[se.Q_144P]:{width:256,height:144},[se.Q_240P]:{width:428,height:240},[se.Q_360P]:{width:640,height:360},[se.Q_480P]:{width:856,height:480},[se.Q_720P]:{width:1280,height:720},[se.Q_1080P]:{width:1920,height:1080},[se.Q_1440P]:{width:2560,height:1440},[se.Q_2160P]:{width:3840,height:2160},[se.Q_4320P]:{width:7680,height:4320}},Ut=(a,e)=>Le[a].height>Le[e].height,ui=(a,e)=>Le[a].height>=Le[e].height,kt=(a,e)=>Le[a].height<Le[e].height,hi=(a,e)=>Le[a].height<=Le[e].height,li=a=>a.sort((e,t)=>e===t?0:e===se.INVARIANT?1:t===se.INVARIANT?-1:kt(e,t)?1:-1)[0],fi=Object.keys(Le).sort((a,e)=>kt(a,e)?-1:1),dt=({width:a,height:e})=>{const t=Math.min(a,e),s=Math.max(a,e);return fi.find(i=>{const r=Le[i];return r.width>=s&&r.height>=t})},pi=a=>Le[a].height,Ft=a=>a===se.INVARIANT;class re{state;transition;transitionStarted$=new _;transitionEnded$=new _;transitionUpdated$=new _;forceChanged$=new _;stateChangeStarted$=C(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=C(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e}setState(e){const t=this.transition,s=this.state;this.transition=void 0,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:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||A(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const mi=a=>{switch(a){case g.MPEG:case g.DASH:case g.DASH_SEP:case g.DASH_ONDEMAND:case g.DASH_WEBM: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 L(a)}};var M;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(M||(M={}));const Si=5,gi=5,bi=500,ds=7e3;class yi{subscription=new K;loadMediaTimeoutSubscription=new K;videoState=new re(M.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(mi(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 K;this.subscription.add(e),this.subscription.add(C(this.videoState.stateChangeStarted$.pipe(E(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(E(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));const t=(i,r)=>this.subscription.add(i.subscribe(r));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new _;e.add(i.pipe(_e(bi)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let r=NaN;e.add(B(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===N.Applying||Math.abs(o-r)>Si)&&i.next(o),r=o})),e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);const{remotePlayer:r}=this.params.connection,n=i.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<gi&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:L(n)}}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});const s=C(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0));t(s,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(M.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(M.PLAYING),w(this.params.desiredState.playbackState,l.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:N.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===M.PAUSED||e===M.PLAYING)&&(this.videoState.setState(M.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===M.PLAYING||e===M.PAUSED)&&(this.videoState.setState(M.PLAYING),w(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===M.READY&&this.videoState.setState(M.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&w(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==M.STOPPED&&this.videoState.setState(M.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),s={volume:e.volume??t.volume,muted:e.muted??t.muted};(s.volume!==t.volume||s.muted!==s.muted)&&this.params.output.volume$.next(s)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let s,i,r;switch(e){case g.MPEG:{const d=t[e];k(d);const u=li(Object.keys(d));k(u);const h=d[u];k(h),s=h,i="video/mp4",r=chrome.cast.media.StreamType.BUFFERED;break}case g.HLS:case g.HLS_ONDEMAND:{const d=t[e];k(d),s=d.url,i="application/x-mpegurl",r=chrome.cast.media.StreamType.BUFFERED;break}case g.DASH_SEP:case g.DASH_ONDEMAND:case g.DASH_WEBM:{const d=t[e];k(d),s=d.url,i="application/dash+xml",r=chrome.cast.media.StreamType.BUFFERED;break}case g.DASH_LIVE_CMAF:{const d=t[e];k(d),s=d.url,i="application/dash+xml",r=chrome.cast.media.StreamType.LIVE;break}case g.HLS_LIVE:case g.HLS_LIVE_CMAF:{const d=t[e];k(d),s=pt(d.url),i="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",u=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:D.VIDEO_PIPELINE,message:d,thrown:u}),u}case g.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return L(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??s,i);n.contentUrl=s,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 s=this.params.desiredState.seekState.getState();return s.state===N.Applying||s.state===N.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((i,r)=>{this.loadMediaTimeoutSubscription.add(ti(ds).subscribe(()=>r(`timeout(${ds})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{const r=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:r}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:D.VIDEO_PIPELINE,message:r,thrown:i})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),s===l.STOPPED){e!==M.STOPPED&&(this.videoState.startTransitionTo(M.STOPPED),this.stop());return}if(!t){if(i?.to!==l.PAUSED&&r.state===N.Requested&&e!==M.STOPPED){this.seek(r.position/1e3);return}switch(s){case l.READY:{switch(e){case M.PLAYING:case M.PAUSED:case M.READY:break;case M.STOPPED:this.videoState.startTransitionTo(M.READY),this.prepare();break;default:L(e)}break}case l.PLAYING:{switch(e){case M.PLAYING:break;case M.PAUSED:this.videoState.startTransitionTo(M.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case M.READY:this.videoState.startTransitionTo(M.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case M.STOPPED:this.videoState.startTransitionTo(M.READY),this.prepare();break;default:L(e)}break}case l.PAUSED:{switch(e){case M.PLAYING:this.videoState.startTransitionTo(M.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case M.PAUSED:break;case M.READY:this.videoState.startTransitionTo(M.PAUSED),this.videoState.setState(M.PAUSED);break;case M.STOPPED:this.videoState.startTransitionTo(M.READY),this.prepare();break;default:L(e)}break}default:L(s)}}}}class cs{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let i=0,r=s.length;i<r;i++)if(s[i].callback===t){s.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let i=0,r=s.length;i<r;i++){const n=s[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Ls extends cs{constructor(){super(),this.listeners||cs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let xs=class{constructor(){Object.defineProperty(this,"signal",{value:new Ls,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(xs.prototype[Symbol.toStringTag]="AbortController",Ls.prototype[Symbol.toStringTag]="AbortSignal");function Bs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Ti(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Bs({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:r};let r=t;(r&&!r.prototype.hasOwnProperty("signal")||i)&&(r=function(d,u){let h;u&&u.signal&&(h=u.signal,delete u.signal);const f=new t(d,u);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},r.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const u=r&&r.prototype.isPrototypeOf(c)?c.signal:d?d.signal:void 0;if(u){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(u.aborted)return Promise.reject(h);const f=new Promise((S,p)=>{u.addEventListener("abort",()=>p(h),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([f,n(c,d)])}return n(c,d)},Request:r}}const Qt=Bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ns=Qt?Ti({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,mt=Qt?Ns.fetch:window.fetch;Qt?Ns.Request:window.Request;const rt=Qt?xs:window.AbortController,vt=a=>a.range?a.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class wt{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){const{url:t}=e.request,s=this.dashJsRequestQueue.get(t)??[];s.push(e),this.dashJsRequestQueue.set(t,s)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const i=t[0];if(!i||!i.request.range)continue;const[r,n]=vt(i.request);if(r>=s.from&&n<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const i=this.sendBigRequest(e,t.map(({request:r})=>r));this.activeRequests.set(e,i)}}}abort(e){if(e){const{request:t}=e,s=(this.dashJsRequestQueue.get(t.url)??[]).includes(e),i=this.activeRequests.get(t.url);s&&i&&i.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(vt),i=s[0][0];let r=s[0][1];for(let f=1;f<s.length&&r<this.params.minDataSize;f++){const S=s[f][1];S-i<=2*this.params.minDataSize&&(r=Math.max(r,S))}i===0?r=Math.max(r,i+this.params.minInitSize):r=Math.max(r,i+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${i}-${r}`);const o=n.toString(),c=new rt,d=c.signal,u={url:e,from:i,to:r,loaded:0,data:null,abortController:c};d.addEventListener("abort",()=>this.onBigRequestAbort(u));const h=f=>{throw this.params.onError?.({id:"BigRequestParsing",category:D.PARSER,message:"Error parsing response data",thrown:f}),f};return mt(o,{signal:d}).then(f=>{if(u.response=f,!f.ok||!f.body){this.onBigRequestError(u);return}const[S,p]=f.body.tee();this.params.onDownloadStream?.(p);const m=S.getReader(),y=parseInt(f.headers.get("Content-Length")??"",10)||r-i+1;u.data=new ArrayBuffer(y);const P=new Uint8Array(u.data),x=async({done:Z,value:$})=>{Z?this.onBigRequestProgress(u):$&&(P.set($,u.loaded),u.loaded+=$.byteLength,this.onBigRequestProgress(u),await m?.read().then(x,wt.suppressStreamErrors).catch(h))};m?.read().then(x,wt.suppressStreamErrors).catch(h)},wt.suppressAbort).catch(f=>this.onBigRequestError(u,f)),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:r,response:n}){if(!this.activeRequests.has(e)||!r)return;const o=this.dashJsRequestQueue.get(e)??[];for(const c of o){const{request:d}=c,[u,h]=vt(d),f=u>=t&&h<=t+i,S=t>=u&&t+i<h,p=r.slice(u-t,Math.min(h-t+1,i));if((f||S)&&(d.requestStartDate=d.requestStartDate??new Date,d.firstByteDate=d.firstByteDate??new Date,d.bytesLoaded=p.byteLength,d.bytesTotal=s-t),f){d.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter(y=>y!==c)),c.success?.(p,"",e);const m=n?Array.from(n.headers.entries()).map(([y,P])=>`${y}: ${P}`).join(`\r
7
- `):"";this.dashMetrics?.addHttpRequest(d,e,n?.status??200,m,[])}else S&&c.progress?.({loaded:i,total:s-t,lengthComputable:!0,stream:!0})}}onBigRequestError({url:e,from:t,to:s},i){if(this.params.onError?.({id:"BigRequest",category:D.NETWORK,message:"Download error",thrown:i}),!this.activeRequests.has(e))return;const r=this.dashJsRequestQueue.get(e)??[];for(const n of r){const[o,c]=vt(n.request);(o>=t&&o<s||c>t&&c<=s)&&n?.error?.(n.request,String(i))}if(this.activeRequests.delete(e),i)throw i}onBigRequestAbort({url:e,from:t,to:s}){if(!this.activeRequests.has(e))return;const i=this.dashJsRequestQueue.get(e)??[];for(const r of i){const[n,o]=vt(r.request);(n>=t&&n<s||o>t&&o<=s)&&r?.abort?.(r.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Ht{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Ht.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Ht.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Ei=(a,e)=>t=>({create:s=>{const i=a(t).create(s);return new Ht(i,e,s)}}),vi=(a,e)=>{const t=new wt(e);return a.extend("SchemeLoaderFactory",function(){const{parent:s}=this,i=s.getLoader;return{getLoader:r=>{const n=i(r);return Ei(n,t)}}},!0),()=>t.destroy()};var Ai=a=>{let e,t=!1,s=!1;a.on("playbackTimeUpdated",({timeToEnd:i})=>{s=i<=3,t&&s&&e?.()}),a.extend("MediaSourceController",function(){const{parent:i}=this,r=i.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>r(n),t&&s&&e?.()}}},!0)},$i=a=>{const e=new b(1/0),t=new _,s=new b(void 0),i=new b(void 0);let r=NaN,n=!1;const o=()=>{r=Date.now(),n=!1},c=u=>{const h=Object.fromEntries(u.getAllResponseHeaders().trim().split(/[\n\r]+/).map(p=>p.split(": ")));if("x-playback-duration"in h||"x-playback-duration-millis"in h){const p=parseInt(u.getResponseHeader("X-Playback-Duration")??"",10),y=parseInt(u.getResponseHeader("X-Playback-Duration-Millis")??"",10)??p*1e3??NaN;A(y)&&!isNaN(y)&&e.next(y)}const f=h["x-delivery-type"]??Dt.HTTP1,S={1:!0,0:!1}[h["x-reused"]]??void 0;s.next(f),i.next(S)},d=u=>{u.readyState>=2&&!n&&(n=!0,t.next(Date.now()-r))};return a.extend("XHRLoader",function(){const{parent:u}=this,h=u.load.bind(u);return{load:function(f){if(f.request.type==="MPD"){const S=f.onload,p=f.progress;f.onload=function(...m){return c(this),S(...m)},f.progress=function(...m){return d(this),p(...m)},o()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:i,connectionType$:s}},St=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},ki=a=>a.extend("RequestModifier",()=>({modifyRequestURL:St}),!0),wi=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[i,r]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${i}-${r}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const Ne=(a,e,t,{equal:s=(n,o)=>n===o,changed$:i,onError:r}={})=>{const n=a.getState(),o=e(),c=W(i),d=new K;return i&&d.add(i.subscribe(u=>{const h=a.getState();s(u,h)&&a.setState(u)},r)),s(o,n)||(t(n),c&&a.setState(n)),d.add(a.stateChangeStarted$.subscribe(u=>{t(u.to),c&&a.setState(u.to)},r)),d},ct=(a,e,t)=>Ne(e,()=>a.loop,s=>{A(s)&&(a.loop=s)},{onError:t}),Ge=(a,e,t,s)=>Ne(e,()=>({muted:a.muted,volume:a.volume}),i=>{A(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,r)=>i===r||i?.muted===r?.muted&&i?.volume===r?.volume,changed$:t,onError:s}),et=(a,e,t,s)=>Ne(e,()=>a.playbackRate,i=>{A(i)&&(a.playbackRate=i)},{changed$:t,onError:s}),Pi=a=>["__",a.language,a.label].join("|"),Ri=(a,e)=>{if(a.id===e)return!0;const[t,s,i]=e.split("|");return a.language===s&&a.label===i};class Me{available$=new _;current$=new b(void 0);error$=new _;video;cueSettings;subscription=new K;externalTracks=new Map;connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const i=r=>{this.error$.next({id:"TextTracksManager",category:D.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:r})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Ne(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(E(r=>r.filter(({type:n})=>n==="external"))),onError:i})),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:i})),this.subscription.add(Ne(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const r of this.htmlTextTracksAsArray())this.applyCueSettings(r.cues),this.applyCueSettings(r.activeCues)}))}subscribe(){k(this.video);const{textTracks:e}=this.video;this.subscription.add(B(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(C(B(e,"addtrack"),B(e,"removetrack"),$e(["init"])).pipe(E(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),ue((s,i)=>s.length===i.length&&s.every(({id:r},n)=>r===i[n].id))).subscribe(this.available$)),this.subscription.add(C(B(e,"change"),$e(["init"])).pipe(E(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),E(s=>s&&this.htmlTextTrackToITextTrack(s).id),ue()).subscribe(this.current$));const t=s=>this.applyCueSettings(s.target?.activeCues??null);this.subscription.add(B(e,"addtrack").subscribe(s=>{s.track?.addEventListener("cuechange",t);const i=r=>{const n=r.target?.cues??null;n&&n.length&&(this.applyCueSettings(r.target?.cues??null),r.target?.removeEventListener("cuechange",i))};s.track?.addEventListener("cuechange",i)})),this.subscription.add(B(e,"removetrack").subscribe(s=>{s.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const i=s;A(t.align)&&(i.align=t.align),A(t.position)&&(i.position=t.position),A(t.size)&&(i.size=t.size),A(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){k(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Me.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=e.id!==""?e.id:Pi(e);return this.externalTracks.has(i)?{id:i,type:"external",language:t,label:s,url:this.externalTracks.get(i).url}:{id:i,type:"internal",language:t,label:s}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){k(this.video);for(const t of this.htmlTextTracksAsArray(!0))A(e)&&Ri(t,e)?t.mode="showing":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){k(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),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){k(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var ze=a=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),a.appendChild(e),e};class ss{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Ms=()=>{const{userAgent:a}=window.navigator;return!/chrome/i.test(a)&&/webkit|safari|khtml/i.test(a)};const Zt=3;class Di{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let i=this._source.buffered.start(t);const r=this._source.buffered.end(t);i>e&&i-e<Zt&&(i=e),this._buffer.push({from:i,to:r,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||Zt))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:i,to:r})=>{const n=i>=e&&i<t,o=r>=e&&r<t;n&&o||(n?s(t,r):o?s(i,e):i<e&&r>t?(s(t,r),s(i,e)):s(i,r))})}destroy(){this._buffer=[]}}var Os=(a,e,t=Zt)=>{let s=0,i=0;for(let r=0;r<a.length;r++){const n=a.start(r),o=a.end(r);if(n<=e&&e<=o){if(s=n,i=o,!t)return{from:s,to:i};for(let c=r-1;c>=0;c--)a.end(c)+t>=s&&(s=a.start(c));for(let c=r+1;c<a.length;c++)a.start(c)-t<=i&&(i=a.end(c))}}return{from:s,to:i}};const _i=50,Ii=a=>a.webkitAudioDecodedByteCount!=="undefined"?!!a.webkitAudioDecodedByteCount:a.mozHasAudio!=="undefined"?a.mozHasAudio:a.audioTracks?!!a.audioTracks.length:!0,We=a=>{const e=p=>B(a,p).pipe(ot(void 0)),s=C(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(p=>B(a,p))).pipe(E(p=>p.type==="ended"?a.readyState<2:a.readyState<3),ue()),i=C(B(a,"progress"),B(a,"timeupdate")).pipe(E(()=>Os(a.buffered,a.currentTime))),r=Ms()?Ye({play:e("play").pipe(pe()),playing:e("playing")}).pipe(ot(void 0)):e("playing"),n=B(a,"playing").pipe(_e(_i),E(()=>Ii(a))),o=B(a,"volumechange").pipe(E(()=>({muted:a.muted,volume:a.volume}))),c=B(a,"ratechange").pipe(E(()=>a.playbackRate)),d=B(a,"error").pipe(O(()=>Boolean(a.error||a.played.length)),E(()=>{const p=a.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:D.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:a.error??void 0}})),u=B(a,"timeupdate").pipe(E(()=>a.currentTime)),h=new _,f=.3;let S;return u.subscribe(p=>{a.loop&&A(S)&&A(p)&&S>=a.duration-f&&p<=f&&h.next(S),S=p}),{playing$:r,pause$:e("pause").pipe(O(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:B(a,"durationchange").pipe(E(()=>a.duration)),isBuffering$:s,currentBuffer$:i,volumeState$:o,isAudioAvailable$:n,playbackRateState$:c}},is=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let as=!1,He={};const Ci=a=>{as=a},Li=()=>{He={}},xi=a=>{a(He)},Bt=(a,e)=>{as&&(He.meta=He.meta??{},He.meta[a]=e)};class Be{name;constructor(e){this.name=e}next(e){if(!as)return;He.series=He.series??{};const t=He.series[this.name]??[];t.push([Date.now(),e]),He.series[this.name]=t}}const Bi=new Be("best_bitrate"),Ni=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class Mi{last;history={};recordSelection(e){this.history[e.id]=ce()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const It=(a,{container:e,throughput:t,tuning:s,limits:i,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d})=>{const u=s.usePixelRatio?window.devicePixelRatio??1:1,h=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*u*s.containerSizeFactor,height:e.height*u*s.containerSizeFactor},f=h&&dt(h),S=s.considerPlaybackRate&&A(o)?o:1,p=a.filter(H=>!Ft(H.quality)).sort((H,ie)=>Ut(H.quality,ie.quality)?-1:1),m=p.at(-1)?.quality,y=p.at(0)?.quality,P=W(i)||A(i.min)&&A(i.max)&&kt(i.max,i.min)||A(i.min)&&y&&Ut(i.min,y)||A(i.max)&&m&&kt(i.max,m),x=S*Ni(n??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),$=p.filter(H=>{const ie=f?kt(H.quality,f):!0,q=A(t)&&isFinite(t)&&A(H.bitrate)?t-r>=H.bitrate*x:!0,J=s.lazyQualitySwitch&&A(s.minBufferToSwitchUp)&&c&&!Ft(c.quality)&&(n??0)<s.minBufferToSwitchUp&&Ut(H.quality,c.quality),ne=P||(W(i.max)||hi(H.quality,i.max))&&(W(i.min)||ui(H.quality,i.min));return ie&&q&&!J&&ne})[0];$&&$.bitrate&&Bi.next($.bitrate);const v=$??p[Math.ceil((p.length-1)/2)]??a[0],F=v&&d&&d.history[v.id]&&ce()-d.history[v.id]<=s.trackCooldown&&(!d.last||v.id!==d.last.id);if(v?.id&&d&&!F&&d.recordSelection(v),F&&d?.last){const H=d.last;return d?.recordSwitch(H),H}return d?.recordSwitch(v),v};var ve=a=>new URL(a).hostname;const Oi=300,qt=(a,e=Oi)=>new _t(t=>{const{width:s,height:i}=a.getBoundingClientRect();if(t.next({width:s,height:i}),!window.ResizeObserver)return;const r=new ResizeObserver(ai(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()}),Ui=5e3,At={};var U;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(U||(U={}));const fe=(a,e)=>new _t(t=>{const s=i=>t.next(i);return a.on(e,s),()=>a.off(e,s)});class us{subscription=new K;videoState=new re(U.DOWNLOADING_LIB);video;player;params;textTracksManager=new Me;videoTracks=[];frameRatesByFrameHeight={};isLive$=new b(void 0);maxSeekBackTime$=new b(1/0);availableFrom$=new b(void 0);elementSize$=new b(void 0);liveOffset=new ss;destroyBigRequest;constructor(e){this.video=ze(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(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:D.NETWORK,message:`Dash.js failed to load: ${i?.toString?.()}`,thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),Ui);import("dashjs/dist/dash.mediaplayer.min.js").then(i=>{e||(At.MediaPlayer=i.MediaPlayer,At.Debug=i.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){k(At.MediaPlayer,"dashjs not loaded"),k(At.Debug,"dashjs not loaded"),this.player=At.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(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?is(t.frameRate+""):void 0),!0)),(this.params.format===g.DASH_WEBM||this.params.format===g.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=vi(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&wi(this.player),Ai(this.player),this.params.tuning.requestQuick&&ki(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(U.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=m=>{e.error$.next({id:"DashIFProvider",category:D.WTF,message:"DashIFProvider internal logic error",thrown:m})},i=(m,y)=>this.subscription.add(m.subscribe(y,s));i(qt(this.video),this.elementSize$),i(fe(this.player,"error").pipe(E(m=>{const y=typeof m.error=="object"?m.error.code:m.error,P=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${y}`,message:P}})),e.error$),i(fe(this.player,"playbackError").pipe(E(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const r=fe(this.player,"qualityChangeRendered").pipe(O(({mediaType:m})=>m==="video"),E(({newQuality:m})=>this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===m)?.track));r.pipe(O(A)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(O(({to:m})=>m===U.STREAM_INITIALIZED),pe()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===m)?.track?.id},m=>{if(W(m))return;const y=this.videoTracks.find(({track:P})=>P.id===m)?.bitrateInfo;y&&this.player.setQualityFor("video",y.qualityIndex)},{changed$:r.pipe(E(m=>m?.id)),onError:s}))},s)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:s})),i(fe(this.player,"bufferStateChanged").pipe(O(({mediaType:m})=>m==="video"),E(({state:m})=>m==="bufferStalled")),e.isBuffering$),i(fe(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:y}})=>{const P=this.player.getDashMetrics(),x=P.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),Z=P.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??Dt.HTTP1,$={1:!0,0:!1}[x]??void 0;this.params.output.httpConnectionType$.next(Z),this.params.output.httpConnectionReused$.next($),e.hostname$.next(ve(y))}),i(fe(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:y,availableFrom:P}}})=>{this.isLive$.next(y),this.availableFrom$.next(P.getTime()),y||e.duration$.next(m),this.videoTracks=[];const x=this.player.getQualityFor("video");let Z;for(const $ of this.player.getBitrateInfoListFor("video")){const v=$.qualityIndex.toString(10),F=dt($),H=$.bitrate/1e3,ie={width:$.width,height:$.height},q=this.frameRatesByFrameHeight[$.height];if(F){const J={id:v,quality:F,bitrate:H,size:ie,fps:q};this.videoTracks.push({track:J,bitrateInfo:$}),$.qualityIndex===x&&(Z=J)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:$})=>$)),Z&&e.currentVideoTrack$.next(Z),this.videoState.setState(U.STREAM_INITIALIZED),this.videoState.startTransitionTo(U.READY)}),i(fe(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const y=m.requestEndDate.getTime()-m.firstByteDate.getTime(),P=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(P,y)}),i(C(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),y=It(this.videoTracks.map(({track:x})=>x),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),P=this.videoTracks.find(({track:x})=>x===y);P?.bitrateInfo&&this.player.setQualityFor("video",P?.bitrateInfo.qualityIndex,!1)}),i(Ye({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(O(A))}).pipe(O(({isLive:m})=>m),E(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=fe(this.player,"playbackTimeUpdated").pipe(E(({time:m})=>m??0));i(Ye({availableFrom:this.availableFrom$.pipe(O(A)),currentTime:n}),({availableFrom:m,currentTime:y})=>this.params.output.liveTime$.next(m+y*1e3)),i(n.pipe(O(()=>this.isLive$.getValue()===!1)),e.position$),i(fe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),i(fe(this.player,"playbackEnded"),e.endedEvent$),i(fe(this.player,"playbackProgress").pipe(E(()=>Os(this.video.buffered,this.video.currentTime))),e.currentBuffer$),i(fe(this.player,"playbackPlaying"),()=>{this.videoState.setState(U.PLAYING),w(t.playbackState,l.PLAYING)}),i(fe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(U.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),i(fe(this.player,"playbackPaused"),()=>{this.videoState.setState(U.PAUSED),w(t.playbackState,l.PAUSED)}),i(fe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY)}),i(this.isLive$,e.isLive$),i(qt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=C(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0));i(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:u,connectionReused$:h}=$i(this.player);i(u,this.params.output.httpConnectionType$),i(h,this.params.output.httpConnectionReused$),i(c,this.maxSeekBackTime$),i(d.pipe(pe()),e.firstBytesEvent$),i(fe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&i(Ye({isLive:this.isLive$,isShort:e.duration$.pipe(E(m=>m<60))}),({isLive:m,isShort:y})=>{const P=!m&&y;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:P}}})}),i(n.pipe(O(m=>m>this.params.tuning.insufficientBufferRuleMargin),pe()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(fe(this.player,"manifestLoaded").pipe(pe()).subscribe(()=>{this.subscription.add(fe(this.player,"playbackPlaying").pipe(pe(),ot(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(ct(this.video,t.isLooped,s));const{volumeState$:f,looped$:S,playbackRateState$:p}=We(this.video);this.subscription.add(Ge(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(S.subscribe(e.loopedEvent$)),this.subscription.add(et(this.video,t.playbackRate,p,s))}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(U.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(U.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,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const i=pt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ft.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(U.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(U.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===U.DOWNLOADING_LIB||e===U.STREAM_INITIALIZED))switch(s?.to!==l.PAUSED&&i.state===N.Requested&&e!==U.STOPPED&&t!==l.STOPPED&&(r?this.seek(i.position-this.liveOffset.getTotalPausedTime()):this.seek(i.position)),t){case l.STOPPED:{switch(e){case U.STOPPED:break;case U.PLAYING:case U.PAUSED:case U.READY:this.stop();break;default:L(e)}break}case l.READY:{switch(e){case U.STOPPED:this.prepare();break;case U.PLAYING:case U.PAUSED:case U.READY:break;default:L(e)}break}case l.PLAYING:{switch(e){case U.PLAYING:break;case U.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 U.READY:this.play();break;case U.STOPPED:this.prepare();break;default:L(e)}break}case l.PAUSED:{switch(e){case U.PLAYING:this.pause(),this.liveOffset.pause();break;case U.PAUSED:break;case U.READY:this.videoState.setState(U.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED);break;case U.STOPPED:this.prepare();break;default:L(e)}break}default:L(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch{}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Ct=a=>{switch(a){case"mobile":return se.Q_144P;case"lowest":return se.Q_240P;case"low":return se.Q_360P;case"sd":case"medium":return se.Q_480P;case"hd":case"high":return se.Q_720P;case"fullhd":case"full":return se.Q_1080P;case"quadhd":case"quad":return se.Q_1440P;case"ultrahd":case"ultra":return se.Q_2160P}},tt=async a=>{const e=a.muted;try{await a.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(s){return a.muted=!1,console.warn(s),!1}}return!0};function ye(){return ce()}function Us(a){return ye()-a}function hs(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,i=n=>s.test(n);return{resolve:(n,o,c=!1)=>{i(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 Vi(a,e,t){const s=(...i)=>{t.apply(null,i),a.removeEventListener(e,s)};a.addEventListener(e,s)}function Vt(a,e,t,s){const i=window.XMLHttpRequest;let r,n,o,c=!1,d=0,u,h,f=!1,S="arraybuffer",p=7e3,m=2e3,y=()=>{if(c)return;k(u);const j=Us(u);let le;if(j<m){le=m-j,setTimeout(y,le);return}m*=2,m>p&&(m=p),n&&n.abort(),n=new i,F()};const P=j=>(r=j,ne),x=j=>(h=j,ne),Z=()=>(S="json",ne),$=()=>{if(!c){if(--d>=0){y(),s&&s();return}c=!0,h&&h(),t&&t()}},v=j=>(f=j,ne),F=()=>{u=ye(),n=new i,n.open("get",a);let j=0,le,xe=0;const Qe=()=>(k(u),Math.max(u,Math.max(le||0,xe||0)));if(r&&n.addEventListener("progress",I=>{const X=ye();r.updateChunk&&I.loaded>j&&(r.updateChunk(Qe(),I.loaded-j),j=I.loaded,le=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(c)return;k(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&r){const X=n.response.byteLength-j;X&&r.updateChunk&&r.updateChunk(Qe(),X)}h&&h(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),f){const I=()=>{k(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(xe=ye(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=S,n.send(),ne},ne={withBitrateReporting:P,withParallel:v,withJSONResponse:Z,withRetryCount:j=>(d=j,ne),withRetryInterval:(j,le)=>(A(j)&&(m=j),A(le)&&(p=le),ne),withTimeout:j=>(o=j,ne),withFinally:x,send:F,abort:()=>{n&&(n.abort(),n=void 0),c=!0,h&&h()}};return ne}const Fi=100,Hi=2e3,qi=500;let Yi=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,s){return{start:e,end:t,bytes:s}}_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-qi;if(t-e>Hi){let s=0,i=0;for(;this.intervals.length>0;){const r=this.intervals[0];if(r.end<=t)s+=r.end-r.start,i+=r.bytes,this.intervals.splice(0,1);else{if(r.start>=t)break;{const n=t-r.start,o=r.end-r.start;s+=n;const c=r.bytes*n/o;i+=c,r.start=t,r.bytes-=c}}}if(i>0&&s>0){const r=i*8/(s/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(i)}/${Math.round(s)} 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,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>Fi&&(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 Gi{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,i,r){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,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 s=ye(),i=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()-s,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=Vt(t,r,()=>i("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 s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!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,s,i){const r={};return r.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=i,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}`),s(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=s,r._retryCB=i,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 Nt=1e4,Mt=3,zi=300,Wi=2e3,Qi=6e4,ji=10,Ji=1,Ki=500;class Xi{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 Yi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hs(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],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=hs(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 s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-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",()=>{Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.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,s=t.buffered.length;let i;s!==0&&(i=t.buffered.start(s-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){const{videoElement:t}=this.params;let s,i,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)?(!i||r.bitrate>i.bitrate)&&(i=r):(!s||s.bitrate>r.bitrate)&&(s=r));return i||s}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:s,videoElement:i,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{Vi(i,"progress",()=>{i.buffered.length?(i.currentTime=i.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 Gi(Mt,Nt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:i}=this.params;let r=!1,n=null,o=null,c=null,d=null,u=!1;const h=()=>{const $=r&&(!u||u===this.rep);return $||t("Not running!"),$},f=($,v,F)=>{c&&c.abort(),c=Vt(this.urlResolver.resolve($,!1),v,F,()=>this._retryCallback()).withTimeout(Nt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mt).withFinally(()=>{c=null}).send()},S=($,v,F)=>{k(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),v,F,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},p=$=>{const v=s.playbackRate;s.playbackRate!==$&&(t(`Playback rate switch: ${v}=>${$}`),s.playbackRate=$)},m=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)p(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}const F=ye()-1e4;let H=0;for(let q=0;q<this.bufferStates.length;q++){const J=this.bufferStates[q];$=Math.min($,J.buf),J.ts<F&&H++}this.bufferStates.splice(0,H),t(`update playback rate; minBuffer=${$} drop=${H} jitter=${this.sourceJitter}`);let ie=$-Ji;this.sourceJitter>=0?ie-=this.sourceJitter/2:this.sourceJitter-=1,ie>3?p(1.15):ie>1?p(1.1):ie>.3?p(1.05):p(1)}},P=$=>{let v;const F=()=>v&&v.start?v.start.length:0,H=I=>v.start[I]/1e3,ie=I=>v.dur[I]/1e3,q=I=>v.fragIndex+I,J=(I,X)=>({chunkIdx:q(I),startTS:H(I),dur:ie(I),discontinuity:X}),ne=()=>{let I=0;if(v&&v.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,he=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,me=X;this.sourceJitter>1&&(me+=this.sourceJitter-1);let Ee=v.dur.length-1;for(;Ee>=0&&(me-=v.dur[Ee],!(me<=0));--Ee);I=Math.min(Ee,v.dur.length-1-he),I=Math.max(I,0)}return J(I,!0)},j=I=>{const X=F();if(!(X<=0)){if(A(I)){for(let he=0;he<X;he++)if(H(he)>I)return J(he)}return ne()}},le=I=>{const X=F(),he=I?I.chunkIdx+1:0,me=he-v.fragIndex;if(!(X<=0)){if(!I||me<0||me-X>ji)return t(`Resync: offset=${me} bChunks=${X} chunk=`+JSON.stringify(I)),ne();if(!(me>=X))return J(he-v.fragIndex,!1)}},xe=(I,X,he)=>{d&&d.abort(),d=Vt(this.urlResolver.resolve(I,!0,this.lowLatency),X,he,()=>this._retryCallback()).withTimeout(Nt).withRetryCount(Mt).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,X)=>{xe($,he=>{if(!h())return;v=he;const me=Boolean(v.lowLatency);me!==this.lowLatency&&m(me);let Ee=0;for(let je=0;je<v.dur.length;++je)Ee+=v.dur[je];Ee>0&&(k(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/v.dur.length)),i({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,I(j(X))},()=>this._handleNetworkError())},nextChunk:le}},x=()=>{r=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),k(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:$=>{const{videoElement:v,logger:F}=this.params;let H=P(e.jidxUrl),ie,q,J,ne,j=0,le,xe,Qe;const I=()=>{le&&(clearTimeout(le),le=void 0);const Y=Math.max(Ki,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=j+Y,Se=ye(),be=Math.min(1e4,ge-Se);j=Se;const Oe=()=>{d||h()&&H.seek(()=>{h()&&(j=ye(),X(),I())})};be>0?le=window.setTimeout(()=>{this.paused?I():Oe()},be):Oe()},X=()=>{let Y;for(;Y=H.nextChunk(ne);)ne=Y,bt(Y);const ge=H.nextChunk(J);if(ge){if(J&&ge.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?I():(x(),this._initPlayerWith(e));return}je(ge)}else I()},he=(Y,ge)=>{if(!h()||!this.sourceBuffer)return;let Se,be,Oe;const Ue=Ie=>{window.setTimeout(()=>{h()&&he(Y,ge)},Ie)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),Ue(100);else{const Ie=ye(),Je=v.currentTime;!this.paused&&v.buffered.length>1&&xe===Je&&Ie-Qe>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),xe!==Je&&(xe=Je,Qe=Ie);const Ke=this._getBufferSizeSec();if(Ke>30)F(`Buffered ${Ke} seconds; delaying appendBuffer`),Ue(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Ie,buf:Ke}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Xe){if(Xe.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Oe=this.sourceBuffer.buffered.length,Oe!==0&&(Se=this.sourceBuffer.buffered.start(0),be=Je,be-Se>4&&this.sourceBuffer.remove(Se,be-3)),Ue(1e3);else throw Xe}}},me=()=>{q&&ie&&(F([`Appending chunk, sz=${q.byteLength}:`,JSON.stringify(J)]),he(q,function(){q=null,X()}))},Ee=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),je=Y=>{h()&&S(Ee(Y),(ge,Se)=>{if(h()){if(Se/=1e3,q=ge,J=Y,n=Y.startTS,Se){const be=Math.min(10,Y.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}me()}},()=>this._handleNetworkError())},bt=Y=>{h()&&(k(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(Y),!1)))},xt=Y=>{h()&&(e.cachedHeader=Y,he(Y,()=>{ie=!0,me()}))};r=!0,H.seek(Y=>{if(h()){if(j=ye(),!Y){I();return}ne=Y,!W($)||Y.startTS>$?je(Y):(J=Y,X())}},$),e.cachedHeader?xt(e.cachedHeader):f(e.headerUrl,xt,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>n},u}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),A(i)&&(i+=.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,k(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return A(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,S,p;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(S=this._getBufferSizeSec(),p=h/this.bitrate,S>10&&p>.8||S>15&&p>.5||S>20&&p>.3)){e(`Not switching: buffer=${Math.floor(S)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},r=(()=>({updateChunk:(f,S)=>{const p=ye();if(this.chunkRateEstimator.addInterval(f,p,S)){const y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:S,duration:p-f,speed:y}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let h=r.get();if(h&&o&&this.autoQuality){if(c&&h>o&&Us(n)<3e4)return;s(h)}c=this.autoQuality};return{updateChunk:(h,f)=>{const S=r.updateChunk(h,f);return S&&d(),S},notifySwitch:h=>{const f=ye();h<o&&(n=f),o=h}}}_fetchManifest(e,t,s){this.manifestRequest=Vt(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Nt).withRetryCount(Mt).withRetryInterval(zi,Wi).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;tt(t).then(s=>{s||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params,r=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&i.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}`),s({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))},Qi))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var V;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(V||(V={}));const Zi=[V.PAUSED,V.PLAYING,V.READY],ea=[V.PAUSED,V.PLAYING,V.READY];class ta{subscription=new K;video;videoState=new re(V.STOPPED);dash;representations$=new b([]);textTracksManager=new Me;maxSeekBackTime$=new b(1/0);zeroTime$=new b(void 0);liveOffset=new ss;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=i=>{e.output.error$.next({id:"DashLiveProvider",category:D.WTF,message:"DashLiveProvider internal logic error",thrown:i})};C(this.videoState.stateChangeStarted$.pipe(E(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(E(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(i)}`})}),this.video=ze(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.hostname$.next(ve(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 s=We(this.video);this.subscription.add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(V.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ue(),E(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Ye({zeroTime:this.zeroTime$.pipe(O(A)),position:s.timeUpdate$}).subscribe(({zeroTime:i,position:r})=>this.params.output.liveTime$.next(i+r*1e3),t)).add(ct(this.video,this.params.desiredState.isLooped,t)).add(Ge(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(et(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:i}})=>{const r=i&&pi(i);this.dash.setMaxAutoQuality(r)})).add(this.videoState.stateChangeEnded$.subscribe(i=>{switch(i.to){case V.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case V.MANIFEST_READY:case V.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case V.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case V.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return L(i.to)}},t)).add(C(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Xi({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(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),i=!s&&A(t)?t:It(e.map(({track:n})=>n),{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()})?.id,r=e.find(({track:n})=>n.id===i)?.representation;k(r,"Representations missing"),this.dash.startPlay(r,s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(s)}setVideoTrack(e){const t=this.representations$.getValue().find(({track:s})=>s.id===e)?.representation;k(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=-e,s=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(s),this.dash.reinit(pt(this.params.source.url,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:D.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,s=[];for(const i of t){const r=i.name??i.index.toString(10),n=Ct(i.name)??dt(i.video),o=i.bitrate/1e3,c={...i.video};if(!n)continue;const d={id:r,quality:n,bitrate:o,size:c};s.push({track:d,representation:i})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map(({track:i})=>i)),this.videoState.getTransition()?.to===V.MANIFEST_READY&&this.videoState.setState(V.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,s=this.representations$.getValue().find(({representation:i})=>i===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),A(s)&&this.params.output.currentVideoTrack$.next(s);break}case"bandwidth":{const{size:t,duration:s}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,s);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(r)};`}),s===l.STOPPED){e!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(V.STOPPED));return}if(!t){if(ea.includes(e)){const n=this.params.desiredState.videoTrack.getTransition()?.to;A(n)&&this.setVideoTrack(n);const o=this.params.desiredState.autoVideoTrackSwitching.getTransition();o&&this.setAutoQuality(o.to)}if(i?.to!==l.PAUSED&&r.state===N.Requested&&Zi.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case V.STOPPED:this.videoState.startTransitionTo(V.MANIFEST_READY),this.dash.attachSource(pt(this.params.source.url));return;case V.MANIFEST_READY:this.videoState.startTransitionTo(V.READY),this.prepare();break;case V.READY:if(s===l.PAUSED)this.videoState.setState(V.PAUSED);else if(s===l.PLAYING){this.videoState.startTransitionTo(V.PLAYING);const n=i?.from;n&&n===l.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(V.PAUSED)})}return;case V.PLAYING:s===l.PAUSED&&(this.videoState.startTransitionTo(V.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case V.PAUSED:s===l.PLAYING&&(this.videoState.startTransitionTo(V.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(V.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return L(e)}}}}var Vs=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),s=e===null?Dt.HTTP1:e??void 0,i=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:s,reused:i}},at=(a,e)=>{let t=0;for(let s=0;s<a.length;s++){const i=a.start(s)*1e3,r=a.end(s)*1e3;i<=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},ia=a=>{const e=document.createElement("a");return e.href=a,e.host};class Fs{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,i,r,n){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=i,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(k(this._xhr),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(s=>s.split(":").map(i=>i.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(ia(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 Yt{_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(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const i=this._sourceBuffer.buffered;let r=0;for(let n=0,o=i.length;n<o;n++)r+=i.end(n)-i.start(n);r&&(this._maxBufferDuration=Math.round(r))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,i,r,n,o){this.abort(()=>{let c=0;const d=Date.now();let u=0,h=0,f=0;const S=m=>{i(Yt._str2ua(m.substr(c))),c=m.length};let p=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(p=St(p)),this._lastXhr=new Fs(p,e.failoverHosts,m=>{this._lastXhr=void 0,S(m);const y=Date.now()-d;this._params.onBandwidthChange({size:m.length,duration:y,speed:8*m.length/(y/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),r?.()},m=>{if(m.length-c>o&&S(m),h===0){h=Date.now();return}f=m.length-u;const y=Date.now()-h;f>=100*1024&&y>=1e3&&(this._params.onBandwidthChange({size:f,duration:y,speed:8*f/(y/1e3)}),f=0,u=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},n,(m,y,P)=>this._params.onError(m,y,P))})}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(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};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=Yt._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 s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);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)?)?$/,s=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},i=t.exec(e),r=i?.[1]==="-"?-1:1,n={years:s(i?.[2],r),months:s(i?.[3],r),weeks:s(i?.[4],r),days:s(i?.[5],r),hours:s(i?.[6],r),minutes:s(i?.[7],r),seconds:s(i?.[8],r)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=St(s)),new Fs(s,t,i=>{this.attachManifest(i,t,sa(s))},void 0,i=>{this._params.onResponseHeaders(i)},(i,r,n)=>this._params.onError(i,r,n))}attachManifest(e,t,s){const r=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,u)=>{const h=d.attributes.getNamedItem(u);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(n(r,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(r.getElementsByTagName("Representation"),d=>{const u=d.getElementsByTagName("SegmentBase")[0],h=u&&n(u,"indexRange").split("-"),f=u&&u.getElementsByTagName("Initialization")[0],S=f&&n(f,"range").split("-");if(!S||!h){const Z=d.parentElement;if(Z?.getAttribute("contentType")==="text"){const $=d.getAttribute("id")??void 0,v=(s?s+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,F=Z.getAttribute("lang")??void 0;v&&c.push({id:$,url:v,language:F})}return}const p=.1,m=Number(d.attributes.getNamedItem("bandwidth")?.value),y=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let P;const x=d.attributes.getNamedItem("frameRate")?.value??void 0;P=x?is(x):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:m,baseURL:y,failoverHosts:t,indexFrom:Number(h[0]),indexTo:Number(h[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:P,bufferSize:p*m/8,bufferLength:p,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:u,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),d&&f.setAttribute("id",d),u&&f.setAttribute("srclang",u),this._video.appendChild(f)}),this._representations.sort((d,u)=>u.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,i=>{let r=e.initTo-e.initFrom+1;if(!i.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(i.buffer,0,r);const n=new DataView(i.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 u=n.getUint16(r+2,!1);r+=4,e.refs=[];for(let f=0;f<u;f+=1){const S=d+(n.getUint32(r,!1)&2147483647),p=c+n.getUint32(r+4,!1);r+=12,e.refs.push({fromTime:c/o,toTime:p/o,fromOffset:d,toOffset:S-1}),d=S,c=p}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,i=>{this._params.onResponseHeaders(i),this._params.onIdxRequestPing(Date.now()-s)},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 s=new t;let i,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 u=this._appendVector[String(d.fromTime)];u!==i&&(i=u,this._params.onRepresentationPlay(u));let h;if(this._findRef(d.toTime)){const S=this._buffer.getByTime(this._video.currentTime);if(!S){this._onDashCallback("buffering");return}h=S.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),r!==S.to&&(r=S.to,window.setTimeout(()=>{try{const p=this._buffer.getNextWithGap(S);p&&(this._video.currentTime=p.from)}catch(p){throw this._params.onError("GapSyncError",`Seek Error ${String(p)}`,p),p}},h*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=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Yt({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",c),s.removeEventListener("webkitsourceopen",c)};s.addEventListener("sourceopen",c,!1),s.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1,i=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const r=this._findRef(t);if(r){if(s){this._isLastRef(r)&&t>=r.toTime&&(t=r.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=i||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 s=this._buffer.getByTime(this._video.currentTime),i=this._findRef(this._video.currentTime);if(!s||!i){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const r=.1;if(i.toTime<s.to+r){const n=this._findRef(i.toTime);n&&n.toTime<s.to+r?(this._buffer.smartRemove(i.fromTime-r,n.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(i.fromTime-r,i.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,i.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||W(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 s;for(let i=0;i<t.length;i++){const r=t[i];if(r.fromTime<=e&&r.toTime>e)return r;r.fromTime>e&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const i=t[t.length-1];if(e>i.toTime)return i}return s}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const s=t[t.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),i=this._video.buffered.end(t);if(e>s&&e<i)return Math.round(i*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var G;(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"})(G||(G={}));const ra=[G.PAUSED,G.PLAYING];class na{videoState=new re(G.STOPPED);subscription=new K;video;buffer;dash;representations$=new b([]);currentRepresentation$=new b(void 0);params;textTracksManager=new Me;elementSize$=new b(void 0);dashLiteEvents={idxRequestPing$:new _,responseHeaders$:new _,manifestReady$:new _,representationPlay$:new _,error$:new _};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),C(this.videoState.stateChangeStarted$.pipe(E(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(E(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=ze(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(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Di(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:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:i,category:D.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,s=o=>{e.error$.next({id:"DashProvider",category:D.WTF,message:"DashProvider internal logic error",thrown:o})},i=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},r=We(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,s));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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(r.seeking$.subscribe(()=>{W(this.params.desiredState.seekState.getState().state!==N.Applying)&&(this.videoState.getState()===G.PLAYING||this.videoState.getState()===G.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(ct(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(qt(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)})).add(r.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,l.PLAYING)},s)).add(r.loadedMetadata$.subscribe(()=>{this.videoState.setState(G.METADATA_LOADED)},s)).add(r.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe(E(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:D.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(C(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,B(this.video,"progress")).pipe(E(()=>{const o=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.videoTrack.getState(),h=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),S=i();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let p;if(!S&&A(u))p=u;else{const m=at(this.video.buffered,this.video.currentTime*1e3),y=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,P=Math.min(m/y,1);p=It(c.map(({track:x})=>x),{container:f,throughput:h,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:P,playbackRate:this.video.playbackRate,current:c.find(({representation:x})=>x===o)?.track})?.id}return A(p)?c.find(({track:m})=>m.id===p)?.representation:void 0}),ue()).subscribe(this.currentRepresentation$,s)).add(Ye({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(O(o=>o.to===G.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(O(A))}).pipe(pe()).subscribe(()=>this.videoState.setState(G.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(O(A),ue((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&i()?o.height<=c.height:o===c)).subscribe(o=>{const c=at(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!i())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(ve(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=Vs(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(pe(),ot(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,s)).add(this.dashLiteEvents.representationPlay$.pipe(O(A)).subscribe(this.handleRepresentationPlay,s)).add(C(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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 L(e)}}handleManifestReady=e=>{const t=[];for(const s of e){const i=s.name??s.id??s.height.toString(10),r=(s.name&&Ct(s.name))??dt(s),n=s.bandwidth/1e3,o={width:s.width,height:s.height},c=s.fps;if(!r)continue;const d={id:i,quality:r,bitrate:n,size:o,fps:c};t.push({track:d,representation:s})}this.representations$.next(t),this.params.output.availableVideoTracks$.next(t.map(({track:s})=>s)),this.videoState.setState(G.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:s})=>s===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 k(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(){tt(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(r)};`}),s===l.STOPPED){e!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.dash.destroy(),this.video.setAttribute("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(G.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(!t)switch(i?.to!==l.PAUSED&&r.state===N.Requested&&ra.includes(e)&&this.seek(r.position,r.forcePrecise),e){case G.STOPPED:this.videoState.startTransitionTo(G.MANIFEST_LOADED),this.prepare();return;case G.MANIFEST_LOADED:this.videoState.startTransitionTo(G.INITIAL_REPRESENTATION_SELECTED);return;case G.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(G.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case G.METADATA_LOADED:this.videoState.startTransitionTo(G.READY),this.dash.updateRefsForCurrentTime();return;case G.READY:s===l.READY?w(this.params.desiredState.playbackState,l.READY):s===l.PAUSED?(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)):s===l.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:s===l.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.video.pause()):i?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case G.PAUSED:s===l.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;default:return L(e)}}}var Pe;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Pe||(Pe={}));var Gt;(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"})(Gt||(Gt={}));var Re;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Re||(Re={}));var Q;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(Q||(Q={}));var gt;(function(a){a.MP4="mp4",a.WEBM="webm"})(gt||(gt={}));var es=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const oa=(a,e={})=>{const s=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},da=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ls=da?oa:window.requestIdleCallback;let Hs=!1;try{Hs=Ms()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class ca{bufferFull$=new _;error$=new _;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(s=>{const i={operation:"append",data:e,signal:t,callback:s};this.queue.push(i),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(i=>{const r={operation:"remove",from:e,to:t,signal:s,callback:i};this.queue.unshift(r),this.pull()})}async abort(e){return new Promise(t=>{let s;Hs&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:i}of this.queue)i(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}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:D.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(i){i instanceof DOMException&&i.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):i instanceof DOMException&&i.name==="InvalidStateError"&&t==="remove"||this.error$.next({id:`BufferTaskQueue:${t}`,category:D.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:i}),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:L(t)}}}var fs=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};const qs=new TextDecoder("ascii"),Ys=a=>{let e=0,t=a.getUint32(e);e+=4;const s=new DataView(a.buffer,a.byteOffset+e,4),i=qs.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const r=Math.min(t,a.byteLength)-e,n=new DataView(a.buffer,a.byteOffset+e,r);return{id:i,size:t,contents:n}},ua=a=>qs.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ha=(a,e,t)=>{const s=Ys(a),i=[];let r=0;const n=()=>{const m=s.contents.getUint32(r);return r+=4,m};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),u=n(),h=n(),f=n()&4294967295;let S=u/d*1e3,p=(t?t.to+1:a.byteOffset+a.byteLength)+h;for(let m=0;m<f;m++){const y=n(),P=y>>>31,x=y<<1>>>1,Z=n();if(n(),P!==0)throw new Error("Unsupported multilevel sidx");const $=Z/d*1e3;i.push({status:Q.NONE,time:{from:S,to:S+$},byte:{from:p,to:p+x-1}}),S+=$,p+=x}return i},la=a=>{let e=0,t=!1,s=!1;for(;e<=a.byteLength&&!t;){const i=new DataView(a.buffer,a.byteOffset+e);try{const r=Ys(i);if(s||=r.id==="mdat",e+r.size<=a.byteLength)e+=r.size;else break}catch{t=!0}}return e>0&&e<=a.byteLength&&s?new DataView(a.buffer,a.byteOffset,e):null},fa={validateData:ua,parseInit:()=>null,getIndexRange:()=>{},parseSegments:ha,parseFeedableSegmentChunk:la};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.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 R;(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"})(R||(R={}));const ps={[T.EBML]:{type:R.Master},[T.EBMLVersion]:{type:R.UnsignedInteger},[T.EBMLReadVersion]:{type:R.UnsignedInteger},[T.EBMLMaxIDLength]:{type:R.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:R.UnsignedInteger},[T.DocType]:{type:R.String},[T.DocTypeVersion]:{type:R.UnsignedInteger},[T.DocTypeReadVersion]:{type:R.UnsignedInteger},[T.Void]:{type:R.Binary},[T.Segment]:{type:R.Master},[T.SeekHead]:{type:R.Master},[T.Seek]:{type:R.Master},[T.SeekID]:{type:R.Binary},[T.SeekPosition]:{type:R.UnsignedInteger},[T.Info]:{type:R.Master},[T.TimestampScale]:{type:R.UnsignedInteger},[T.Duration]:{type:R.Float},[T.Tracks]:{type:R.Master},[T.Chapters]:{type:R.Master},[T.Cluster]:{type:R.Master},[T.Timestamp]:{type:R.UnsignedInteger},[T.SilentTracks]:{type:R.Master},[T.SilentTrackNumber]:{type:R.UnsignedInteger},[T.Position]:{type:R.UnsignedInteger},[T.PrevSize]:{type:R.UnsignedInteger},[T.SimpleBlock]:{type:R.Binary},[T.BlockGroup]:{type:R.Master},[T.EncryptedBlock]:{type:R.Binary},[T.Attachments]:{type:R.Master},[T.Tags]:{type:R.Master},[T.Cues]:{type:R.Master},[T.CuePoint]:{type:R.Master},[T.CueTime]:{type:R.UnsignedInteger},[T.CueTrackPositions]:{type:R.Master},[T.CueTrack]:{type:R.UnsignedInteger},[T.CueClusterPosition]:{type:R.UnsignedInteger},[T.CueRelativePosition]:{type:R.UnsignedInteger},[T.CueDuration]:{type:R.UnsignedInteger},[T.CueBlockNumber]:{type:R.UnsignedInteger},[T.CueCodecState]:{type:R.UnsignedInteger},[T.CueReference]:{type:R.Master},[T.CueRefTime]:{type:R.UnsignedInteger}},Gs=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 s=zt(a,t),i=s in ps,r=i?ps[s].type:R.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,u=zt(c),h=d*2**((o-1)*8)+u,f=t+o;let S;return f+h>a.byteLength?S=new DataView(a.buffer,a.byteOffset+f):S=new DataView(a.buffer,a.byteOffset+f,h),{tag:i?s:"0x"+s.toString(16).toUpperCase(),type:r,tagHeaderSize:f,tagSize:f+h,value:S,valueSize:h}},zt=(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 R.SignedInteger:return a.getInt8(0);case R.UnsignedInteger:return zt(a);case R.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case R.String:return new TextDecoder("ascii").decode(a);case R.UTF8:return new TextDecoder("utf-8").decode(a);case R.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case R.Master:return a;case R.Binary:return a;default:L(e)}},Lt=(a,e)=>{let t=0;for(;t<a.byteLength;){const s=new DataView(a.buffer,a.byteOffset+t),i=Gs(s);if(!e(i))return;i.type===R.Master&&Lt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},pa=a=>{if(a.getUint32(0)!==T.EBML)return!1;let e,t,s;const i=Gs(a);return Lt(i.value,({tag:r,type:n,value:o})=>(r===T.EBMLReadVersion?e=qe(o,n):r===T.DocType?t=qe(o,n):r===T.DocTypeReadVersion&&(s=qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},zs=[T.Info,T.SeekHead,T.Tracks,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],ma=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],Sa=a=>{let e,t,s,i,r=!1,n=!1,o=!1,c,d;return Lt(a,({tag:u,type:h,value:f,valueSize:S})=>{if(u===T.SeekID){const p=qe(f,h);d=zt(p)}else u!==T.SeekPosition&&(d=void 0);return u===T.Segment?(e=f.byteOffset,t=f.byteOffset+S):u===T.Info?r=!0:u===T.SeekHead?n=!0:u===T.TimestampScale?s=qe(f,h):u===T.Duration?i=qe(f,h):u===T.SeekPosition&&d===T.Cues?c=qe(f,h):r&&n&&zs.includes(u)&&(o=!0),!o}),k(e,"Failed to parse webm Segment start"),k(t,"Failed to parse webm Segment end"),k(i,"Failed to parse webm Segment duration"),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(i/1e9*s*1e3),cuesSeekPosition:c}},ga=a=>{if(W(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ba=(a,e)=>{let t=!1,s=!1;const i=o=>A(o.time)&&A(o.position),r=[];let n;return Lt(a,({tag:o,type:c,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&i(n)&&r.push(n),n={};break;case T.CueTime:n&&(n.time=qe(d,c));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=qe(d,c));break;default:t&&zs.includes(o)&&(s=!0)}return!(t&&s)}),n&&i(n)&&r.push(n),r.map((o,c)=>{const{time:d,position:u}=o,h=r[c+1];return{status:Q.NONE,time:{from:d,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+u,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},ya=a=>{let e=0,t=!1;try{Lt(a,s=>s.tag===T.Cluster?s.tagSize<=a.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):ma.includes(s.tag)?(e+s.tagSize<=a.byteLength&&(e+=s.tagSize,t||=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Ta={validateData:pa,parseInit:Sa,getIndexRange:ga,parseSegments:ba,parseFeedableSegmentChunk:ya};class ms{onLastSegment$=new b(!1);fullyBuffered$=new b(!1);playingRepresentation$=new b(void 0);error$=new _;gaps=[];subscription=new K;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new rt;destroyAbortController=new rt;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;constructor(e,t,s,i,{fetcher:r,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1}){switch(this.fetcher=r,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case gt.MP4:this.containerParser=fa;break;case gt.WEBM:this.containerParser=Ta;break;default:L(s)}this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=Ce(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);k(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ca(this.sourceBuffer),this.subscription.add(B(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:D.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(B(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:D.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,fs(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 s=this.initData.get(t.id),i=this.segments.get(t.id);if(k(s,"No init buffer for starting representation"),k(i,"No segments for starting representation"),!(s instanceof ArrayBuffer))return;let r=0;for(const n of i)n.time.from-r>0&&this.gaps.push({representation:t.id,from:r,to:n.time.from}),r=n.time.to;A(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=Ce(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);k(t,`No such representation ${e}`);let s=this.initData.get(e);if(W(s)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),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 i=this.getCurrentPosition();A(i)&&this.maintain(i)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new rt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(W(e)||W(this.downloadingRepresentationId)||W(this.playingRepresentationId)||W(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(k(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const i=s.find(d=>e>=d.time.from&&e<d.time.to);let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=at(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&u>=i.time.to-e+100&&(r=h)}if(isFinite(this.bufferLimit)&&fs(this.sourceBuffer.buffered)>=this.bufferLimit){const d=at(this.sourceBuffer.buffered,e),u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<u);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,r),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{const u=o.at(0);u&&u.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status===Q.FED&&!o.length&&at(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=s.at(-1);c&&c.status===Q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(i===c))}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const s=this.segments.get(t);return s?s.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(){this.initData.clear(),this.segments.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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const i=e.findIndex(({status:h,time:{from:f,to:S}},p)=>{const m=f<=s&&S>=s,y=f>s||m||p===0&&s===0,P=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&f<=s+P||S<=s+P;return(h===Q.NONE||h===Q.PARTIALLY_EJECTED&&y&&x&&this.sourceBuffer&&!es(this.sourceBuffer.buffered,s))&&y&&x});if(i===-1)return[];if(t!==Re.BYTE_RANGE)return e.slice(i,i+1);const r=e;let n=0,o=0;const c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,u=this.preloadOnly?this.forwardBufferTarget:0;for(let h=i;h<r.length&&(n<=d||o<=u);h++){const f=r[h];if(n+=f.byte.to+1-f.byte.from,o+=f.time.to+1-f.time.from,f.status===Q.NONE||f.status===Q.PARTIALLY_EJECTED)c.push(f);else break}return c}async loadSegments(e,t,s="auto"){if(!e.length)return;let i,r,n=e;const{type:o}=t.segmentReference;switch(o){case Re.BYTE_RANGE:{i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Re.TEMPLATE:{const d=e.at(0);i=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:L(o)}for(const d of n)d.status=Q.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await Ce(c,async function*(){const d=os(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,d))}.bind(this))(),c.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(i,{range:r,onProgress:(d,u)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,r?r.from:0,u,c)}catch(h){this.error$.next({id:"SegmentFeeding",category:D.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:c,priority:s}).then(()=>this.failedDownloads=0,d=>{for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);this.onSegmentDownloadError(d)})}onSegmentDownloadError(e){let t=!1;const s=this.getCurrentPosition();this.sourceBuffer&&A(s)&&(t=at(this.sourceBuffer?.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:D.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,i,r){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=h=>{this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=Q.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const S of this.segments.get(f.id)??[])S.status===Q.FED&&S.time.from===h.segment.time.from&&S.time.to===h.segment.time.to&&(S.status=Q.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},c=this.representations.get(t);if(!c)return;const d=c.segmentReference.type,u=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,S=d===Re.BYTE_RANGE,p=S?f.byte.to-f.byte.from+1:u;if(h.representationId!==t||!(!S||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(r.aborted){n();continue}const y=S?f.byte.from-s:0,P=S?f.byte.to-s:e.byteLength,x=y<i,Z=P<=i;if(f.status===Q.DOWNLOADING&&x&&Z){f.status=Q.DOWNLOADED,this.activeSegments.delete(h);const $=new DataView(e.buffer,e.byteOffset+y,p);this.sourceBufferTaskQueue.append($,r).then(v=>v&&!r.aborted?o(h):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&x&&(h.loadedBytes=Math.min(p,i-y),h.loadedBytes>h.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+y+h.feedingBytes,h.loadedBytes-h.feedingBytes),v=h.loadedBytes===p?$:this.containerParser.parseFeedableSegmentChunk($);v?.byteLength&&(f.status=Q.PARTIALLY_FED,h.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,r).then(F=>{if(r.aborted)n();else if(F)h.fedBytes+=v.byteLength,h.fedBytes===p&&o(h);else{if(h.feedingBytes<p)return;n()}}))}}}abortSegment(e){e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[i,r]of this.initData.entries()){const n=r instanceof Promise;t||=n,r===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=ls(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?Ce(this.destroyAbortController.signal,async function*(){const o=os(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,i)).then(o=>{if(!o)return;const{dataView:c,segments:d}=o,u=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,u),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:D.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||W(e)||this.sourceBuffer.updating)return!1;let i=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 u="size"in d?d.size??0:d.byte.to-d.byte.from;i+=u};for(const d of this.segments.values())for(const u of d){if(u.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;u.status===Q.FED&&c(u)}if(o=isFinite(r)&&isFinite(n),!o){i=0,r=1/0,n=-1/0;for(const d of this.segments.values())for(const u of d){if(u.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;u.status===Q.FED&&c(u)}}if(o=isFinite(r)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const u=this.sourceBuffer.buffered.start(d)*1e3,h=this.sourceBuffer.buffered.end(d)*1e3;for(const f of this.segments.values())for(const S of f)if(S.status===Q.NONE&&Math.round(S.time.from)<=Math.round(u)&&Math.round(S.time.to)>=Math.round(h)){r=u,n=h;break}}if(o=isFinite(r)&&isFinite(n),!o&&s){i=0,r=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const u of this.segments.values())for(const h of u)h.time.from>e+d&&h.status===Q.FED&&c(h)}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)}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let i={representation:e,from:s.time.from,to:s.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<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){i=void 0;break}o>s.time.from&&o<s.time.to&&(i.from=o),n<s.time.to&&n>s.time.from&&(i.to=n)}}i&&i.to-i.from>=1&&!this.gaps.some(r=>i&&r.from===i.from&&r.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ls(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:D.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(W(this.sourceBuffer)||W(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const i=Math.round(this.sourceBuffer.buffered.start(s)*1e3),r=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:i,to:r})}const t=1;for(const s of this.segments.values())for(const i of s){const{status:r}=i;if(r!==Q.FED&&r!==Q.PARTIALLY_EJECTED)continue;const n=Math.floor(i.time.from),o=Math.ceil(i.time.to),c=e.some(u=>u.from-t<=n&&u.to+t>=o),d=e.filter(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);c||(d.length===1?i.status=Q.PARTIALLY_EJECTED:i.status=Q.NONE)}}}var lt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(lt||(lt={}));class Ea{throughputEstimator;requestQuic;lastConnectionType$=new b(void 0);lastConnectionReused$=new b(void 0);lastRequestFirstBytes$=new b(void 0);abortAllController=new rt;subscription=new K;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Vs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=Ce(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=St(t));const s=yield mt(t,{signal:this.abortAllController.signal}).catch($t);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=Ce(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?lt.HEADER:lt.PARAM,range:s,onProgress:i,priority:r="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(s)switch(t){case lt.HEADER:{d.append("Range",`bytes=${s.from}-${s.to}`);break}case lt.PARAM:{const q=new URL(c,location.href);q.searchParams.append("bytes",`${s.from}-${s.to}`),c=q.toString();break}default:L(t)}this.requestQuic&&(c=St(c));let u=this.abortAllController.signal;if(n){const q=new rt;if(this.subscription.add(C(B(this.abortAllController.signal,"abort"),B(n,"abort")).subscribe(()=>{try{q.abort()}catch(J){$t(J)}})),this.abortAllController.signal.aborted||n.aborted)try{q.abort()}catch(J){$t(J)}u=q.signal}const h=ce(),f=yield mt(c,{priority:r,headers:d,signal:u}).catch($t),S=ce();if(this.throughputEstimator?.addRawRtt(S-h),!f)return null;if(!f.ok||!f.body)return Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const p=parseInt(f.headers.get("Content-Length")??"",10)||s&&s.to-s.from+1||NaN;if(!p){const q=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(q.byteLength,ce()-S),i?.(new DataView(q),q.byteLength),q}if(!i&&!o)return f.arrayBuffer();const[m,y]=f.body.tee(),P=m.getReader();o&&this.throughputEstimator?.trackStream(y);let x=0;const Z=new ArrayBuffer(p),$=new Uint8Array(Z),v=new DataView(Z);let F=!1;const H=q=>{F=!0,$t(q)},ie=Ce(u,async function*({done:q,value:J}){x===0&&this.lastRequestFirstBytes$.next(ce()-h),!u.aborted&&(q?i?.(v,x):J&&($.set(J,x),x+=J.byteLength,i?.(v,x),yield P?.read().then(ie,H)))}.bind(this));return yield P?.read().then(ie,H),F?null:Z}.bind(this));async fetchRepresentation(e,t,s="auto"){const{type:i}=e;switch(i){case Re.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case Re.TEMPLATE:return await this.fetchTemplateRepresentation(e,s)??null;default:L(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=Ce(this.abortAllController.signal,async function*(e,t,s){if(e.type!==Re.BYTE_RANGE)return null;const{from:i,to:r}=e.initRange;let n=i,o=r,c=!1,d,u;e.indexRange&&(d=e.indexRange.from,u=e.indexRange.to,c=r+1===d,c&&(n=Math.min(d,i),o=Math.max(u,r))),n=Math.min(n,0);const h=yield this.fetch(e.url,{range:{from:n,to:o},priority:s,measureThroughput:!1});if(!h)return null;const f=new DataView(h,i-n,r-n+1);if(!t.validateData(f))throw new Error("Invalid media file");const S=t.parseInit(f),p=e.indexRange??t.getIndexRange(S);if(!p)throw new ReferenceError("No way to load representation index");let m;if(c)m=new DataView(h,p.from-n,p.to-p.from+1);else{const P=yield this.fetch(e.url,{range:p,priority:s,measureThroughput:!1});if(!P)return null;m=new DataView(P)}const y=t.parseSegments(m,S,p);return{dataView:new DataView(h),segments:y}}.bind(this));fetchTemplateRepresentation=Ce(this.abortAllController.signal,async function*(e,t){if(e.type!==Re.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(s,{priority:t,measureThroughput:!1});return i?{segments:e.segments.map(n=>({...n,status:Q.NONE,size:void 0})),dataView:new DataView(i)}:null}.bind(this))}const $t=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},Ss=a=>{if(!a.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},s=/^(-|\+)?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),i=s?.[1]==="-"?-1:1,r={days:e(s?.[5],i),hours:e(s?.[6],i),minutes:e(s?.[7],i),seconds:e(s?.[8],i)};return r.days*24*60*60*1e3+r.hours*60*60*1e3+r.minutes*60*1e3+r.seconds*1e3},Jt=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[i,r]of Object.entries(s)){const n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>W(r)?o:W(c)?r:r.padStart(parseInt(c,10),"0"))}return t},va=(a,e)=>{const s=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},r=s.children[0],n=r.getElementsByTagName("Period")[0],o=n.children;let c;const d=r.getAttribute("mediaPresentationDuration"),u=n.getAttribute("duration");if(d)c=Ss(d);else if(u){const p=Ss(u);A(p)&&(c=p)}let h=0;const f=r.getAttribute("profiles")?.split(",")??[],S=f.includes(Gt.WEBM_AS_IN_FFMPEG)||f.includes(Gt.WEBM_AS_IN_SPEC)?gt.WEBM:gt.MP4;for(const p of o){const m=p.getAttribute("mimeType"),y=p.getAttribute("codecs"),P=p.getAttribute("contentType")??m?.split("/")[0],x=p.getAttribute("profiles")?.split(",")??[],Z=p.querySelectorAll("Representation"),$=p.querySelector("SegmentTemplate");if(P!=="text")for(const v of Z){const F=v.getAttribute("mimeType")??m,H=v.getAttribute("codecs")??y??"",ie=v.getAttribute("contentType")??F?.split("/")[0]??P,q=p.getAttribute("profiles")?.split(",")??[],J=parseInt(v.getAttribute("width")??"",10),ne=parseInt(v.getAttribute("height")??"",10),j=parseInt(v.getAttribute("bandwidth")??"",10)/1e3,le=v.getAttribute("frameRate")??"",xe=v.getAttribute("quality")??void 0,Qe=le?is(le):void 0,I=v.getAttribute("id")??(h++).toString(10),X=ie==="video"?`${ne}p`:ie==="audio"?`${j}Kbps`:H,he=`${I}@${X}`,me=v.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(me,e).toString(),je=[...f,...x,...q];let bt;const xt=v.querySelector("SegmentBase"),Y=v.querySelector("SegmentTemplate")??$;if(xt){const Se=v.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[be,Oe]=Se.split("-").map(st=>parseInt(st,10)),Ue={from:be,to:Oe},Ie=v.querySelector("SegmentBase")?.getAttribute("indexRange"),[Je,Ke]=Ie?Ie.split("-").map(st=>parseInt(st,10)):[],Xe=Ie?{from:Je,to:Ke}:void 0;bt={type:Re.BYTE_RANGE,url:Ee,initRange:Ue,indexRange:Xe}}else if(Y){const Se={representationId:v.getAttribute("id")??void 0,bandwidth:v.getAttribute("bandwidth")??void 0},be=parseInt(Y.getAttribute("timescale")??"",10),Oe=Y.getAttribute("initialization")??"",Ue=Y.getAttribute("media"),Ie=parseInt(Y.getAttribute("startNumber")??"",10)??1,Je=Jt(Oe,Se);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Ke=Y.querySelectorAll("SegmentTimeline S")??[],Xe=[];if(Ke.length){let st=Ie,it=0;for(const yt of Ke){const ut=parseInt(yt.getAttribute("d")??"",10)*1e3,Tt=parseInt(yt.getAttribute("r")??"",10)||0,Et=parseInt(yt.getAttribute("t")??"",10)??void 0;for(let rs=0;rs<Tt+1;rs++){const Xs=Jt(Ue,{...Se,segmentNumber:st.toString(10),segmentTime:Et.toString(10)}),Zs=Et?Et/be:it;it+=ut/be;const ei=it;st++,Xe.push({time:{from:Zs,to:ei},url:Xs})}}}else if(A(c)){const it=parseInt(Y.getAttribute("duration")??"",10)/be*1e3,yt=Math.ceil(c/it);let ut=0;for(let Tt=1;Tt<yt;Tt++){const Et=Jt(Ue,{...Se,segmentNumber:Tt.toString(10),segmentTime:ut.toString(10)});Xe.push({time:{from:ut,to:ut+it},url:Et}),ut+=it}}bt={type:Re.TEMPLATE,baseUrl:Ee,initUrl:Je,segments:Xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!F)continue;const ge={video:Pe.VIDEO,audio:Pe.AUDIO,text:Pe.TEXT}[ie];ge&&i[ge].push({id:he,kind:ge,segmentReference:bt,profiles:je,duration:c,bitrate:j,mime:F,codecs:H,width:J,height:ne,fps:Qe,quality:xe})}}return{duration:c,container:S,representations:i}},Aa=["timeupdate","progress","play","seeked","stalled","waiting"];var we;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(we||(we={}));let $a=class{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new K;fetcher;state$=new re(we.NONE);currentVideoRepresentation$=new b(void 0);error$=new _;lastConnectionType$=new b(void 0);lastConnectionReused$=new b(void 0);lastRequestFirstBytes$=new b(void 0);forceEnded$=new _;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new rt;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ea({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=Ce(this.destroyController.signal,async function*(e,t){this.element=e,this.state$.startTransitionTo(we.MANIFEST_READY);const s=yield this.fetcher.fetchManifest(t).catch(n=>this.error$.next({id:"LoadManifest",category:D.NETWORK,message:"Failed to load manifest",thrown:n}));if(!s)return;let i;try{i=va(s??"",t)}catch(n){this.error$.next({id:"ManifestParsing",category:D.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!i)return;const r=({mime:n,codecs:o})=>Boolean(e.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`));this.manifest={...i,representations:Object.fromEntries(Object.entries(i.representations).map(([n,o])=>[n,o.filter(r)]))},this.manifest.representations.video.length?this.state$.setState(we.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:D.PARSER,message:"No playable video representations"})}.bind(this));initRepresentations=Ce(this.destroyController.signal,async function*(e,t){k(this.manifest),k(this.element),this.state$.startTransitionTo(we.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new ms(Pe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],A(t)&&(this.audioBufferManager=new ms(Pe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const i=C(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(E(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),r=C(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(E(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.subscription.add(C(this.forceEnded$,Ye({allBuffersFull:i,someBufferEnded:r}).pipe(O(({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:D.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.subscription.add(C(...this.bufferManagers.map(n=>n.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),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(we.REPRESENTATIOS_READY)}.bind(this));initBuffer(){k(this.element),this.state$.setState(we.RUNNING),this.subscription.add(C(...Aa.map(e=>B(this.element,e)),B(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:D.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(B(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(B(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&es(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Pe.VIDEO]:this.videoBufferManager,[Pe.AUDIO]:this.audioBufferManager,[Pe.TEXT]:null}[e]?.switchTo(t)}seek(e,t){k(this.element),k(this.videoBufferManager);let s;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?s=e:s=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),es(this.element.buffered,s)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(s),this.audioBufferManager?.maintain(s),this.element.currentTime=s/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(we.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.destroyController.abort(),this.fetcher.destroy(),this.stop(),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=si(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),t=>{this.error$.next({id:"GapWatchdog",category:D.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const s of this.bufferManagers)for(const i of s.gaps)s.playingRepresentation$.getValue()===i.representation&&i.from<=e&&i.to>e&&(this.element.duration*1e3-i.to<this.tuning.endGapTolerance?t.push(1/0):t.push(i.to));if(t.length){const s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};var oe;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(oe||(oe={}));const ka=({id:a,width:e,height:t,bitrate:s,fps:i,quality:r})=>{const n=(r?Ct(r):void 0)??dt({width:e,height:t});return n&&{id:a,quality:n,bitrate:s,size:{width:e,height:t},fps:i}},wa=({id:a,bitrate:e})=>({id:a,bitrate:e}),Pa=(a,e,t)=>{const s=e.indexOf(t);return a.at(Math.round(a.length*s/e.length))??a.at(-1)};class Ra{subscription=new K;videoState=new re(oe.STOPPED);video;player;params;elementSize$=new b(void 0);textTracksManager=new Me;videoTracks=[];audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Mi;constructor(e){this.params=e,this.video=ze(this.params.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(ve(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new $a({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=We(this.video),i=d=>{e.error$.next({id:"DashVKProvider",category:D.WTF,message:"DashVKProvider internal logic error",thrown:d})},r=(d,u)=>this.subscription.add(d.subscribe(u,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.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.isAudioAvailable$,e.isAudioAvailable$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(O(A),pe(),ot(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ct(this.video,t.isLooped,i)),this.subscription.add(Ge(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,i)),r(qt(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),w(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),w(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===we.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const u=this.player.getRepresentations();k(u,"Manifest not loaded or empty");const h=Array.from(u.audio).sort((p,m)=>m.bitrate-p.bitrate),f=Array.from(u.video).sort((p,m)=>m.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const m=wa(p);m&&this.audioTracks.push({track:m,representation:p})}for(const p of f){const m=ka(p);if(m){this.videoTracks.push({track:m,representation:p});const y=!this.params.tuning.isAudioDisabled&&Pa(h,f,p);y&&this.audioRepresentations.set(p.id,y)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const S=this.selectVideoRepresentation();k(S),this.player.initRepresentations(S.id,this.audioRepresentations.get(S.id)?.id)}else d===we.REPRESENTATIOS_READY&&(this.videoState.setState(oe.READY),this.player.initBuffer())},i));const n=d=>e.error$.next({id:"RepresentationSwitch",category:D.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(C(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,B(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),u=this.player.state$.getTransition();if(d!==we.RUNNING||u||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(Pe.VIDEO,h.id).catch(n);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(Pe.AUDIO,f.id).catch(n)}},i)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ue(),E(d=>d&&this.videoTracks.find(({representation:{id:u}})=>u===d)?.track)).subscribe(e.currentVideoTrack$,i)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(E(({to:d})=>d===l.READY),ue());this.subscription.add(C(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===l.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(C(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===l.READY)));const c=C(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0));this.subscription.add(c.subscribe(this.syncPlayback,i))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState(),s=this.videoTracks.find(({track:{id:h}})=>h===t)?.track,i=this.params.output.currentVideoTrack$.getValue(),r=at(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(s&&!e?this.audioRepresentations.get(s.id)?.bitrate??0:0,i?this.audioRepresentations.get(i.id)?.bitrate??0:0),d=It(this.videoTracks.map(({track:h})=>h),{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:i,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),u=e?d??s:s??d;return u&&this.videoTracks.find(({track:h})=>h===u)?.representation}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state===N.Requested&&s?.to!==l.PAUSED&&e!==oe.STOPPED&&t!==l.STOPPED&&this.seek(i.position,i.forcePrecise),t===l.STOPPED){e!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.player.stop(),this.video.setAttribute("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),w(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),w(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):s?.to===l.READY&&w(this.params.desiredState.playbackState,l.READY);return;case oe.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case oe.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;default:return L(e)}}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}}const Da=5e3,Ve={};var z;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const Ot=(a,e)=>new _t(t=>{const s=(i,r)=>t.next(r);return a.on(e,s),()=>a.off(e,s)});class _a{subscription=new K;videoState=new re(z.INITIALIZING);video;params;hls;textTracksManager=new Me;trackLevels=new Map;constructor(e){this.video=ze(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(ve(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:D.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),Da);import("hls.js/dist/hls.min.js").then(i=>{e||(Ve.Hls=i.default,Ve.Events=i.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){k(Ve.Hls,"hls.js not loaded"),this.hls=new Ve.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){k(Ve.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:D.WTF,message:"HlsJsProvider internal logic error",thrown:d})},i=We(this.video),r=(d,u)=>this.subscription.add(d.subscribe(u,s));r(i.timeUpdate$,t.position$),r(i.durationChange$,t.duration$),r(i.ended$,t.endedEvent$),r(i.looped$,t.loopedEvent$),r(i.error$,t.error$),r(i.isBuffering$,t.isBuffering$),r(i.currentBuffer$,t.currentBuffer$),r(i.loadStart$,t.firstBytesEvent$),r(i.playing$,t.firstFrameEvent$),r(i.canplay$,t.canplay$),r(i.seeked$,t.seekedEvent$),r(i.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(ct(this.video,e.isLooped,s)),this.subscription.add(Ge(this.video,e.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,e.playbackRate,i.playbackRateState$,s)),this.subscription.add(Ot(this.hls,Ve.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:D.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),w(e.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),w(e.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},s)),r(Ot(this.hls,Ve.Events.MANIFEST_PARSED).pipe(E(({levels:d})=>d.reduce((u,h)=>{const f=h.name||h.height.toString(10),{width:S,height:p}=h,m=Ct(h.attrs.QUALITY??"")??dt({width:S,height:p});if(!m)return u;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:f.toString(),quality:m,bitrate:h.bitrate/1e3,size:{width:S,height:p},fps:y};return this.trackLevels.set(f,{track:P,level:h}),u.push(P),u},[]))),t.availableVideoTracks$),r(Ot(this.hls,Ve.Events.LEVEL_LOADING).pipe(E(({url:d})=>ve(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:s}));const n=d=>Array.from(this.trackLevels.values()).find(({level:u})=>u===d)?.track,o=Ot(this.hls,Ve.Events.LEVEL_SWITCHED).pipe(E(({level:d})=>n(this.hls.levels[d])));o.pipe(O(A)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Ne(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel])?.id,d=>{if(W(d))return;const u=this.trackLevels.get(d)?.level;if(!u)return;const h=this.hls.levels.indexOf(u),f=this.hls.currentLevel,S=this.hls.levels[f];!S||u.bitrate>S.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(E(d=>d?.id)),onError:s})),r(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=C(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!==z.INITIALIZING)switch(s?.to!==l.PAUSED&&i.state===N.Requested&&this.seek(i.position),t){case l.STOPPED:switch(e){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:L(e)}break;case l.READY:switch(e){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:L(e)}break;case l.PLAYING:switch(e){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:L(e)}break;case l.PAUSED:switch(e){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED);break;case z.PLAYING:this.pause();break;default:L(e)}break;default:L(t)}};prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(z.PLAYING),await tt(this.video)||(this.videoState.setState(z.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))}pause(){this.videoState.startTransitionTo(z.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.setAttribute("src",""),this.video.load(),this.videoState.setState(z.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0)}}const gs="X-Playback-Duration";var bs=async a=>{const e=await mt(a,{method:"HEAD"});return e.headers.has(gs)?parseInt(e.headers.get(gs),10):void 0};const Ia=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){const[t,s]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=dt({width:t,height:s})}return e??null},Ws=async(a,e=a)=>{const i=(await(await mt(a)).text()).split(`
8
- `),r=[];for(let n=0;n<i.length;n++){const c=i[n].match(/^#EXT-X-STREAM-INF:(.+)/);if(!c)continue;const d=Object.fromEntries(c[1].split(",").map(y=>y.split("="))),u=d.QUALITY??`stream-${d.BANDWIDTH}`,h=Ia(d);let f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const S=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0;let p;if(d.RESOLUTION){const[y,P]=d.RESOLUTION.split("x").map(x=>parseInt(x,10));y&&P&&(p={width:y,height:P})}const m=new URL(i[++n],e).toString();h&&r.push({id:u,quality:h,url:m,bandwidth:f,size:p,fps:S})}return r};var ee;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(ee||(ee={}));class Ca{subscription=new K;videoState=new re(ee.STOPPED);video;params;textTracksManager=new Me;manifests$=new b([]);maxSeekBackTime$;liveOffset=new ss;manifestStartTime$=new b(void 0);constructor(e){this.params=e,this.video=ze(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:se.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),Ws(pt(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ve(this.params.source.url)),this.maxSeekBackTime$=new b(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),r=i?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n)return;const o=s?"master":r;return s&&!i&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:D.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=We(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c,s));r(i.ended$,e.endedEvent$),r(i.error$,e.error$),r(i.isBuffering$,e.isBuffering$),r(i.currentBuffer$,e.currentBuffer$),r(i.loadedMetadata$,e.firstBytesEvent$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),w(t.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),w(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ee.READY&&this.videoState.setState(ee.READY),this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(ue(),E(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&A(d.to)){const h=d.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(S=>S.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ve(f.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),c&&c.from===ee.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===N.Requested&&this.seek(o.position)},s)),this.subscription.add(i.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},s)),this.subscription.add(Ye({startTime:this.manifestStartTime$.pipe(O(A)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),s)),this.subscription.add(this.manifests$.pipe(E(o=>o.map(({id:c,quality:d,size:u,bandwidth:h,fps:f})=>({id:c,quality:d,size:u,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const n=C(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,$e(["init"])).pipe(_e(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(W(e))return;const t=pt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),bs(t).then(s=>{if(!W(s))this.maxSeekBackTime$.next(s);else{const i=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(W(i)||!isFinite(i))try{mt(t).then(r=>r.text()).then(r=>{const n=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(r)?.[1];if(n){const o=new URL(n,t).toString();bs(o).then(c=>{W(c)||this.maxSeekBackTime$.next(c)})}})}catch{}}})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===l.STOPPED){e!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.video.setAttribute("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(ee.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(i||r){const c=this.videoState.getState();this.videoState.setState(ee.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),o.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==l.PAUSED&&o.state===N.Requested){this.videoState.startTransitionTo(ee.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(e){case ee.READY:t===l.READY?w(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case ee.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(ee.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&&(w(this.params.desiredState.playbackState,l.PAUSED),this.liveOffset.pause());return;case ee.CHANGING_MANIFEST:break;default:return L(e)}}}var ae;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(ae||(ae={}));class La{subscription=new K;videoState=new re(ae.STOPPED);video;params;textTracksManager=new Me;manifests$=new b([]);constructor(e){this.params=e,this.video=ze(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:se.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),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(ve(this.params.source.url)),Ws(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),r=i?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n)return;const o=s?"master":r;return s&&!i&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:D.WTF,message:"HlsProvider internal logic error",thrown:o})},i=We(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c));r(i.timeUpdate$,e.position$),r(i.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.seeked$,e.seekedEvent$),r(i.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(ct(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),w(t.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),w(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ae.READY&&this.videoState.setState(ae.READY),this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},s).add(i.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&A(d.to)){const h=d.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(S=>S.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ve(f.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),c&&c.from===ae.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===N.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe(E(o=>o.map(({id:c,quality:d,size:u,bandwidth:h,fps:f})=>({id:c,quality:d,size:u,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const n=C(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();W(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===l.STOPPED){e!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.STOPPED),this.video.setAttribute("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(ae.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===ae.STOPPED){this.videoState.startTransitionTo(ae.READY),this.prepare();return}if(i||r){const c=this.videoState.getState();this.videoState.setState(ae.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:d}=this.video;this.prepare(),o.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:d*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&o.state===N.Requested&&this.seek(o.position),e){case ae.READY:t===l.READY?w(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(ae.PAUSED),w(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()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case ae.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;case ae.CHANGING_MANIFEST:break;default:return L(e)}}}var de;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(de||(de={}));class xa{subscription=new K;videoState=new re(de.STOPPED);video;trackUrls={};params;textTracksManager=new Me;constructor(e){this.params=e,this.video=ze(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],i)=>{const r=i.toString(10);this.trackUrls[r]={track:{quality:t,id:r},url:s}}),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.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:D.WTF,message:"MpegProvider internal logic error",thrown:o})},i=We(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c,s));r(i.timeUpdate$,e.position$),r(i.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.seeked$,e.seekedEvent$),r(i.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(ct(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),w(t.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),w(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===de.READY&&this.videoState.setState(de.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()===de.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=C(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();k(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];k(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=St(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ve(t))}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.setAttribute("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),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.seekState.getState();if(e===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(r){const{currentTime:o}=this.video;this.prepare(),n.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:o*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&n.state===N.Requested&&this.seek(n.position),e){case de.READY:t===l.READY?w(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(de.PAUSED),w(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()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case de.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;default:return L(e)}}}const ys=["stun:videostun.mycdn.me:80"],Ba=1e3,Na=3,Kt=()=>null;class Ma{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Kt;externalStopCallback=Kt;externalErrorCallback=Kt;constructor(e,t){this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.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:ys}]};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:D.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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))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),Ba)}normalizeOptions(e={}){const t={stunServerList:ys,maxRetryNumber:Na,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var te;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(te||(te={}));class Oa{subscription;params;log;video;videoState=new re(te.STOPPED);liveStreamClient;maxSeekBackTime$=new b(0);constructor(e){this.subscription=new K,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ze(e.container),this.liveStreamClient=new Ma(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:D.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};C(this.videoState.stateChangeStarted$.pipe(E(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(E(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const i=We(this.video),r=(n,o)=>this.subscription.add(n.subscribe(o,s));r(i.timeUpdate$,e.liveTime$),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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED)},s)).add(i.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING)},s)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ge(this.video,t.volume,i.volumeState$,s)).add(i.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case te.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(l.STOPPED);break;case te.READY:break;case te.PAUSED:t.playbackState.setState(l.PAUSED);break;case te.PLAYING:t.playbackState.setState(l.PLAYING);break;default:return L(n.to)}},s)).add(C(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,$e(["init"])).pipe(_e(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}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.hostname$.next(ve(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:se.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,l.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(te.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:D.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition();if(e===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(r){this.prepare();return}switch(e){case te.READY:t===l.PAUSED?(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case te.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;default:return L(e)}}}class Ts{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 Boolean(this.current.done)}}var Ua=()=>{const a=window.navigator;return a.userAgentData?a.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const Qs=Ua(),Wt=document.createElement("video"),Fe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Wt.canPlayType?.("application/x-mpegurl")||Wt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},ke={mp4:Boolean(Wt.canPlayType?.("video/mp4")),webm:Boolean(Wt.canPlayType?.("video/webm")),cmaf:!0},Ze={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},ht=(Ze.h264||Ze.h265)&&Ze.aac,jt=Fe.hls&&ke.mp4,Va=Boolean(window.WebSocket),Fa=()=>Object.keys(Ze).filter(a=>Ze[a]),Ha=(a,e=!1)=>a.filter(t=>{switch(t){case g.DASH:return Fe.mse&&ke.mp4&&ht;case g.DASH_SEP:return Fe.mse&&ke.mp4&&ht;case g.DASH_WEBM:return Fe.mse&&ke.webm&&Ze.vp9&&Ze.opus;case g.DASH_LIVE:return Fe.mse&&ke.mp4&&ht;case g.DASH_LIVE_CMAF:return Fe.mse&&ke.mp4&&ht&&ke.cmaf;case g.DASH_ONDEMAND:return Fe.mse&&ke.mp4&&ht;case g.HLS:case g.HLS_LIVE:case g.HLS_LIVE_CMAF:case g.HLS_ONDEMAND:return jt||e&&Fe.mse&&ke.mp4&&ht;case g.MPEG:return ke.mp4;case g.DASH_LIVE_WEBM:return!1;case g.WEB_RTC_LIVE:return Fe.webrtc&&Va&&Ze.h264&&(ke.mp4||ke.webm);default:return L(t)}}),qa=()=>Qs?[g.MPEG,g.DASH_WEBM,g.DASH_SEP,g.DASH,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND]:jt?[g.DASH_WEBM,g.DASH_SEP,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND,g.MPEG,g.DASH]:[g.DASH_WEBM,g.DASH_SEP,g.DASH,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND,g.MPEG],Ya=()=>Qs?[g.HLS_LIVE,g.HLS_LIVE_CMAF,g.WEB_RTC_LIVE,g.DASH_LIVE,g.DASH_LIVE_CMAF]:jt?[g.WEB_RTC_LIVE,g.HLS_LIVE,g.HLS_LIVE_CMAF,g.DASH_LIVE,g.DASH_LIVE_CMAF]:[g.WEB_RTC_LIVE,g.DASH_LIVE,g.DASH_LIVE_CMAF,g.HLS_LIVE,g.HLS_LIVE_CMAF],Es=a=>a?[g.HLS_LIVE]:[g.DASH_WEBM,g.DASH_SEP,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND,g.MPEG];var Ga=a=>new _t(e=>{const t=new K,s=a.desiredPlaybackState$.stateChangeStarted$.pipe(E(({from:d,to:u})=>`${d}-${u}`)),i=a.desiredPlaybackState$.stateChangeEnded$,r=a.providerChanged$,n=new _;let o=0,c="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),c="provider change",o=0})),t.add(r.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const vs={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},za={cacheDuration:12e4},Wa={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Qa={maxPausedTime:3e4},As={maxPausedTime:3e4};class ja{current$=new b({type:void 0});providerError$=new _;noAvailableProvidersError$=new _;providerOutput={position$:new b(0),duration$:new b(1/0),volume$:new b({muted:!1,volume:1}),currentVideoTrack$:new b(void 0),availableVideoTracks$:new b([]),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),autoVideoTrackLimitingAvailable$:new b(!1),currentBuffer$:new b(void 0),isBuffering$:new b(!0),error$:new _,willSeekEvent$:new _,seekedEvent$:new _,loopedEvent$:new _,endedEvent$:new _,firstBytesEvent$:new _,firstFrameEvent$:new _,canplay$:new _,isLive$:new b(void 0),liveTime$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),element$:new b(void 0)};subscription=new K;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Ha([...Ya(),...qa()],this.params.tuning.useHlsJs).filter(n=>A(e.sources[n])),{formatsToAvoid:s}=this.params.tuning,i=s.length?[...t.filter(n=>!s.includes(n)),...t.filter(n=>s.includes(n))]:t;this.screenFormatsIterator=new Ts(i);const r=[...Es(!0),...Es(!1)];this.chromecastFormatsIterator=new Ts(r.filter(n=>A(e.sources[n])))}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(W(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:D.WTF,message:"Failed to create provider",thrown:i})}s?this.current$.next({type:t,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;k(e,"No current provider"),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,s=this.params.desiredState.seekState.getState(),i=s.state!==N.None;this.params.desiredState.seekState.setState({state:N.Requested,position:i?s.position:t,forcePrecise:i?s.forcePrecise:!1}),e.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return L(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:i}=this.params,r=this.providerOutput,n={container:s,source:null,desiredState:i,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case g.DASH:{const o=this.applyFailoverHost(t[e]);return k(o),new na({...n,source:o,config:za})}case g.DASH_SEP:case g.DASH_WEBM:case g.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return k(o),this.params.tuning.useDashJs?new us({...n,source:o,format:e,config:As}):new Ra({...n,source:o})}case g.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return k(o),new us({...n,source:o,format:e,config:As})}case g.HLS:case g.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return k(o),jt||!this.params.tuning.useHlsJs?new La({...n,source:o}):new _a({...n,source:o})}case g.HLS_LIVE:case g.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return k(o),new Ca({...n,source:o,config:Qa})}case g.MPEG:{const o=this.applyFailoverHost(t[e]);return k(o),new xa({...n,source:o})}case g.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return k(o),new ta({...n,source:o,config:Wa})}case g.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return k(o),new Oa({container:s,source:o,desiredState:i,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 L(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:i,meta:r}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return k(o),new yi({connection:o,meta:r,container:s,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ae.CHROMECAST:Ae.SCREEN}chooseFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return L(e)}}skipFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.next();case Ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return L(e)}}handleNoFormatsError(e){switch(e){case Ae.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case Ae.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return L(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=i=>{const r=new URL(i);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:s(e.url)}}return Object.fromEntries(Object.entries(e).map(([i,r])=>[i,s(r)]))}initProviderErrorHandling(){const e=new K;let t=!1,s=0;return e.add(C(this.providerOutput.error$,Ga({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:vs.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(O(({type:i})=>i!==void 0))}).pipe(E(i=>({id:`ProviderHangup:${i}`,category:D.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const i=this.params.desiredState.playbackState.transitionEnded$.pipe(O(({to:r})=>r===l.PLAYING),pe()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{if(this.current$.getValue().destination===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const r=i.category===D.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<vs.providerErrorLimit;n&&(r&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var De;(function(a){a[a.LOCAL_STORAGE=0]="LOCAL_STORAGE",a[a.SESSION_STORAGE=1]="SESSION_STORAGE",a[a.RUNTIME=2]="RUNTIME"})(De||(De={}));const js=new Map;let nt=De.RUNTIME;const Xt=`vk-videoplayer-dummy-key-${Math.random()}`,Ja=()=>{try{localStorage.setItem(Xt,"test"),localStorage.removeItem(Xt),nt=De.LOCAL_STORAGE}catch(a){if(a instanceof DOMException||a instanceof TypeError)try{sessionStorage.getItem(Xt),nt=De.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)nt=De.RUNTIME;else throw e}else throw a}};Ja();const Ka=a=>{switch(nt){case De.LOCAL_STORAGE:return localStorage.getItem(a)??void 0;case De.SESSION_STORAGE:return sessionStorage.getItem(a)??void 0;case De.RUNTIME:return js.get(a);default:L(nt)}},$s=(a,e)=>{switch(nt){case De.LOCAL_STORAGE:try{localStorage.setItem(a,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case De.SESSION_STORAGE:try{sessionStorage.setItem(a,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case De.RUNTIME:return void js.set(a,e);default:L(nt)}},ts=(a,e,t)=>t*e+(1-t)*a,Js=(a,e)=>a.reduce((t,s)=>t+s,0)/e,Xa=(a,e,t,s)=>{let i=0,r=t;const n=Js(a,e),o=e<s?e:s;for(let c=0;c<o;c++)a[r]>n?i++:i--,r=(a.length+r-1)%a.length;return Math.abs(i)===o};class Ks{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 b(e.initial),this.debounced$=new b(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Be(`raw_${t}`),this.smoothedSeries$=new Be(`smoothed_${t}`),this.reportedSeries$=new Be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const i=Math.sqrt(t),r=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;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)&&(W(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 Za extends Ks{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ts(this.slow,e,this.params.emaAlphaSlow),this.fast=ts(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class er extends Ks{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Js(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ts(this.emaSmoothed,e,this.params.emaAlpha);const s=Xa(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class ks{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Za({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new er({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const tr=5e3,ws="one_video_throughput",Ps="one_video_rtt",Pt=window.navigator.connection,Rs=()=>{const a=Pt?.downlink;if(A(a)&&a!==10)return a*1e3},Ds=()=>{const a=Pt?.rtt;if(A(a)&&a!==3e3)return a},_s=(a,e,t)=>{const s=t*8,i=s/a;return s/(i+e)};class Rt{throughput;rtt;subscription=new K;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Rt.load(ws)||(e.useBrowserEstimation?Rs():void 0)||tr,s=Rt.load(Ps)??(e.useBrowserEstimation?Ds():void 0)??0;if(this.throughput$=new b(t),this.rtt$=new b(s),this.rttAdjustedThroughput$=new b(_s(t,s,e.rttPenaltyRequestSize)),this.throughput=ks.getSmoothedValue(t,-1,e),this.rtt=ks.getSmoothedValue(s,1,e),e.useBrowserEstimation){const i=()=>{const n=Rs();n&&this.throughput.next(n);const o=Ds();A(o)&&this.rtt.next(o)};Pt&&"onchange"in Pt&&this.subscription.add(B(Pt,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{$s(ws,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{$s(Ps,i.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ye({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(E(({throughput:i,rtt:r})=>_s(i,r,e.rttPenaltyRequestSize)),O(i=>{const r=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(i-r)/r>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=ce();const i=new K;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(B(e,"progress").pipe(pe()).subscribe(r=>{t=r.loaded,s=ce()}));break;case 1:case 0:i.add(B(e,"loadstart").subscribe(()=>{t=0,s=ce()}));break}i.add(B(e,"loadend").subscribe(r=>{if(e.status===200){const n=r.loaded,o=ce(),c=n-t,d=o-s;this.addRawSpeed(c,d,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let s=0;const i=ce();let r=0,n=ce();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},c=async({done:d,value:u})=>{d?(this.addRawSpeed(s,ce()-i,1),this.concurrentDownloads.delete(e)):u&&(s+=u.byteLength,r+=u.byteLength,r>=this.tuningConfig.streamMinSampleSize&&ce()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,ce()-n,this.concurrentDownloads.size),r=0,n=ce()),await t?.read().then(c,o))};this.concurrentDownloads.add(e),t?.read().then(c,o)}addRawSpeed(e,t,s=1){if(Rt.sanityCheck(e,t)){const i=e*8/t;this.throughput.next(i*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){const t=Ka(e);if(A(t))return parseInt(t,10)??void 0}}const Is={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},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},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,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,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},sr=a=>{const e={};for(const t of Object.keys(Is)){const s=Is[t],i=a[t];Array.isArray(s)&&Array.isArray(i)?e[t]=i:typeof s=="object"&&typeof i=="object"?e[t]={...s,...i}:e[t]=i??s}return e};var ir=({seekState:a,position$:e})=>C(a.stateChangeEnded$.pipe(E(({to:t})=>t.state===N.None?void 0:(t.position??NaN)/1e3),O(A)),e.pipe(O(()=>a.getState().state===N.None))),ar=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return k(e,`Wrong container or containerId {${a.container}}`),e};const Cs=({playbackState:a,seekState:e,playbackAbort$:t,looped$:s,position$:i})=>new _t(r=>{let n;const o=a.transitionEnded$.pipe(O(S=>(S.from===l.PAUSED||S.from===l.STOPPED)&&S.to===l.PLAYING)),c=a.stateChangeEnded$.pipe(O(S=>S.from===l.PLAYING&&S.to===l.PAUSED)),d=e.stateChangeEnded$.pipe(O(({to:S})=>S.state===N.Requested&&(a.getTransition()?.from??a.getState())===l.PLAYING)),u=e.stateChangeEnded$.pipe(O(({from:S,to:p})=>S.state===N.Applying&&p.state===N.None&&(a.getTransition()?.from??a.getState())===l.PLAYING)),h=C(o,u).pipe(E(()=>i.getValue()),O(A)),f=C(C(c,d,t),s).pipe(E(()=>i.getValue()),O(A));return new K().add(h.subscribe(S=>{n=S})).add(f.subscribe(S=>{if(W(n)||n===S)return;const p={from:n,to:S};n=void 0,r.next(p)}))});class ur{subscription=new K;domContainer;providerContainer;chromecastInitializer;logger=new ii;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new re(l.STOPPED),seekState:new re({state:N.None}),volume:new re({volume:1,muted:!1}),videoTrack:new re(void 0),autoVideoTrackSwitching:new re(!0),autoVideoTrackLimits:new re({}),isLooped:new re(!1),playbackRate:new re(1),externalTextTracks:new re([]),currentTextTrack:new re(void 0),textTrackCuesSettings:new re({})};info={playbackState$:new b(l.STOPPED),position$:new b(0),duration$:new b(1/0),muted$:new b(!1),volume$:new b(1),availableQualities$:new b([]),availableQualitiesFps$:new b({}),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),currentQuality$:new b(void 0),isAutoQualityEnabled$:new b(!0),autoQualityLimitingAvailable$:new b(!1),autoQualityLimits$:new b({}),currentPlaybackRate$:new b(1),currentBuffer$:new b({start:0,end:0}),isBuffering$:new b(!0),isStalled$:new b(!1),isEnded$:new b(!1),isLooped$:new b(!1),isLive$:new b(void 0),liveTime$:new b(void 0),currentFormat$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),throughputEstimation$:new b(void 0),rttEstimation$:new b(void 0),videoBitrate$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),chromecastState$:new b(Te.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(void 0)};events={inited$:new _,started$:new _,willPause$:new _,willResume$:new _,willDestruct$:new _,watchCoverageRecord$:new _,watchCoverageLive$:new _,managedError$:new _,fatalError$:new _,ended$:new _,looped$:new _,seeked$:new _,willSeek$:new _,firstBytes$:new _,firstFrame$:new _,canplay$:new _,log$:new _};experimental={element$:new b(void 0),enableDebugTelemetry$:new b(!1),dumpTelemetry:xi};constructor(e={}){if(this.initLogs(),this.tuning=sr(e),this.chromecastInitializer=new di({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Rt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,i)=>{const r=Reflect.get(t,s,i);return typeof r!="function"?r:(...n)=>{try{return r.apply(t,n)}catch(o){const c=n.map(h=>JSON.stringify(h,(f,S)=>{const p=typeof S;return["number","string","boolean"].includes(p)?S:S===null?null:`<${p}>`})),d=`Player.${String(s)}`,u=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:D.WTF,message:u,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=ar(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ja({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},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.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=this.desiredState.playbackState;return e.getState()!==l.PLAYING&&e.startTransitionTo(l.PLAYING),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){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:N.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()===Te.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()===Te.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){k(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const s=t.find(i=>i.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){k(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.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()}getExactTime(){k(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(W(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===N.None?void 0:t.position;return A(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:i})=>s||i||0,0),height:e.reduce((s,{height:i})=>s||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(C(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(E(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(E(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(E(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(E(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(E(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e===l.STOPPED),pe()).subscribe(()=>{this.initedAt=ce(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(()=>!this.isPlaybackStarted),O(e=>e.to===l.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.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();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const c=this.desiredState.seekState.getState();c.state===N.Requested?this.desiredState.seekState.setState({...c,state:N.Applying}):this.events.managedError$.next({id:`WillSeekIn${c.state}`,category:D.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===N.Applying&&(this.desiredState.seekState.setState({state:N.None}),this.events.seeked$.next())})).add(e.current$.pipe(E(c=>c.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(E(c=>c.destination),ue()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(E(c=>c.map(({quality:d})=>d).sort((d,u)=>Ft(d)?1:Ft(u)?-1:Ut(u,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(c=>{const d={};for(const u of c)u.fps&&(d[u.quality]=u.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(c=>{this.info.currentQuality$.next(c?.quality),this.info.videoBitrate$.next(c?.bitrate)})).add(e.providerOutput.hostname$.pipe(ue()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ue()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ue()).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.currentBuffer$.pipe(E(c=>c?{start:c.from,end:c.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(E(c=>c.muted),ue()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(E(c=>c.volume),ue()).subscribe(this.info.volume$)).add(ir({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(C(e.providerOutput.endedEvent$.pipe(ot(!0)),e.providerOutput.seekedEvent$.pipe(ot(!1))).pipe(ue()).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(E(c=>({id:"NoProviders",category:D.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(pe(),E(()=>ce()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(pe(),E(()=>ce()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(pe(),E(()=>ce()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new b(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new b(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(({to:c})=>c===l.PLAYING),pe()).subscribe(()=>s.next(!1)));let i=0;const r=C(e.providerOutput.isBuffering$,t,s).pipe(E(()=>{const c=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||s.getValue();return c&&!d}),ue());this.subscription.add(r.subscribe(c=>{c?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))}));const n=new K;this.subscription.add(n);const o=C(B(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(O(c=>Boolean(c?.provider))));e.providerOutput.isLive$.pipe(ue()).subscribe(c=>{switch(k(this.providerContainer),n.unsubscribe(),c){case!0:{const d=new b(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(u=>d.next(u&&Math.floor(u/1e3)))),n.add(Cs({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe(E(({from:u,to:h})=>({start:u,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(Cs({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe(E(({from:d,to:u})=>({start:d,end:u}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(C(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:c?.videoWidth,height:c?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(c=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:c?.size?.width,height:c?.size?.height},{width:d?.videoWidth,height:d?.videoHeight})}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(E(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new K;this.subscription.add(t),this.subscription.add(e.current$.pipe(ue((s,i)=>s.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(s=>s.length>0),pe()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=It(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})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(C(this.desiredState.videoTrack.stateChangeStarted$.pipe(E(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(E(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(E(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(E(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(E(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(E(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(E(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(E(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(E(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;k(this.providerContainer),k(e),Li(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ci(t)),this.providerContainer.current$.subscribe(({type:t})=>Bt("provider",t)),e.duration$.subscribe(t=>Bt("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),pe()).subscribe(t=>Bt("tracks",t)),this.events.fatalError$.subscribe(new Be("fatalError")),this.events.managedError$.subscribe(new Be("managedError")),e.position$.subscribe(new Be("position")),e.currentVideoTrack$.pipe(E(t=>t?.quality)).subscribe(new Be("quality")),this.info.currentBuffer$.subscribe(new Be("buffer")),e.isBuffering$.subscribe(new Be("isBuffering"))].forEach(t=>this.subscription.add(t)),Bt("codecs",Fa())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>this.events.managedError$.next({id:"WakeLock",category:D.DOM,message:String(i)}))};this.subscription.add(C(B(document,"visibilitychange"),B(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const i=document.visibilityState==="visible",r=this.desiredState.playbackState.getState()===l.PLAYING,n=Boolean(e)&&!e?.released;i&&r?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const hr=`${ni}@${ri}`;export{Te as ChromecastState,Dt as HttpConnectionType,pr as Observable,l as PlaybackState,ur as Player,hr as SDK_VERSION,mr as Subject,Sr as Subscription,gr as ValueSubject,g as VideoFormat,se as VideoQuality};
6
+ import{ValueSubject as g,Subject as _,Subscription as X,isNonNullable as A,ErrorCategory as D,isNullable as W,fromEvent as B,assertNever as C,merge as x,tap as ps,map as E,observableFrom as ke,filterChanged as he,assertNonNullable as k,debounce as _e,timeout as ci,combine as Ge,once as pe,mapTo as ct,filter as O,now as ce,Observable as Mt,abortable as xe,getExponentialDelay as ms,interval as hi,Logger as ui}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as Wr,Subject as Qr,Subscription as jr,ValueSubject as Jr}from"@vkontakte/videoplayer-shared/esnext.esm.js";import li from"lodash/debounce.js";const fi="2.0.83-dev.65744ed.0",pi="esnext.esm.js";var l;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(l||(l={}));var b;(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_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"})(b||(b={}));var Ae;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));var Te;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(Te||(Te={}));var Bt;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Bt||(Bt={}));var M;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(M||(M={}));var mi=a=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",a),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Si{connection$=new g(void 0);castState$=new g(Te.NOT_AVAILABLE);errorEvent$=new _;contentId;realCastState$=new g(Te.NOT_AVAILABLE);subscription=new X;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 s=A(window.chrome?.cast),i=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},i||mi("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:D.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();W(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();W(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),s=cast.framework.CastContext.getInstance();this.subscription.add(B(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=s.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 C(i.sessionState)}})).add(x(B(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ps(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),E(i=>i.castState)),ke([s.getCastState()])).pipe(he(),E(gi),ps(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{const r=i===Te.CONNECTED,n=A(this.connection$.getValue());if(r&&!n){const o=s.getCurrentSession();k(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(W(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(i===Te.CONNECTED?A(this.connection$.getValue())?Te.CONNECTED:Te.AVAILABLE:i)}))}initializeCastApi(){let e,t,s;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:s}),this.initListeners()}catch(i){this.errorEvent$.next({id:"ChromecastInitializer",category:D.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}}const gi=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Te.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Te.AVAILABLE;case cast.framework.CastState.CONNECTING:return Te.CONNECTING;case cast.framework.CastState.CONNECTED:return Te.CONNECTED;default:return C(a)}};var St;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(St||(St={}));var gt=(a,e=0,t=St.OFFSET_P)=>{switch(t){case St.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case St.PLAYBACK_SHIFT:{if(e===0)return a;const s=new URL(a);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:C(t)}return a},w=(a,e,t=!1)=>{const s=a.getTransition();(t||!s||s.to===e)&&a.setState(e)},te;(function(a){a.INVARIANT="Invariant quality",a.Q_144P="144p",a.Q_240P="240p",a.Q_360P="360p",a.Q_480P="480p",a.Q_720P="720p",a.Q_1080P="1080p",a.Q_1440P="1440p",a.Q_2160P="2160p",a.Q_4320P="4320p"})(te||(te={}));const Ce={[te.Q_144P]:{width:256,height:144},[te.Q_240P]:{width:428,height:240},[te.Q_360P]:{width:640,height:360},[te.Q_480P]:{width:856,height:480},[te.Q_720P]:{width:1280,height:720},[te.Q_1080P]:{width:1920,height:1080},[te.Q_1440P]:{width:2560,height:1440},[te.Q_2160P]:{width:3840,height:2160},[te.Q_4320P]:{width:7680,height:4320}},Gt=(a,e)=>Ce[a].height>Ce[e].height,bi=(a,e)=>Ce[a].height>=Ce[e].height,It=(a,e)=>Ce[a].height<Ce[e].height,yi=(a,e)=>Ce[a].height<=Ce[e].height,Ti=a=>a.sort((e,t)=>e===t?0:e===te.INVARIANT?1:t===te.INVARIANT?-1:It(e,t)?1:-1)[0],Ei=Object.keys(Ce).sort((a,e)=>It(a,e)?-1:1),ht=({width:a,height:e})=>{const t=Math.min(a,e),s=Math.max(a,e);return Ei.find(i=>{const r=Ce[i];return r.width>=s&&r.height>=t})},vi=a=>Ce[a].height,Wt=a=>a===te.INVARIANT;class re{state;transition;transitionStarted$=new _;transitionEnded$=new _;transitionUpdated$=new _;forceChanged$=new _;stateChangeStarted$=x(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=x(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e}setState(e){const t=this.transition,s=this.state;this.transition=void 0,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:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||A(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Ai=a=>{switch(a){case b.MPEG:case b.DASH:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return C(a)}};var N;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(N||(N={}));const ki=5,wi=5,$i=500,Ss=7e3;class Ri{subscription=new X;loadMediaTimeoutSubscription=new X;videoState=new re(N.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(Ai(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 X;this.subscription.add(e),this.subscription.add(x(this.videoState.stateChangeStarted$.pipe(E(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(E(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));const t=(i,r)=>this.subscription.add(i.subscribe(r));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new _;e.add(i.pipe(_e($i)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let r=NaN;e.add(B(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===M.Applying||Math.abs(o-r)>ki)&&i.next(o),r=o})),e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);const{remotePlayer:r}=this.params.connection,n=i.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<wi&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:C(n)}}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});const s=x(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0));t(s,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(N.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(N.PLAYING),w(this.params.desiredState.playbackState,l.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:M.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===N.PAUSED||e===N.PLAYING)&&(this.videoState.setState(N.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===N.PLAYING||e===N.PAUSED)&&(this.videoState.setState(N.PLAYING),w(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===N.READY&&this.videoState.setState(N.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&w(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==N.STOPPED&&this.videoState.setState(N.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),s={volume:e.volume??t.volume,muted:e.muted??t.muted};(s.volume!==t.volume||s.muted!==s.muted)&&this.params.output.volume$.next(s)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let s,i,r;switch(e){case b.MPEG:{const d=t[e];k(d);const h=Ti(Object.keys(d));k(h);const u=d[h];k(u),s=u,i="video/mp4",r=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const d=t[e];k(d),s=d.url,i="application/x-mpegurl",r=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const d=t[e];k(d),s=d.url,i="application/dash+xml",r=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const d=t[e];k(d),s=d.url,i="application/dash+xml",r=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const d=t[e];k(d),s=gt(d.url),i="application/x-mpegurl",r=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:D.VIDEO_PIPELINE,message:d,thrown:h}),h}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return C(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??s,i);n.contentUrl=s,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 s=this.params.desiredState.seekState.getState();return s.state===M.Applying||s.state===M.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((i,r)=>{this.loadMediaTimeoutSubscription.add(ci(Ss).subscribe(()=>r(`timeout(${Ss})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===M.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{const r=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:r}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:D.VIDEO_PIPELINE,message:r,thrown:i})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),s===l.STOPPED){e!==N.STOPPED&&(this.videoState.startTransitionTo(N.STOPPED),this.stop());return}if(!t){if(i?.to!==l.PAUSED&&r.state===M.Requested&&e!==N.STOPPED){this.seek(r.position/1e3);return}switch(s){case l.READY:{switch(e){case N.PLAYING:case N.PAUSED:case N.READY:break;case N.STOPPED:this.videoState.startTransitionTo(N.READY),this.prepare();break;default:C(e)}break}case l.PLAYING:{switch(e){case N.PLAYING:break;case N.PAUSED:this.videoState.startTransitionTo(N.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case N.READY:this.videoState.startTransitionTo(N.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case N.STOPPED:this.videoState.startTransitionTo(N.READY),this.prepare();break;default:C(e)}break}case l.PAUSED:{switch(e){case N.PLAYING:this.videoState.startTransitionTo(N.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case N.PAUSED:break;case N.READY:this.videoState.startTransitionTo(N.PAUSED),this.videoState.setState(N.PAUSED);break;case N.STOPPED:this.videoState.startTransitionTo(N.READY),this.prepare();break;default:C(e)}break}default:C(s)}}}}class gs{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let i=0,r=s.length;i<r;i++)if(s[i].callback===t){s.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let i=0,r=s.length;i<r;i++){const n=s[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Hs extends gs{constructor(){super(),this.listeners||gs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Ys=class{constructor(){Object.defineProperty(this,"signal",{value:new Hs,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Ys.prototype[Symbol.toStringTag]="AbortController",Hs.prototype[Symbol.toStringTag]="AbortSignal");function qs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Pi(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!qs({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:r};let r=t;(r&&!r.prototype.hasOwnProperty("signal")||i)&&(r=function(d,h){let u;h&&h.signal&&(u=h.signal,delete h.signal);const f=new t(d,h);return u&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),f},r.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const h=r&&r.prototype.isPrototypeOf(c)?c.signal:d?d.signal:void 0;if(h){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(h.aborted)return Promise.reject(u);const f=new Promise((S,p)=>{h.addEventListener("abort",()=>p(u),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([f,n(c,d)])}return n(c,d)},Request:r}}const ts=qs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Gs=ts?Pi({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,bt=ts?Gs.fetch:window.fetch;ts?Gs.Request:window.Request;const ot=ts?Ys:window.AbortController,Rt=a=>a.range?a.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class xt{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){const{url:t}=e.request,s=this.dashJsRequestQueue.get(t)??[];s.push(e),this.dashJsRequestQueue.set(t,s)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const i=t[0];if(!i||!i.request.range)continue;const[r,n]=Rt(i.request);if(r>=s.from&&n<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const i=this.sendBigRequest(e,t.map(({request:r})=>r));this.activeRequests.set(e,i)}}}abort(e){if(e){const{request:t}=e,s=(this.dashJsRequestQueue.get(t.url)??[]).includes(e),i=this.activeRequests.get(t.url);s&&i&&i.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(Rt),i=s[0][0];let r=s[0][1];for(let f=1;f<s.length&&r<this.params.minDataSize;f++){const S=s[f][1];S-i<=2*this.params.minDataSize&&(r=Math.max(r,S))}i===0?r=Math.max(r,i+this.params.minInitSize):r=Math.max(r,i+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${i}-${r}`);const o=n.toString(),c=new ot,d=c.signal,h={url:e,from:i,to:r,loaded:0,data:null,abortController:c};d.addEventListener("abort",()=>this.onBigRequestAbort(h));const u=f=>{throw this.params.onError?.({id:"BigRequestParsing",category:D.PARSER,message:"Error parsing response data",thrown:f}),f};return bt(o,{signal:d}).then(f=>{if(h.response=f,!f.ok||!f.body){this.onBigRequestError(h);return}const[S,p]=f.body.tee();this.params.onDownloadStream?.(p);const m=S.getReader(),T=parseInt(f.headers.get("Content-Length")??"",10)||r-i+1;h.data=new ArrayBuffer(T);const P=new Uint8Array(h.data),L=async({done:se,value:$})=>{se?this.onBigRequestProgress(h):$&&(P.set($,h.loaded),h.loaded+=$.byteLength,this.onBigRequestProgress(h),await m?.read().then(L,xt.suppressStreamErrors).catch(u))};m?.read().then(L,xt.suppressStreamErrors).catch(u)},xt.suppressAbort).catch(f=>this.onBigRequestError(h,f)),h}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:r,response:n}){if(!this.activeRequests.has(e)||!r)return;const o=this.dashJsRequestQueue.get(e)??[];for(const c of o){const{request:d}=c,[h,u]=Rt(d),f=h>=t&&u<=t+i,S=t>=h&&t+i<u,p=r.slice(h-t,Math.min(u-t+1,i));if((f||S)&&(d.requestStartDate=d.requestStartDate??new Date,d.firstByteDate=d.firstByteDate??new Date,d.bytesLoaded=p.byteLength,d.bytesTotal=s-t),f){d.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter(T=>T!==c)),c.success?.(p,"",e);const m=n?Array.from(n.headers.entries()).map(([T,P])=>`${T}: ${P}`).join(`\r
7
+ `):"";this.dashMetrics?.addHttpRequest(d,e,n?.status??200,m,[])}else S&&c.progress?.({loaded:i,total:s-t,lengthComputable:!0,stream:!0})}}onBigRequestError({url:e,from:t,to:s},i){if(this.params.onError?.({id:"BigRequest",category:D.NETWORK,message:"Download error",thrown:i}),!this.activeRequests.has(e))return;const r=this.dashJsRequestQueue.get(e)??[];for(const n of r){const[o,c]=Rt(n.request);(o>=t&&o<s||c>t&&c<=s)&&n?.error?.(n.request,String(i))}if(this.activeRequests.delete(e),i)throw i}onBigRequestAbort({url:e,from:t,to:s}){if(!this.activeRequests.has(e))return;const i=this.dashJsRequestQueue.get(e)??[];for(const r of i){const[n,o]=Rt(r.request);(n>=t&&n<s||o>t&&o<=s)&&r?.abort?.(r.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Qt{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Qt.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Qt.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Di=(a,e)=>t=>({create:s=>{const i=a(t).create(s);return new Qt(i,e,s)}}),_i=(a,e)=>{const t=new xt(e);return a.extend("SchemeLoaderFactory",function(){const{parent:s}=this,i=s.getLoader;return{getLoader:r=>{const n=i(r);return Di(n,t)}}},!0),()=>t.destroy()};var Ii=a=>{let e,t=!1,s=!1;a.on("playbackTimeUpdated",({timeToEnd:i})=>{s=i<=3,t&&s&&e?.()}),a.extend("MediaSourceController",function(){const{parent:i}=this,r=i.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>r(n),t&&s&&e?.()}}},!0)},xi=a=>{const e=new g(1/0),t=new _,s=new g(void 0),i=new g(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(p=>p.split(": ")));if("x-playback-duration"in u||"x-playback-duration-millis"in u){const p=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),T=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??p*1e3??NaN;A(T)&&!isNaN(T)&&e.next(T)}const f=u["x-delivery-type"]??Bt.HTTP1,S={1:!0,0:!1}[u["x-reused"]]??void 0;s.next(f),i.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(f){if(f.request.type==="MPD"){const S=f.onload,p=f.progress;f.onload=function(...m){return c(this),S(...m)},f.progress=function(...m){return d(this),p(...m)},o()}return u(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:i,connectionType$:s}},yt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Ci=a=>a.extend("RequestModifier",()=>({modifyRequestURL:yt}),!0),Li=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[i,r]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${i}-${r}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const Ne=(a,e,t,{equal:s=(n,o)=>n===o,changed$:i,onError:r}={})=>{const n=a.getState(),o=e(),c=W(i),d=new X;return i&&d.add(i.subscribe(h=>{const u=a.getState();s(h,u)&&a.setState(h)},r)),s(o,n)||(t(n),c&&a.setState(n)),d.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),c&&a.setState(h.to)},r)),d},ut=(a,e,t)=>Ne(e,()=>a.loop,s=>{A(s)&&(a.loop=s)},{onError:t}),ze=(a,e,t,s)=>Ne(e,()=>({muted:a.muted,volume:a.volume}),i=>{A(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,r)=>i===r||i?.muted===r?.muted&&i?.volume===r?.volume,changed$:t,onError:s}),tt=(a,e,t,s)=>Ne(e,()=>a.playbackRate,i=>{A(i)&&(a.playbackRate=i)},{changed$:t,onError:s}),Bi=a=>["__",a.language,a.label].join("|"),Mi=(a,e)=>{if(a.id===e)return!0;const[t,s,i]=e.split("|");return a.language===s&&a.label===i};class Oe{available$=new _;current$=new g(void 0);error$=new _;video;cueSettings;subscription=new X;externalTracks=new Map;connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const i=r=>{this.error$.next({id:"TextTracksManager",category:D.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:r})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Ne(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(E(r=>r.filter(({type:n})=>n==="external"))),onError:i})),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:i})),this.subscription.add(Ne(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const r of this.htmlTextTracksAsArray())this.applyCueSettings(r.cues),this.applyCueSettings(r.activeCues)}))}subscribe(){k(this.video);const{textTracks:e}=this.video;this.subscription.add(B(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(x(B(e,"addtrack"),B(e,"removetrack"),ke(["init"])).pipe(E(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),he((s,i)=>s.length===i.length&&s.every(({id:r},n)=>r===i[n].id))).subscribe(this.available$)),this.subscription.add(x(B(e,"change"),ke(["init"])).pipe(E(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),E(s=>s&&this.htmlTextTrackToITextTrack(s).id),he()).subscribe(this.current$));const t=s=>this.applyCueSettings(s.target?.activeCues??null);this.subscription.add(B(e,"addtrack").subscribe(s=>{s.track?.addEventListener("cuechange",t);const i=r=>{const n=r.target?.cues??null;n&&n.length&&(this.applyCueSettings(r.target?.cues??null),r.target?.removeEventListener("cuechange",i))};s.track?.addEventListener("cuechange",i)})),this.subscription.add(B(e,"removetrack").subscribe(s=>{s.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const i=s;A(t.align)&&(i.align=t.align),A(t.position)&&(i.position=t.position),A(t.size)&&(i.size=t.size),A(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){k(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Oe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=e.id!==""?e.id:Bi(e);return this.externalTracks.has(i)?{id:i,type:"external",language:t,label:s,url:this.externalTracks.get(i).url}:{id:i,type:"internal",language:t,label:s}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){k(this.video);for(const t of this.htmlTextTracksAsArray(!0))A(e)&&Mi(t,e)?t.mode="showing":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){k(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),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){k(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var We=a=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),a.appendChild(e),e};class hs{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var zs=()=>{const{userAgent:a}=window.navigator;return!/chrome/i.test(a)&&/webkit|safari|khtml/i.test(a)};const os=3;class Ni{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let i=this._source.buffered.start(t);const r=this._source.buffered.end(t);i>e&&i-e<os&&(i=e),this._buffer.push({from:i,to:r,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||os))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:i,to:r})=>{const n=i>=e&&i<t,o=r>=e&&r<t;n&&o||(n?s(t,r):o?s(i,e):i<e&&r>t?(s(t,r),s(i,e)):s(i,r))})}destroy(){this._buffer=[]}}var Ws=(a,e,t=os)=>{let s=0,i=0;for(let r=0;r<a.length;r++){const n=a.start(r),o=a.end(r);if(n<=e&&e<=o){if(s=n,i=o,!t)return{from:s,to:i};for(let c=r-1;c>=0;c--)a.end(c)+t>=s&&(s=a.start(c));for(let c=r+1;c<a.length;c++)a.start(c)-t<=i&&(i=a.end(c))}}return{from:s,to:i}};const Oi=50,Ui=a=>a.webkitAudioDecodedByteCount!=="undefined"?!!a.webkitAudioDecodedByteCount:a.mozHasAudio!=="undefined"?a.mozHasAudio:a.audioTracks?!!a.audioTracks.length:!0,Qe=a=>{const e=p=>B(a,p).pipe(ct(void 0)),s=x(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(p=>B(a,p))).pipe(E(p=>p.type==="ended"?a.readyState<2:a.readyState<3),he()),i=x(B(a,"progress"),B(a,"timeupdate")).pipe(E(()=>Ws(a.buffered,a.currentTime))),r=zs()?Ge({play:e("play").pipe(pe()),playing:e("playing")}).pipe(ct(void 0)):e("playing"),n=B(a,"playing").pipe(_e(Oi),E(()=>Ui(a))),o=B(a,"volumechange").pipe(E(()=>({muted:a.muted,volume:a.volume}))),c=B(a,"ratechange").pipe(E(()=>a.playbackRate)),d=B(a,"error").pipe(O(()=>Boolean(a.error||a.played.length)),E(()=>{const p=a.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:D.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=B(a,"timeupdate").pipe(E(()=>a.currentTime)),u=new _,f=.3;let S;return h.subscribe(p=>{a.loop&&A(S)&&A(p)&&S>=a.duration-f&&p<=f&&u.next(S),S=p}),{playing$:r,pause$:e("pause").pipe(O(()=>!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$:B(a,"durationchange").pipe(E(()=>a.duration)),isBuffering$:s,currentBuffer$:i,volumeState$:o,isAudioAvailable$:n,playbackRateState$:c}},us=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let ls=!1,qe={};const Vi=a=>{ls=a},Fi=()=>{qe={}},Hi=a=>{a(qe)},Ft=(a,e)=>{ls&&(qe.meta=qe.meta??{},qe.meta[a]=e)};class Be{name;constructor(e){this.name=e}next(e){if(!ls)return;qe.series=qe.series??{};const t=qe.series[this.name]??[];t.push([Date.now(),e]),qe.series[this.name]=t}}const Yi=new Be("best_bitrate"),qi=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class Gi{last;history={};recordSelection(e){this.history[e.id]=ce()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Nt=(a,{container:e,throughput:t,tuning:s,limits:i,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:c,history:d})=>{const h=s.usePixelRatio?window.devicePixelRatio??1:1,u=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*s.containerSizeFactor,height:e.height*h*s.containerSizeFactor},f=u&&ht(u),S=s.considerPlaybackRate&&A(o)?o:1,p=a.filter(H=>!Wt(H.quality)).sort((H,ie)=>Gt(H.quality,ie.quality)?-1:1),m=p.at(-1)?.quality,T=p.at(0)?.quality,P=W(i)||A(i.min)&&A(i.max)&&It(i.max,i.min)||A(i.min)&&T&&Gt(i.min,T)||A(i.max)&&m&&It(i.max,m),L=S*qi(n??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),$=p.filter(H=>{const ie=f?It(H.quality,f):!0,Y=A(t)&&isFinite(t)&&A(H.bitrate)?t-r>=H.bitrate*L:!0,J=s.lazyQualitySwitch&&A(s.minBufferToSwitchUp)&&c&&!Wt(c.quality)&&(n??0)<s.minBufferToSwitchUp&&Gt(H.quality,c.quality),ne=P||(W(i.max)||yi(H.quality,i.max))&&(W(i.min)||bi(H.quality,i.min));return ie&&Y&&!J&&ne})[0];$&&$.bitrate&&Yi.next($.bitrate);const v=$??p[Math.ceil((p.length-1)/2)]??a[0],F=v&&d&&d.history[v.id]&&ce()-d.history[v.id]<=s.trackCooldown&&(!d.last||v.id!==d.last.id);if(v?.id&&d&&!F&&d.recordSelection(v),F&&d?.last){const H=d.last;return d?.recordSwitch(H),H}return d?.recordSwitch(v),v};var ve=a=>new URL(a).hostname;const zi=300,jt=(a,e=zi)=>new Mt(t=>{const{width:s,height:i}=a.getBoundingClientRect();if(t.next({width:s,height:i}),!window.ResizeObserver)return;const r=new ResizeObserver(li(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()}),Wi=5e3,Pt={};var U;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(U||(U={}));const fe=(a,e)=>new Mt(t=>{const s=i=>t.next(i);return a.on(e,s),()=>a.off(e,s)});class bs{subscription=new X;videoState=new re(U.DOWNLOADING_LIB);video;player;params;textTracksManager=new Oe;videoTracks=[];frameRatesByFrameHeight={};isLive$=new g(void 0);maxSeekBackTime$=new g(1/0);availableFrom$=new g(void 0);elementSize$=new g(void 0);liveOffset=new hs;destroyBigRequest;constructor(e){this.video=We(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(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:D.NETWORK,message:`Dash.js failed to load: ${i?.toString?.()}`,thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),Wi);import("dashjs/dist/dash.mediaplayer.min.js").then(i=>{e||(Pt.MediaPlayer=i.MediaPlayer,Pt.Debug=i.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){k(Pt.MediaPlayer,"dashjs not loaded"),k(Pt.Debug,"dashjs not loaded"),this.player=Pt.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(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?us(t.frameRate+""):void 0),!0)),(this.params.format===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=_i(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&Li(this.player),Ii(this.player),this.params.tuning.requestQuick&&Ci(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(U.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=m=>{e.error$.next({id:"DashIFProvider",category:D.WTF,message:"DashIFProvider internal logic error",thrown:m})},i=(m,T)=>this.subscription.add(m.subscribe(T,s));i(jt(this.video),this.elementSize$),i(fe(this.player,"error").pipe(E(m=>{const T=typeof m.error=="object"?m.error.code:m.error,P=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${T}`,message:P}})),e.error$),i(fe(this.player,"playbackError").pipe(E(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const r=fe(this.player,"qualityChangeRendered").pipe(O(({mediaType:m})=>m==="video"),E(({newQuality:m})=>this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===m)?.track));r.pipe(O(A)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(O(({to:m})=>m===U.STREAM_INITIALIZED),pe()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===m)?.track?.id},m=>{if(W(m))return;const T=this.videoTracks.find(({track:P})=>P.id===m)?.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:r.pipe(E(m=>m?.id)),onError:s}))},s)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:s})),i(fe(this.player,"bufferStateChanged").pipe(O(({mediaType:m})=>m==="video"),E(({state:m})=>m==="bufferStalled")),e.isBuffering$),i(fe(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:T}})=>{const P=this.player.getDashMetrics(),L=P.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),se=P.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??Bt.HTTP1,$={1:!0,0:!1}[L]??void 0;this.params.output.httpConnectionType$.next(se),this.params.output.httpConnectionReused$.next($),e.hostname$.next(ve(T))}),i(fe(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:T,availableFrom:P}}})=>{this.isLive$.next(T),this.availableFrom$.next(P.getTime()),T||e.duration$.next(m),this.videoTracks=[];const L=this.player.getQualityFor("video");let se;for(const $ of this.player.getBitrateInfoListFor("video")){const v=$.qualityIndex.toString(10),F=ht($),H=$.bitrate/1e3,ie={width:$.width,height:$.height},Y=this.frameRatesByFrameHeight[$.height];if(F){const J={id:v,quality:F,bitrate:H,size:ie,fps:Y};this.videoTracks.push({track:J,bitrateInfo:$}),$.qualityIndex===L&&(se=J)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:$})=>$)),se&&e.currentVideoTrack$.next(se),this.videoState.setState(U.STREAM_INITIALIZED),this.videoState.startTransitionTo(U.READY)}),i(fe(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const T=m.requestEndDate.getTime()-m.firstByteDate.getTime(),P=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(P,T)}),i(x(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=Nt(this.videoTracks.map(({track:L})=>L),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),P=this.videoTracks.find(({track:L})=>L===T);P?.bitrateInfo&&this.player.setQualityFor("video",P?.bitrateInfo.qualityIndex,!1)}),i(Ge({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(O(A))}).pipe(O(({isLive:m})=>m),E(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=fe(this.player,"playbackTimeUpdated").pipe(E(({time:m})=>m??0));i(Ge({availableFrom:this.availableFrom$.pipe(O(A)),currentTime:n}),({availableFrom:m,currentTime:T})=>this.params.output.liveTime$.next(m+T*1e3)),i(n.pipe(O(()=>this.isLive$.getValue()===!1)),e.position$),i(fe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),i(fe(this.player,"playbackEnded"),e.endedEvent$),i(fe(this.player,"playbackProgress").pipe(E(()=>Ws(this.video.buffered,this.video.currentTime))),e.currentBuffer$),i(fe(this.player,"playbackPlaying"),()=>{this.videoState.setState(U.PLAYING),w(t.playbackState,l.PLAYING)}),i(fe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(U.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),i(fe(this.player,"playbackPaused"),()=>{this.videoState.setState(U.PAUSED),w(t.playbackState,l.PAUSED)}),i(fe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY)}),i(this.isLive$,e.isLive$),i(jt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0));i(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:h,connectionReused$:u}=xi(this.player);i(h,this.params.output.httpConnectionType$),i(u,this.params.output.httpConnectionReused$),i(c,this.maxSeekBackTime$),i(d.pipe(pe()),e.firstBytesEvent$),i(fe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&i(Ge({isLive:this.isLive$,isShort:e.duration$.pipe(E(m=>m<60))}),({isLive:m,isShort:T})=>{const P=!m&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:P}}})}),i(n.pipe(O(m=>m>this.params.tuning.insufficientBufferRuleMargin),pe()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(fe(this.player,"manifestLoaded").pipe(pe()).subscribe(()=>{this.subscription.add(fe(this.player,"playbackPlaying").pipe(pe(),ct(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(ut(this.video,t.isLooped,s));const{volumeState$:f,looped$:S,playbackRateState$:p}=Qe(this.video);this.subscription.add(ze(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(S.subscribe(e.loopedEvent$)),this.subscription.add(tt(this.video,t.playbackRate,p,s))}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(U.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(U.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,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const i=gt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,St.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(U.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(U.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===U.DOWNLOADING_LIB||e===U.STREAM_INITIALIZED))switch(s?.to!==l.PAUSED&&i.state===M.Requested&&e!==U.STOPPED&&t!==l.STOPPED&&(r?this.seek(i.position-this.liveOffset.getTotalPausedTime()):this.seek(i.position)),t){case l.STOPPED:{switch(e){case U.STOPPED:break;case U.PLAYING:case U.PAUSED:case U.READY:this.stop();break;default:C(e)}break}case l.READY:{switch(e){case U.STOPPED:this.prepare();break;case U.PLAYING:case U.PAUSED:case U.READY:break;default:C(e)}break}case l.PLAYING:{switch(e){case U.PLAYING:break;case U.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 U.READY:this.play();break;case U.STOPPED:this.prepare();break;default:C(e)}break}case l.PAUSED:{switch(e){case U.PLAYING:this.pause(),this.liveOffset.pause();break;case U.PAUSED:break;case U.READY:this.videoState.setState(U.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED);break;case U.STOPPED:this.prepare();break;default:C(e)}break}default:C(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch{}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Ot=a=>{switch(a){case"mobile":return te.Q_144P;case"lowest":return te.Q_240P;case"low":return te.Q_360P;case"sd":case"medium":return te.Q_480P;case"hd":case"high":return te.Q_720P;case"fullhd":case"full":return te.Q_1080P;case"quadhd":case"quad":return te.Q_1440P;case"ultrahd":case"ultra":return te.Q_2160P}},st=async a=>{const e=a.muted;try{await a.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(s){return a.muted=!1,console.warn(s),!1}}return!0};function ye(){return ce()}function Qs(a){return ye()-a}function ys(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,i=n=>s.test(n);return{resolve:(n,o,c=!1)=>{i(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 Qi(a,e,t){const s=(...i)=>{t.apply(null,i),a.removeEventListener(e,s)};a.addEventListener(e,s)}function zt(a,e,t,s){const i=window.XMLHttpRequest;let r,n,o,c=!1,d=0,h,u,f=!1,S="arraybuffer",p=7e3,m=2e3,T=()=>{if(c)return;k(h);const j=Qs(h);let le;if(j<m){le=m-j,setTimeout(T,le);return}m*=2,m>p&&(m=p),n&&n.abort(),n=new i,F()};const P=j=>(r=j,ne),L=j=>(u=j,ne),se=()=>(S="json",ne),$=()=>{if(!c){if(--d>=0){T(),s&&s();return}c=!0,u&&u(),t&&t()}},v=j=>(f=j,ne),F=()=>{h=ye(),n=new i,n.open("get",a);let j=0,le,Le=0;const je=()=>(k(h),Math.max(h,Math.max(le||0,Le||0)));if(r&&n.addEventListener("progress",I=>{const K=ye();r.updateChunk&&I.loaded>j&&(r.updateChunk(je(),I.loaded-j),j=I.loaded,le=K)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(c)return;k(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&r){const K=n.response.byteLength-j;K&&r.updateChunk&&r.updateChunk(je(),K)}u&&u(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),f){const I=()=>{k(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=ye(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=S,n.send(),ne},ne={withBitrateReporting:P,withParallel:v,withJSONResponse:se,withRetryCount:j=>(d=j,ne),withRetryInterval:(j,le)=>(A(j)&&(m=j),A(le)&&(p=le),ne),withTimeout:j=>(o=j,ne),withFinally:L,send:F,abort:()=>{n&&(n.abort(),n=void 0),c=!0,u&&u()}};return ne}const ji=100,Ji=2e3,Xi=500;let Ki=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,s){return{start:e,end:t,bytes:s}}_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-Xi;if(t-e>Ji){let s=0,i=0;for(;this.intervals.length>0;){const r=this.intervals[0];if(r.end<=t)s+=r.end-r.start,i+=r.bytes,this.intervals.splice(0,1);else{if(r.start>=t)break;{const n=t-r.start,o=r.end-r.start;s+=n;const c=r.bytes*n/o;i+=c,r.start=t,r.bytes-=c}}}if(i>0&&s>0){const r=i*8/(s/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(i)}/${Math.round(s)} 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,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>ji&&(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 Zi{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,i,r){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,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 s=ye(),i=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()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=zt(t,r,()=>i("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 s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!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,s,i){const r={};return r.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=i,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}`),s(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=s,r._retryCB=i,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 Ht=1e4,Yt=3,ea=300,ta=2e3,sa=6e4,ia=10,aa=1,ra=500;class na{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 Ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ys(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],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=ys(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 s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-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",()=>{Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.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,s=t.buffered.length;let i;s!==0&&(i=t.buffered.start(s-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){const{videoElement:t}=this.params;let s,i,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)?(!i||r.bitrate>i.bitrate)&&(i=r):(!s||s.bitrate>r.bitrate)&&(s=r));return i||s}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:s,videoElement:i,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{Qi(i,"progress",()=>{i.buffered.length?(i.currentTime=i.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 Zi(Yt,Ht,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:i}=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!"),$},f=($,v,F)=>{c&&c.abort(),c=zt(this.urlResolver.resolve($,!1),v,F,()=>this._retryCallback()).withTimeout(Ht).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Yt).withFinally(()=>{c=null}).send()},S=($,v,F)=>{k(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),v,F,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},p=$=>{const v=s.playbackRate;s.playbackRate!==$&&(t(`Playback rate switch: ${v}=>${$}`),s.playbackRate=$)},m=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),T()},T=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)p(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}const F=ye()-1e4;let H=0;for(let Y=0;Y<this.bufferStates.length;Y++){const J=this.bufferStates[Y];$=Math.min($,J.buf),J.ts<F&&H++}this.bufferStates.splice(0,H),t(`update playback rate; minBuffer=${$} drop=${H} jitter=${this.sourceJitter}`);let ie=$-aa;this.sourceJitter>=0?ie-=this.sourceJitter/2:this.sourceJitter-=1,ie>3?p(1.15):ie>1?p(1.1):ie>.3?p(1.05):p(1)}},P=$=>{let v;const F=()=>v&&v.start?v.start.length:0,H=I=>v.start[I]/1e3,ie=I=>v.dur[I]/1e3,Y=I=>v.fragIndex+I,J=(I,K)=>({chunkIdx:Y(I),startTS:H(I),dur:ie(I),discontinuity:K}),ne=()=>{let I=0;if(v&&v.dur){let K=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,me=K;this.sourceJitter>1&&(me+=this.sourceJitter-1);let Ee=v.dur.length-1;for(;Ee>=0&&(me-=v.dur[Ee],!(me<=0));--Ee);I=Math.min(Ee,v.dur.length-1-ue),I=Math.max(I,0)}return J(I,!0)},j=I=>{const K=F();if(!(K<=0)){if(A(I)){for(let ue=0;ue<K;ue++)if(H(ue)>I)return J(ue)}return ne()}},le=I=>{const K=F(),ue=I?I.chunkIdx+1:0,me=ue-v.fragIndex;if(!(K<=0)){if(!I||me<0||me-K>ia)return t(`Resync: offset=${me} bChunks=${K} chunk=`+JSON.stringify(I)),ne();if(!(me>=K))return J(ue-v.fragIndex,!1)}},Le=(I,K,ue)=>{d&&d.abort(),d=zt(this.urlResolver.resolve(I,!0,this.lowLatency),K,ue,()=>this._retryCallback()).withTimeout(Ht).withRetryCount(Yt).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,K)=>{Le($,ue=>{if(!u())return;v=ue;const me=Boolean(v.lowLatency);me!==this.lowLatency&&m(me);let Ee=0;for(let Je=0;Je<v.dur.length;++Je)Ee+=v.dur[Je];Ee>0&&(k(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/v.dur.length)),i({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,I(j(K))},()=>this._handleNetworkError())},nextChunk:le}},L=()=>{r=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),k(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:$=>{const{videoElement:v,logger:F}=this.params;let H=P(e.jidxUrl),ie,Y,J,ne,j=0,le,Le,je;const I=()=>{le&&(clearTimeout(le),le=void 0);const q=Math.max(ra,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=j+q,Se=ye(),be=Math.min(1e4,ge-Se);j=Se;const Ve=()=>{d||u()&&H.seek(()=>{u()&&(j=ye(),K(),I())})};be>0?le=window.setTimeout(()=>{this.paused?I():Ve()},be):Ve()},K=()=>{let q;for(;q=H.nextChunk(ne);)ne=q,At(q);const ge=H.nextChunk(J);if(ge){if(J&&ge.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?I():(L(),this._initPlayerWith(e));return}Je(ge)}else I()},ue=(q,ge)=>{if(!u()||!this.sourceBuffer)return;let Se,be,Ve;const Fe=Ie=>{window.setTimeout(()=>{u()&&ue(q,ge)},Ie)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),Fe(100);else{const Ie=ye(),Xe=v.currentTime;!this.paused&&v.buffered.length>1&&Le===Xe&&Ie-je>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),Le!==Xe&&(Le=Xe,je=Ie);const Ke=this._getBufferSizeSec();if(Ke>30)F(`Buffered ${Ke} seconds; delaying appendBuffer`),Fe(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:Ie,buf:Ke}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Ze){if(Ze.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Ve=this.sourceBuffer.buffered.length,Ve!==0&&(Se=this.sourceBuffer.buffered.start(0),be=Xe,be-Se>4&&this.sourceBuffer.remove(Se,be-3)),Fe(1e3);else throw Ze}}},me=()=>{Y&&ie&&(F([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(J)]),ue(Y,function(){Y=null,K()}))},Ee=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),Je=q=>{u()&&S(Ee(q),(ge,Se)=>{if(u()){if(Se/=1e3,Y=ge,J=q,n=q.startTS,Se){const be=Math.min(10,q.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}me()}},()=>this._handleNetworkError())},At=q=>{u()&&(k(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(q),!1)))},Vt=q=>{u()&&(e.cachedHeader=q,ue(q,()=>{ie=!0,me()}))};r=!0,H.seek(q=>{if(u()){if(j=ye(),!q){I();return}ne=q,!W($)||q.startTS>$?Je(q):(J=q,K())}},$),e.cachedHeader?Vt(e.cachedHeader):f(e.headerUrl,Vt,()=>this._handleNetworkError())},stop:L,getTimestampSec:()=>n},h}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),A(i)&&(i+=.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,k(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return A(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=u=>{if(!this.autoQuality)return;let f,S,p;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&u<this.bitrate&&(S=this._getBufferSizeSec(),p=u/this.bitrate,S>10&&p>.8||S>15&&p>.5||S>20&&p>.3)){e(`Not switching: buffer=${Math.floor(S)}; bitrate=${this.bitrate}; newRate=${Math.floor(u)}`);return}f=this._selectQuality(u),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${u}`)},r=(()=>({updateChunk:(f,S)=>{const p=ye();if(this.chunkRateEstimator.addInterval(f,p,S)){const T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:S,duration:p-f,speed:T}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let u=r.get();if(u&&o&&this.autoQuality){if(c&&u>o&&Qs(n)<3e4)return;s(u)}c=this.autoQuality};return{updateChunk:(u,f)=>{const S=r.updateChunk(u,f);return S&&d(),S},notifySwitch:u=>{const f=ye();u<o&&(n=f),o=u}}}_fetchManifest(e,t,s){this.manifestRequest=zt(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Ht).withRetryCount(Yt).withRetryInterval(ea,ta).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;st(t).then(s=>{s||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params,r=n=>{const o=[];return n?.length?(n.forEach((c,d)=>{c.video&&i.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}`),s({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))},sa))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var V;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(V||(V={}));const oa=[V.PAUSED,V.PLAYING,V.READY],da=[V.PAUSED,V.PLAYING,V.READY];class ca{subscription=new X;video;videoState=new re(V.STOPPED);dash;representations$=new g([]);textTracksManager=new Oe;maxSeekBackTime$=new g(1/0);zeroTime$=new g(void 0);liveOffset=new hs;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=i=>{e.output.error$.next({id:"DashLiveProvider",category:D.WTF,message:"DashLiveProvider internal logic error",thrown:i})};x(this.videoState.stateChangeStarted$.pipe(E(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(E(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(i)}`})}),this.video=We(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.hostname$.next(ve(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 s=Qe(this.video);this.subscription.add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===M.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(V.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(he(),E(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Ge({zeroTime:this.zeroTime$.pipe(O(A)),position:s.timeUpdate$}).subscribe(({zeroTime:i,position:r})=>this.params.output.liveTime$.next(i+r*1e3),t)).add(ut(this.video,this.params.desiredState.isLooped,t)).add(ze(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(tt(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:i}})=>{const r=i&&vi(i);this.dash.setMaxAutoQuality(r)})).add(this.videoState.stateChangeEnded$.subscribe(i=>{switch(i.to){case V.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case V.MANIFEST_READY:case V.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case V.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case V.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return C(i.to)}},t)).add(x(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new na({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(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),i=!s&&A(t)?t:Nt(e.map(({track:n})=>n),{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()})?.id,r=e.find(({track:n})=>n.id===i)?.representation;k(r,"Representations missing"),this.dash.startPlay(r,s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(s)}setVideoTrack(e){const t=this.representations$.getValue().find(({track:s})=>s.id===e)?.representation;k(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=-e,s=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(s),this.dash.reinit(gt(this.params.source.url,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:D.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,s=[];for(const i of t){const r=i.name??i.index.toString(10),n=Ot(i.name)??ht(i.video),o=i.bitrate/1e3,c={...i.video};if(!n)continue;const d={id:r,quality:n,bitrate:o,size:c};s.push({track:d,representation:i})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map(({track:i})=>i)),this.videoState.getTransition()?.to===V.MANIFEST_READY&&this.videoState.setState(V.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,s=this.representations$.getValue().find(({representation:i})=>i===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),A(s)&&this.params.output.currentVideoTrack$.next(s);break}case"bandwidth":{const{size:t,duration:s}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,s);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(r)};`}),s===l.STOPPED){e!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(V.STOPPED));return}if(!t){if(da.includes(e)){const n=this.params.desiredState.videoTrack.getTransition()?.to;A(n)&&this.setVideoTrack(n);const o=this.params.desiredState.autoVideoTrackSwitching.getTransition();o&&this.setAutoQuality(o.to)}if(i?.to!==l.PAUSED&&r.state===M.Requested&&oa.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case V.STOPPED:this.videoState.startTransitionTo(V.MANIFEST_READY),this.dash.attachSource(gt(this.params.source.url));return;case V.MANIFEST_READY:this.videoState.startTransitionTo(V.READY),this.prepare();break;case V.READY:if(s===l.PAUSED)this.videoState.setState(V.PAUSED);else if(s===l.PLAYING){this.videoState.startTransitionTo(V.PLAYING);const n=i?.from;n&&n===l.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(V.PAUSED)})}return;case V.PLAYING:s===l.PAUSED&&(this.videoState.startTransitionTo(V.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case V.PAUSED:s===l.PLAYING&&(this.videoState.startTransitionTo(V.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(V.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return C(e)}}}}var js=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),s=e===null?Bt.HTTP1:e??void 0,i=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:s,reused:i}},nt=(a,e)=>{let t=0;for(let s=0;s<a.length;s++){const i=a.start(s)*1e3,r=a.end(s)*1e3;i<=e&&e<=r&&(t=r)}return Math.max(t-e,0)};const ha=a=>{const e=document.createElement("a");return e.href=a,e.origin},ua=a=>{const e=document.createElement("a");return e.href=a,e.host};class Js{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,i,r,n){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=i,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(k(this._xhr),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(s=>s.split(":").map(i=>i.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(ua(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 Jt{_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(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const i=this._sourceBuffer.buffered;let r=0;for(let n=0,o=i.length;n<o;n++)r+=i.end(n)-i.start(n);r&&(this._maxBufferDuration=Math.round(r))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,i,r,n,o){this.abort(()=>{let c=0;const d=Date.now();let h=0,u=0,f=0;const S=m=>{i(Jt._str2ua(m.substr(c))),c=m.length};let p=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(p=yt(p)),this._lastXhr=new Js(p,e.failoverHosts,m=>{this._lastXhr=void 0,S(m);const T=Date.now()-d;this._params.onBandwidthChange({size:m.length,duration:T,speed:8*m.length/(T/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),r?.()},m=>{if(m.length-c>o&&S(m),u===0){u=Date.now();return}f=m.length-h;const T=Date.now()-u;f>=100*1024&&T>=1e3&&(this._params.onBandwidthChange({size:f,duration:T,speed:8*f/(T/1e3)}),f=0,h=m.length,u=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},n,(m,T,P)=>this._params.onError(m,T,P))})}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(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};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=Jt._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 s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);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 la{_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)?)?$/,s=(o,c)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*c},i=t.exec(e),r=i?.[1]==="-"?-1:1,n={years:s(i?.[2],r),months:s(i?.[3],r),weeks:s(i?.[4],r),days:s(i?.[5],r),hours:s(i?.[6],r),minutes:s(i?.[7],r),seconds:s(i?.[8],r)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=yt(s)),new Js(s,t,i=>{this.attachManifest(i,t,ha(s))},void 0,i=>{this._params.onResponseHeaders(i)},(i,r,n)=>this._params.onError(i,r,n))}attachManifest(e,t,s){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("-"),f=h&&h.getElementsByTagName("Initialization")[0],S=f&&n(f,"range").split("-");if(!S||!u){const se=d.parentElement;if(se?.getAttribute("contentType")==="text"){const $=d.getAttribute("id")??void 0,v=(s?s+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,F=se.getAttribute("lang")??void 0;v&&c.push({id:$,url:v,language:F})}return}const p=.1,m=Number(d.attributes.getNamedItem("bandwidth")?.value),T=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let P;const L=d.attributes.getNamedItem("frameRate")?.value??void 0;P=L?us(L):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:m,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:P,bufferSize:p*m/8,bufferLength:p,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 f=document.createElement("track");f.setAttribute("src",u),d&&f.setAttribute("id",d),h&&f.setAttribute("srclang",h),this._video.appendChild(f)}),this._representations.sort((d,h)=>h.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,i=>{let r=e.initTo-e.initFrom+1;if(!i.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(i.buffer,0,r);const n=new DataView(i.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 f=0;f<h;f+=1){const S=d+(n.getUint32(r,!1)&2147483647),p=c+n.getUint32(r+4,!1);r+=12,e.refs.push({fromTime:c/o,toTime:p/o,fromOffset:d,toOffset:S-1}),d=S,c=p}const u=e.refs[e.refs.length-1];u.toTime-u.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,i=>{this._params.onResponseHeaders(i),this._params.onIdxRequestPing(Date.now()-s)},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 s=new t;let i,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!==i&&(i=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 p=this._buffer.getNextWithGap(S);p&&(this._video.currentTime=p.from)}catch(p){throw this._params.onError("GapSyncError",`Seek Error ${String(p)}`,p),p}},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=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Jt({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",c),s.removeEventListener("webkitsourceopen",c)};s.addEventListener("sourceopen",c,!1),s.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1,i=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const r=this._findRef(t);if(r){if(s){this._isLastRef(r)&&t>=r.toTime&&(t=r.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),c=i||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 s=this._buffer.getByTime(this._video.currentTime),i=this._findRef(this._video.currentTime);if(!s||!i){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const r=.1;if(i.toTime<s.to+r){const n=this._findRef(i.toTime);n&&n.toTime<s.to+r?(this._buffer.smartRemove(i.fromTime-r,n.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(i.fromTime-r,i.toTime+r,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,i.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||W(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 s;for(let i=0;i<t.length;i++){const r=t[i];if(r.fromTime<=e&&r.toTime>e)return r;r.fromTime>e&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const i=t[t.length-1];if(e>i.toTime)return i}return s}_isLastRef(e){const t=this._currentRepresentation?.refs;if(!t)return!1;const s=t[t.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),i=this._video.buffered.end(t);if(e>s&&e<i)return Math.round(i*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var G;(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"})(G||(G={}));const fa=[G.PAUSED,G.PLAYING];class pa{videoState=new re(G.STOPPED);subscription=new X;video;buffer;dash;representations$=new g([]);currentRepresentation$=new g(void 0);params;textTracksManager=new Oe;elementSize$=new g(void 0);dashLiteEvents={idxRequestPing$:new _,responseHeaders$:new _,manifestReady$:new _,representationPlay$:new _,error$:new _};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),x(this.videoState.stateChangeStarted$.pipe(E(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(E(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=We(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(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Ni(this.video),this.dash=new la({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:i,category:D.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,s=o=>{e.error$.next({id:"DashProvider",category:D.WTF,message:"DashProvider internal logic error",thrown:o})},i=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:o},r=Qe(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,s));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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(r.seeking$.subscribe(()=>{W(this.params.desiredState.seekState.getState().state!==M.Applying)&&(this.videoState.getState()===G.PLAYING||this.videoState.getState()===G.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(ut(this.video,t.isLooped,s)),this.subscription.add(ze(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(tt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(jt(this.video),this.elementSize$),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)})).add(r.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,l.PLAYING)},s)).add(r.loadedMetadata$.subscribe(()=>{this.videoState.setState(G.METADATA_LOADED)},s)).add(r.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe(E(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:D.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(x(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,B(this.video,"progress")).pipe(E(()=>{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(),f=this.elementSize$.getValue(),S=i();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let p;if(!S&&A(h))p=h;else{const m=nt(this.video.buffered,this.video.currentTime*1e3),T=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,P=Math.min(m/T,1);p=Nt(c.map(({track:L})=>L),{container:f,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:P,playbackRate:this.video.playbackRate,current:c.find(({representation:L})=>L===o)?.track})?.id}return A(p)?c.find(({track:m})=>m.id===p)?.representation:void 0}),he()).subscribe(this.currentRepresentation$,s)).add(Ge({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(O(o=>o.to===G.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(O(A))}).pipe(pe()).subscribe(()=>this.videoState.setState(G.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(O(A),he((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&i()?o.height<=c.height:o===c)).subscribe(o=>{const c=nt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!i())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(ve(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:c,reused:d}=js(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(pe(),ct(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,s)).add(this.dashLiteEvents.representationPlay$.pipe(O(A)).subscribe(this.handleRepresentationPlay,s)).add(x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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 C(e)}}handleManifestReady=e=>{const t=[];for(const s of e){const i=s.name??s.id??s.height.toString(10),r=(s.name&&Ot(s.name))??ht(s),n=s.bandwidth/1e3,o={width:s.width,height:s.height},c=s.fps;if(!r)continue;const d={id:i,quality:r,bitrate:n,size:o,fps:c};t.push({track:d,representation:s})}this.representations$.next(t),this.params.output.availableVideoTracks$.next(t.map(({track:s})=>s)),this.videoState.setState(G.MANIFEST_LOADED)};handleRepresentationPlay=e=>{const t=this.representations$.getValue().find(({representation:s})=>s===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 k(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(){st(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(r)};`}),s===l.STOPPED){e!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.dash.destroy(),this.video.setAttribute("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(G.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(!t)switch(i?.to!==l.PAUSED&&r.state===M.Requested&&fa.includes(e)&&this.seek(r.position,r.forcePrecise),e){case G.STOPPED:this.videoState.startTransitionTo(G.MANIFEST_LOADED),this.prepare();return;case G.MANIFEST_LOADED:this.videoState.startTransitionTo(G.INITIAL_REPRESENTATION_SELECTED);return;case G.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(G.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case G.METADATA_LOADED:this.videoState.startTransitionTo(G.READY),this.dash.updateRefsForCurrentTime();return;case G.READY:s===l.READY?w(this.params.desiredState.playbackState,l.READY):s===l.PAUSED?(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)):s===l.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:s===l.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.video.pause()):i?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case G.PAUSED:s===l.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed()):i?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;default:return C(e)}}}var Re;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Re||(Re={}));var Xt;(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"})(Xt||(Xt={}));var Pe;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Pe||(Pe={}));var Q;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(Q||(Q={}));var Tt;(function(a){a.MP4="mp4",a.WEBM="webm"})(Tt||(Tt={}));var Kt;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(Kt||(Kt={}));var ds=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const ma=(a,e={})=>{const s=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Sa=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ts=Sa?ma:window.requestIdleCallback;let Xs=!1;try{Xs=zs()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class ga{bufferFull$=new _;error$=new _;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(s=>{const i={operation:"append",data:e,signal:t,callback:s};this.queue.push(i),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(i=>{const r={operation:"remove",from:e,to:t,signal:s,callback:i};this.queue.unshift(r),this.pull()})}async abort(e){return new Promise(t=>{let s;Xs&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:i}of this.queue)i(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}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:D.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(i){i instanceof DOMException&&i.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):i instanceof DOMException&&i.name==="InvalidStateError"&&t==="remove"||this.error$.next({id:`BufferTaskQueue:${t}`,category:D.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:i}),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:C(t)}}}var Es=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class Ue{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 i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Ks extends Ue{}class ba extends Ue{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 s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class ya extends Ue{parseChildrenBoxes(){return vt(this.content)}}class Ta extends Ue{data;constructor(e){super(e),this.data=this.content}}class Ut extends Ue{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Ea 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 s=this.readUint32();const i=s>>>31,r=s<<1>>>1,n=this.readUint32();s=this.readUint32();const o=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:i,referencedSize:r,subsegmentDuration:n,SAPType:o,SAPDeltaTime:c})}}}class va extends Ue{parseChildrenBoxes(){return vt(this.content)}}class Aa extends Ue{parseChildrenBoxes(){return vt(this.content)}}var rt;(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"})(rt||(rt={}));class ka extends Ut{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=rt.MONOSCOPIC;break;case 1:this.stereoMode=rt.TOP_BOTTOM;break;case 2:this.stereoMode=rt.LEFT_RIGHT;break;case 3:this.stereoMode=rt.STEREO_CUSTOM;break;case 4:this.stereoMode=rt.RIGHT_LEFT;break}this.cursor+=1}}class wa extends Ut{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class $a 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 Ra extends Ue{parseChildrenBoxes(){return vt(this.content)}}class Pa 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 Da extends Ue{parseChildrenBoxes(){return vt(this.content)}}class _a extends Ue{parseChildrenBoxes(){return vt(this.content)}}const Ia={ftyp:ba,moov:ya,mdat:Ta,sidx:Ea,trak:va,mdia:Ra,tkhd:Pa,minf:Da,sv3d:Aa,st3d:ka,prhd:wa,proj:_a,equi:$a,unknown:Ks};class xa{createBox(e,t){const s=Ia[e];return s?new s(t):new Ks(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return ss.createBox(s,new DataView(e.buffer,e.byteOffset))}}const ss=new xa;function _t(a,e){const t=new TextDecoder("ascii");let s=a.byteOffset,i=[];for(;s<a.byteLength;){const r=t.decode(new DataView(a.buffer,s,1));if(r===e[i.length]?i.push(r):i=[],i.length===4&&i.join("")===e){const o=new DataView(a.buffer,s-7,4).getUint32(0);return s-7+o>a.byteLength?null:ss.createBox(e,new DataView(a.buffer,s-7))}s++}return null}function Ca(a,e){const t=[];let s=a.byteOffset;for(;s<a.byteLength;){const i=_t(new DataView(a.buffer,s,a.byteLength),e);if(i)t.push(i),s+=i.source.byteOffset+i.source.byteLength;else break}return t}function vt(a){const e=[];let t=0;for(;t<a.byteLength;){const s=ss.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const La=new TextDecoder("ascii"),Ba=a=>La.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Ma=a=>{const e=ss.createFromView(a);let t=e.earliestPresentationTime/e.timescale*1e3,s=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:Q.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+r.referencedSize-1}};return t+=n,s+=r.referencedSize,o})},Na=a=>{const e=Ca(a,"mdat");if(e.length){const t=e.reduce((s,i)=>s+i.size,0);return new DataView(a.buffer,a.byteOffset,t)}return null},Oa=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Kt.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(_t(a,"sv3d")){e.is3dVideo=!0;const s=_t(a,"st3d");s&&(e.stereoMode=s.stereoMode);const i=_t(a,"prhd");i&&(e.projectionData.pose.yaw=i.poseYawDegrees,e.projectionData.pose.pitch=i.posePitchDegrees,e.projectionData.pose.roll=i.poseRollDegrees);const r=_t(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},Ua={validateData:Ba,parseInit:Oa,getIndexRange:()=>{},parseSegments:Ma,parseFeedableSegmentChunk:Na};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 R;(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"})(R||(R={}));const vs={[y.EBML]:{type:R.Master},[y.EBMLVersion]:{type:R.UnsignedInteger},[y.EBMLReadVersion]:{type:R.UnsignedInteger},[y.EBMLMaxIDLength]:{type:R.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:R.UnsignedInteger},[y.DocType]:{type:R.String},[y.DocTypeVersion]:{type:R.UnsignedInteger},[y.DocTypeReadVersion]:{type:R.UnsignedInteger},[y.Void]:{type:R.Binary},[y.Segment]:{type:R.Master},[y.SeekHead]:{type:R.Master},[y.Seek]:{type:R.Master},[y.SeekID]:{type:R.Binary},[y.SeekPosition]:{type:R.UnsignedInteger},[y.Info]:{type:R.Master},[y.TimestampScale]:{type:R.UnsignedInteger},[y.Duration]:{type:R.Float},[y.Tracks]:{type:R.Master},[y.TrackEntry]:{type:R.Master},[y.Video]:{type:R.Master},[y.Projection]:{type:R.Master},[y.ProjectionType]:{type:R.UnsignedInteger},[y.ProjectionPrivate]:{type:R.Master},[y.Chapters]:{type:R.Master},[y.Cluster]:{type:R.Master},[y.Timestamp]:{type:R.UnsignedInteger},[y.SilentTracks]:{type:R.Master},[y.SilentTrackNumber]:{type:R.UnsignedInteger},[y.Position]:{type:R.UnsignedInteger},[y.PrevSize]:{type:R.UnsignedInteger},[y.SimpleBlock]:{type:R.Binary},[y.BlockGroup]:{type:R.Master},[y.EncryptedBlock]:{type:R.Binary},[y.Attachments]:{type:R.Master},[y.Tags]:{type:R.Master},[y.Cues]:{type:R.Master},[y.CuePoint]:{type:R.Master},[y.CueTime]:{type:R.UnsignedInteger},[y.CueTrackPositions]:{type:R.Master},[y.CueTrack]:{type:R.UnsignedInteger},[y.CueClusterPosition]:{type:R.UnsignedInteger},[y.CueRelativePosition]:{type:R.UnsignedInteger},[y.CueDuration]:{type:R.UnsignedInteger},[y.CueBlockNumber]:{type:R.UnsignedInteger},[y.CueCodecState]:{type:R.UnsignedInteger},[y.CueReference]:{type:R.Master},[y.CueRefTime]:{type:R.UnsignedInteger}},Zs=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 s=Zt(a,t),i=s in vs,r=i?vs[s].type:R.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=Zt(c),u=d*2**((o-1)*8)+h,f=t+o;let S;return f+u>a.byteLength?S=new DataView(a.buffer,a.byteOffset+f):S=new DataView(a.buffer,a.byteOffset+f,u),{tag:i?s:"0x"+s.toString(16).toUpperCase(),type:r,tagHeaderSize:f,tagSize:f+u,value:S,valueSize:u}},Zt=(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},Me=(a,e)=>{switch(e){case R.SignedInteger:return a.getInt8(0);case R.UnsignedInteger:return Zt(a);case R.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case R.String:return new TextDecoder("ascii").decode(a);case R.UTF8:return new TextDecoder("utf-8").decode(a);case R.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case R.Master:return a;case R.Binary:return a;default:C(e)}},Et=(a,e)=>{let t=0;for(;t<a.byteLength;){const s=new DataView(a.buffer,a.byteOffset+t),i=Zs(s);if(!e(i))return;i.type===R.Master&&Et(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Va=a=>{if(a.getUint32(0)!==y.EBML)return!1;let e,t,s;const i=Zs(a);return Et(i.value,({tag:r,type:n,value:o})=>(r===y.EBMLReadVersion?e=Me(o,n):r===y.DocType?t=Me(o,n):r===y.DocTypeReadVersion&&(s=Me(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},ei=[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],Fa=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],Ha=a=>{let e,t,s,i,r=!1,n=!1,o=!1,c,d,h=!1;const u=0;return Et(a,({tag:f,type:S,value:p,valueSize:m})=>{if(f===y.SeekID){const T=Me(p,S);d=Zt(T)}else f!==y.SeekPosition&&(d=void 0);return f===y.Segment?(e=p.byteOffset,t=p.byteOffset+m):f===y.Info?r=!0:f===y.SeekHead?n=!0:f===y.TimestampScale?s=Me(p,S):f===y.Duration?i=Me(p,S):f===y.SeekPosition&&d===y.Cues?c=Me(p,S):f===y.Tracks?Et(p,({tag:T,type:P,value:L})=>T===y.ProjectionType?(h=Me(L,P)===1,!1):!0):r&&n&&ei.includes(f)&&(o=!0),!o}),k(e,"Failed to parse webm Segment start"),k(t,"Failed to parse webm Segment end"),k(i,"Failed to parse webm Segment duration"),s=s??1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(i/1e9*s*1e3),cuesSeekPosition:c,is3dVideo:h,stereoMode:u,projectionType:Kt.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ya=a=>{if(W(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},qa=(a,e)=>{let t=!1,s=!1;const i=o=>A(o.time)&&A(o.position),r=[];let n;return Et(a,({tag:o,type:c,value:d})=>{switch(o){case y.Cues:t=!0;break;case y.CuePoint:n&&i(n)&&r.push(n),n={};break;case y.CueTime:n&&(n.time=Me(d,c));break;case y.CueTrackPositions:break;case y.CueClusterPosition:n&&(n.position=Me(d,c));break;default:t&&ei.includes(o)&&(s=!0)}return!(t&&s)}),n&&i(n)&&r.push(n),r.map((o,c)=>{const{time:d,position:h}=o,u=r[c+1];return{status:Q.NONE,time:{from:d,to:u?u.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:u?e.segmentStart+u.position-1:e.segmentEnd-1}}})},Ga=a=>{let e=0,t=!1;try{Et(a,s=>s.tag===y.Cluster?s.tagSize<=a.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Fa.includes(s.tag)?(e+s.tagSize<=a.byteLength&&(e+=s.tagSize,t||=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(s.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},za={validateData:Va,parseInit:Ha,getIndexRange:Ya,parseSegments:qa,parseFeedableSegmentChunk:Ga};class As{onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);playingRepresentationInit$=new g(void 0);error$=new _;gaps=[];subscription=new X;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new ot;destroyAbortController=new ot;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;constructor(e,t,s,i,{fetcher:r,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1}){switch(this.fetcher=r,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case Tt.MP4:this.containerParser=Ua;break;case Tt.WEBM:this.containerParser=za;break;default:C(s)}this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=xe(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);k(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ga(this.sourceBuffer),this.subscription.add(B(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:D.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(B(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:D.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const c=Math.min(this.bufferLimit,Es(this.sourceBuffer.buffered)*.8);this.bufferLimit=c,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const s=this.initData.get(t.id),i=this.segments.get(t.id),r=this.parsedInitData.get(t.id);if(k(s,"No init buffer for starting representation"),k(i,"No segments for starting representation"),!(s instanceof ArrayBuffer))return;let n=0;for(const o of i)o.time.from-n>0&&this.gaps.push({representation:t.id,from:n,to:o.time.from}),n=o.time.to;A(t.duration)&&t.duration-n>0&&this.gaps.push({representation:t.id,from:n,to:t.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(r)}.bind(this));switchTo=xe(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);k(t,`No such representation ${e}`);let s=this.initData.get(e);if(W(s)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),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 i=this.getCurrentPosition();A(i)&&this.maintain(i)}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ot,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(W(e)||W(this.downloadingRepresentationId)||W(this.playingRepresentationId)||W(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(k(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const i=s.find(d=>e>=d.time.from&&e<d.time.to);let r=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=nt(this.sourceBuffer.buffered,e),u=i?i.time.to+100:-1/0;i&&h>=i.time.to-e+100&&(r=u)}if(isFinite(this.bufferLimit)&&Es(this.sourceBuffer.buffered)>=this.bufferLimit){const d=nt(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(s,t.segmentReference.type,r),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{const h=o.at(0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status===Q.FED&&!o.length&&nt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=s.at(-1);c&&c.status===Q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(i===c))}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const s=this.segments.get(t);return s?s.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(){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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const i=e.findIndex(({status:u,time:{from:f,to:S}},p)=>{const m=f<=s&&S>=s,T=f>s||m||p===0&&s===0,P=Math.min(this.forwardBufferTarget,this.bufferLimit),L=this.preloadOnly&&f<=s+P||S<=s+P;return(u===Q.NONE||u===Q.PARTIALLY_EJECTED&&T&&L&&this.sourceBuffer&&!ds(this.sourceBuffer.buffered,s))&&T&&L});if(i===-1)return[];if(t!==Pe.BYTE_RANGE)return e.slice(i,i+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=i;u<r.length&&(n<=d||o<=h);u++){const f=r[u];if(n+=f.byte.to+1-f.byte.from,o+=f.time.to+1-f.time.from,f.status===Q.NONE||f.status===Q.PARTIALLY_EJECTED)c.push(f);else break}return c}async loadSegments(e,t,s="auto"){if(!e.length)return;let i,r,n=e;const{type:o}=t.segmentReference;switch(o){case Pe.BYTE_RANGE:{i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Pe.TEMPLATE:{const d=e.at(0);i=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:C(o)}for(const d of n)d.status=Q.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(await xe(c,async function*(){const d=ms(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(i,{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:D.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:c,priority:s}).then(()=>this.failedDownloads=0,d=>{for(const h of this.activeSegments)e.includes(h.segment)&&this.abortSegment(h.segment);this.onSegmentDownloadError(d)})}onSegmentDownloadError(e){let t=!1;const s=this.getCurrentPosition();this.sourceBuffer&&A(s)&&(t=nt(this.sourceBuffer?.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:D.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,i,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=Q.FED,"size"in u.segment&&(u.segment.size=u.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const S of this.segments.get(f.id)??[])S.status===Q.FED&&S.time.from===u.segment.time.from&&S.time.to===u.segment.time.to&&(S.status=Q.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:f}=u,S=d===Pe.BYTE_RANGE,p=S?f.byte.to-f.byte.from+1:h;if(u.representationId!==t||!(!S||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(r.aborted){n();continue}const T=S?f.byte.from-s:0,P=S?f.byte.to-s:e.byteLength,L=T<i,se=P<=i;if(f.status===Q.DOWNLOADING&&L&&se){f.status=Q.DOWNLOADED,this.activeSegments.delete(u);const $=new DataView(e.buffer,e.byteOffset+T,p);this.sourceBufferTaskQueue.append($,r).then(v=>v&&!r.aborted?o(u):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&L&&(u.loadedBytes=Math.min(p,i-T),u.loadedBytes>u.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+T+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?$:this.containerParser.parseFeedableSegmentChunk($);v?.byteLength&&(f.status=Q.PARTIALLY_FED,u.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,r).then(F=>{if(r.aborted)n();else if(F)u.fedBytes+=v.byteLength,u.fedBytes===p&&o(u);else{if(u.feedingBytes<p)return;n()}}))}}}abortSegment(e){e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[i,r]of this.initData.entries()){const n=r instanceof Promise;t||=n,r===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Ts(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?xe(this.destroyAbortController.signal,async function*(){const o=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,i)).then(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,h),this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:D.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||W(e)||this.sourceBuffer.updating)return!1;let i=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;i+=h};for(const d of this.segments.values())for(const h of d){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;h.status===Q.FED&&c(h)}if(o=isFinite(r)&&isFinite(n),!o){i=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)||i>t)break;h.status===Q.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 f of this.segments.values())for(const S of f)if(S.status===Q.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&&s){i=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===Q.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)}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let i={representation:e,from:s.time.from,to:s.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<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){i=void 0;break}o>s.time.from&&o<s.time.to&&(i.from=o),n<s.time.to&&n>s.time.from&&(i.to=n)}}i&&i.to-i.from>=1&&!this.gaps.some(r=>i&&r.from===i.from&&r.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ts(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:D.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(W(this.sourceBuffer)||W(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const i=Math.round(this.sourceBuffer.buffered.start(s)*1e3),r=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:i,to:r})}const t=1;for(const s of this.segments.values())for(const i of s){const{status:r}=i;if(r!==Q.FED&&r!==Q.PARTIALLY_EJECTED)continue;const n=Math.floor(i.time.from),o=Math.ceil(i.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?i.status=Q.PARTIALLY_EJECTED:i.status=Q.NONE)}}}var mt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(mt||(mt={}));class Wa{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new ot;subscription=new X;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=js(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=xe(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=yt(t));const s=yield bt(t,{signal:this.abortAllController.signal}).catch(Dt);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=xe(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?mt.HEADER:mt.PARAM,range:s,onProgress:i,priority:r="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(s)switch(t){case mt.HEADER:{d.append("Range",`bytes=${s.from}-${s.to}`);break}case mt.PARAM:{const Y=new URL(c,location.href);Y.searchParams.append("bytes",`${s.from}-${s.to}`),c=Y.toString();break}default:C(t)}this.requestQuic&&(c=yt(c));let h=this.abortAllController.signal;if(n){const Y=new ot;if(this.subscription.add(x(B(this.abortAllController.signal,"abort"),B(n,"abort")).subscribe(()=>{try{Y.abort()}catch(J){Dt(J)}})),this.abortAllController.signal.aborted||n.aborted)try{Y.abort()}catch(J){Dt(J)}h=Y.signal}const u=ce(),f=yield bt(c,{priority:r,headers:d,signal:h}).catch(Dt),S=ce();if(this.throughputEstimator?.addRawRtt(S-u),!f)return null;if(!f.ok||!f.body)return Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));this.onHeadersReceived(f.headers);const p=parseInt(f.headers.get("Content-Length")??"",10)||s&&s.to-s.from+1||NaN;if(!p){const Y=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(Y.byteLength,ce()-S),i?.(new DataView(Y),Y.byteLength),Y}if(!i&&!o)return f.arrayBuffer();const[m,T]=f.body.tee(),P=m.getReader();o&&this.throughputEstimator?.trackStream(T);let L=0;const se=new ArrayBuffer(p),$=new Uint8Array(se),v=new DataView(se);let F=!1;const H=Y=>{F=!0,Dt(Y)},ie=xe(h,async function*({done:Y,value:J}){L===0&&this.lastRequestFirstBytes$.next(ce()-u),!h.aborted&&(Y?i?.(v,L):J&&($.set(J,L),L+=J.byteLength,i?.(v,L),yield P?.read().then(ie,H)))}.bind(this));return yield P?.read().then(ie,H),F?null:se}.bind(this));async fetchRepresentation(e,t,s="auto"){const{type:i}=e;switch(i){case Pe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case Pe.TEMPLATE:return await this.fetchTemplateRepresentation(e,s)??null;default:C(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=xe(this.abortAllController.signal,async function*(e,t,s){if(e.type!==Pe.BYTE_RANGE)return null;const{from:i,to:r}=e.initRange;let n=i,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,i),o=Math.max(h,r))),n=Math.min(n,0);const u=yield this.fetch(e.url,{range:{from:n,to:o},priority:s,measureThroughput:!1});if(!u)return null;const f=new DataView(u,i-n,r-n+1);if(!t.validateData(f))throw new Error("Invalid media file");const S=t.parseInit(f),p=e.indexRange??t.getIndexRange(S);if(!p)throw new ReferenceError("No way to load representation index");let m;if(c)m=new DataView(u,p.from-n,p.to-p.from+1);else{const P=yield this.fetch(e.url,{range:p,priority:s,measureThroughput:!1});if(!P)return null;m=new DataView(P)}const T=t.parseSegments(m,S,p);return{init:S,dataView:new DataView(u),segments:T}}.bind(this));fetchTemplateRepresentation=xe(this.abortAllController.signal,async function*(e,t){if(e.type!==Pe.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(s,{priority:t,measureThroughput:!1});if(!i)return null;const r=e.segments.map(n=>({...n,status:Q.NONE,size:void 0}));return{init:{},segments:r,dataView:new DataView(i)}}.bind(this))}const Dt=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},ks=a=>{if(!a.startsWith("P"))return;const e=(n,o)=>{const c=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(c)?0:c)*o},s=/^(-|\+)?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),i=s?.[1]==="-"?-1:1,r={days:e(s?.[5],i),hours:e(s?.[6],i),minutes:e(s?.[7],i),seconds:e(s?.[8],i)};return r.days*24*60*60*1e3+r.hours*60*60*1e3+r.minutes*60*1e3+r.seconds*1e3},as=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[i,r]of Object.entries(s)){const n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>W(r)?o:W(c)?r:r.padStart(parseInt(c,10),"0"))}return t},Qa=(a,e)=>{const s=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},r=s.children[0],n=r.getElementsByTagName("Period")[0],o=n.children;let c;const d=r.getAttribute("mediaPresentationDuration"),h=n.getAttribute("duration");if(d)c=ks(d);else if(h){const p=ks(h);A(p)&&(c=p)}let u=0;const f=r.getAttribute("profiles")?.split(",")??[],S=f.includes(Xt.WEBM_AS_IN_FFMPEG)||f.includes(Xt.WEBM_AS_IN_SPEC)?Tt.WEBM:Tt.MP4;for(const p of o){const m=p.getAttribute("mimeType"),T=p.getAttribute("codecs"),P=p.getAttribute("contentType")??m?.split("/")[0],L=p.getAttribute("profiles")?.split(",")??[],se=p.querySelectorAll("Representation"),$=p.querySelector("SegmentTemplate");if(P!=="text")for(const v of se){const F=v.getAttribute("mimeType")??m,H=v.getAttribute("codecs")??T??"",ie=v.getAttribute("contentType")??F?.split("/")[0]??P,Y=p.getAttribute("profiles")?.split(",")??[],J=parseInt(v.getAttribute("width")??"",10),ne=parseInt(v.getAttribute("height")??"",10),j=parseInt(v.getAttribute("bandwidth")??"",10)/1e3,le=v.getAttribute("frameRate")??"",Le=v.getAttribute("quality")??void 0,je=le?us(le):void 0,I=v.getAttribute("id")??(u++).toString(10),K=ie==="video"?`${ne}p`:ie==="audio"?`${j}Kbps`:H,ue=`${I}@${K}`,me=v.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(me,e).toString(),Je=[...f,...L,...Y];let At;const Vt=v.querySelector("SegmentBase"),q=v.querySelector("SegmentTemplate")??$;if(Vt){const Se=v.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[be,Ve]=Se.split("-").map(it=>parseInt(it,10)),Fe={from:be,to:Ve},Ie=v.querySelector("SegmentBase")?.getAttribute("indexRange"),[Xe,Ke]=Ie?Ie.split("-").map(it=>parseInt(it,10)):[],Ze=Ie?{from:Xe,to:Ke}:void 0;At={type:Pe.BYTE_RANGE,url:Ee,initRange:Fe,indexRange:Ze}}else if(q){const Se={representationId:v.getAttribute("id")??void 0,bandwidth:v.getAttribute("bandwidth")??void 0},be=parseInt(q.getAttribute("timescale")??"",10),Ve=q.getAttribute("initialization")??"",Fe=q.getAttribute("media"),Ie=parseInt(q.getAttribute("startNumber")??"",10)??1,Xe=as(Ve,Se);if(!Fe)throw new ReferenceError("No media attribute in SegmentTemplate");const Ke=q.querySelectorAll("SegmentTimeline S")??[],Ze=[];if(Ke.length){let it=Ie,at=0;for(const kt of Ke){const lt=parseInt(kt.getAttribute("d")??"",10)*1e3,wt=parseInt(kt.getAttribute("r")??"",10)||0,$t=parseInt(kt.getAttribute("t")??"",10)??void 0;for(let fs=0;fs<wt+1;fs++){const ni=as(Fe,{...Se,segmentNumber:it.toString(10),segmentTime:$t.toString(10)}),oi=$t?$t/be:at;at+=lt/be;const di=at;it++,Ze.push({time:{from:oi,to:di},url:ni})}}}else if(A(c)){const at=parseInt(q.getAttribute("duration")??"",10)/be*1e3,kt=Math.ceil(c/at);let lt=0;for(let wt=1;wt<kt;wt++){const $t=as(Fe,{...Se,segmentNumber:wt.toString(10),segmentTime:lt.toString(10)});Ze.push({time:{from:lt,to:lt+at},url:$t}),lt+=at}}At={type:Pe.TEMPLATE,baseUrl:Ee,initUrl:Xe,segments:Ze}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!F)continue;const ge={video:Re.VIDEO,audio:Re.AUDIO,text:Re.TEXT}[ie];ge&&i[ge].push({id:ue,kind:ge,segmentReference:At,profiles:Je,duration:c,bitrate:j,mime:F,codecs:H,width:J,height:ne,fps:je,quality:Le})}}return{duration:c,container:S,representations:i}},ja=["timeupdate","progress","play","seeked","stalled","waiting"];var $e;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})($e||($e={}));let Ja=class{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new X;fetcher;state$=new re($e.NONE);currentVideoRepresentation$=new g(void 0);currentVideoRepresentationInit$=new g(void 0);error$=new _;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);forceEnded$=new _;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new ot;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Wa({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=xe(this.destroyController.signal,async function*(e,t){this.element=e,this.state$.startTransitionTo($e.MANIFEST_READY);const s=yield this.fetcher.fetchManifest(t).catch(n=>this.error$.next({id:"LoadManifest",category:D.NETWORK,message:"Failed to load manifest",thrown:n}));if(!s)return;let i;try{i=Qa(s??"",t)}catch(n){this.error$.next({id:"ManifestParsing",category:D.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!i)return;const r=({mime:n,codecs:o})=>Boolean(e.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`));this.manifest={...i,representations:Object.fromEntries(Object.entries(i.representations).map(([n,o])=>[n,o.filter(r)]))},this.manifest.representations.video.length?this.state$.setState($e.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:D.PARSER,message:"No playable video representations"})}.bind(this));initRepresentations=xe(this.destroyController.signal,async function*(e,t){k(this.manifest),k(this.element),this.state$.startTransitionTo($e.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new As(Re.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],A(t)&&(this.audioBufferManager=new As(Re.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const i=x(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(E(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),r=x(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(E(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.subscription.add(x(this.forceEnded$,Ge({allBuffersFull:i,someBufferEnded:r}).pipe(O(({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:D.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.subscription.add(x(...this.bufferManagers.map(n=>n.error$)).subscribe(this.error$)),this.subscription.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($e.REPRESENTATIOS_READY)}.bind(this));initBuffer(){k(this.element),this.state$.setState($e.RUNNING),this.subscription.add(x(...ja.map(e=>B(this.element,e)),B(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:D.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(B(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(B(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ds(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){return{[Re.VIDEO]:this.videoBufferManager,[Re.AUDIO]:this.audioBufferManager,[Re.TEXT]:null}[e]?.switchTo(t)}seek(e,t){k(this.element),k(this.videoBufferManager);let s;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?s=e:s=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ds(this.element.buffered,s)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(s),this.audioBufferManager?.maintain(s),this.element.currentTime=s/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($e.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.destroyController.abort(),this.fetcher.destroy(),this.stop(),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=hi(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),t=>{this.error$.next({id:"GapWatchdog",category:D.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const s of this.bufferManagers)for(const i of s.gaps)s.playingRepresentation$.getValue()===i.representation&&i.from<=e&&i.to>e&&(this.element.duration*1e3-i.to<this.tuning.endGapTolerance?t.push(1/0):t.push(i.to));if(t.length){const s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};const Xa=135,Ka=76;class Za{fov;rotation;constructor(){this.fov={x:Xa,y:Ka},this.rotation={x:0,y:0,z:0}}}const ft=10,ws=175;class er{options;camera;rotating=!1;torqueLossTS=0;hold=!1;lastTick;rotationSpeed;rotationMoment;constructor(e,t={}){this.options=t,this.camera=e,this.torqueLossTS=performance.now(),this.rotationSpeed={x:0,y:0,z:0},this.rotationMoment={x:0,y:0,z:0}}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.rotation.x+e,this.camera.rotation.y+t,this.camera.rotation.z+s)}pointCameraTo(e=0,t=0,s=0){this.camera.rotation.x=e,this.camera.rotation.y=this.limitCameraRotationY(t),this.camera.rotation.z=s}setRotationSpeed(e,t,s){e===void 0&&(e=this.rotationSpeed.x),t===void 0&&(t=this.rotationSpeed.y),s===void 0&&(s=this.rotationSpeed.z),this.rotationSpeed.x=e,this.rotationSpeed.y=t,this.rotationSpeed.z=s,this.torqueLossTS=performance.now()}startRotation(){this.rotating=!0}stopRotation(e=!1){e&&this.setRotationSpeed(0,0,0),this.rotating=!1,this.torqueLossTS=performance.now()}limitCameraRotationY(e){return Math.max(-ws,Math.min(e,ws))}temporalFn(e){const t=100-5e-4*(e-this.torqueLossTS);return Math.sign(t)*Math.sqrt(Math.abs(t))/10}tick(e){if(!this.lastTick){this.lastTick=e;return}const s=(e-this.lastTick)/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*s*ft,this.rotationSpeed.y*s*ft,this.rotationSpeed.z*s*ft);else{let i=0,r=0,n=0;const o=this.temporalFn(e);this.rotationSpeed.x&&(this.rotationSpeed.x=Math.sign(this.rotationSpeed.x)*Math.max(Math.abs(this.rotationSpeed.x)-o,0),i=this.rotationSpeed.x*s*ft),this.rotationSpeed.y&&(this.rotationSpeed.y=Math.sign(this.rotationSpeed.y)*Math.max(Math.abs(this.rotationSpeed.y)-o,0),r=this.rotationSpeed.y*s*ft),this.rotationSpeed.z&&(this.rotationSpeed.z=Math.sign(this.rotationSpeed.z)*Math.max(Math.abs(this.rotationSpeed.z)-o,0),n=this.rotationSpeed.z*s*ft),this.turnCamera(i,r,n)}this.rotationSpeed.x===0&&this.rotationSpeed.y===0&&this.rotationSpeed.z===0&&this.stopRotation(),this.lastTick=e}}const tr=`
8
+ attribute vec2 a_vertex;
9
+ attribute vec2 a_texel;
10
+
11
+ varying vec2 v_texel;
12
+
13
+ void main(void) {
14
+ // direct vertex drawing
15
+ gl_Position = vec4(a_vertex, 0.0, 1.0);
16
+ // save texel vector to pass to fragment shader
17
+ v_texel = a_texel;
18
+ }
19
+ `,sr=`
20
+ #ifdef GL_ES
21
+ precision highp float;
22
+ precision highp int;
23
+ #else
24
+ precision mediumhp float;
25
+ #endif
26
+
27
+ varying vec2 v_texel; // [0..1, 0..1]
28
+
29
+ uniform sampler2D u_texture;
30
+ uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
31
+
32
+ const float PI = 3.14159265358979323846264;
33
+ const float PI_2 = PI * 0.5;
34
+ const float PI2 = PI * 2.0;
35
+
36
+ void main(void) {
37
+ // center point of output projection
38
+ float lambda0 = u_focus.x / 360.0; // [-0.5, 0.5]
39
+ float phi0 = u_focus.y / 180.0; // [-0.5, 0.5]
40
+
41
+ float x = PI2 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
42
+ float y = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
43
+
44
+ float p = sqrt(x * x + y * y); // rou
45
+ float c = atan(p);
46
+ float cos_c = cos(c);
47
+ float sin_c = sin(c);
48
+
49
+ // geo coordinates of projection
50
+ float lambda = lambda0 + atan(
51
+ x * sin_c,
52
+ p * cos(phi0) * cos_c - y * sin(phi0) * sin_c
53
+ );
54
+ float phi = asin(cos_c * sin(phi0) + (y * sin_c * cos(phi0)) / p);
55
+
56
+ // reprojected texture coordinates
57
+ vec2 tc = vec2(
58
+ mod(lambda / PI2 - 0.5, 1.0), // [0..1]
59
+ mod(phi / PI - 0.5, 1.0) // [0..1]
60
+ );
61
+
62
+ // sample using new coordinates
63
+ gl_FragColor = texture2D(u_texture, tc);
64
+ }
65
+ `;class ir{container;sourceVideoElement;canvas;gl;options;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;lastCameraRotationX=0;lastCameraRotationY=0;lastCameraRotationT=0;lastCameraRotationDX=0;lastCameraRotationDY=0;mouseDown=!1;onMouseDownHandlerFn;onMouseMoveHandlerFn;onMouseUpHandlerFn;mouseLeaveHandlerFn;renderFn;active=!1;constructor(e,t,s={}){this.container=e,this.sourceVideoElement=t,this.options=s,this.canvas=document.createElement("canvas");const i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.canvas.classList.add("player-scene3d"),this.container.appendChild(this.canvas),this.camera=new Za,this.cameraRotationManager=new er(this.camera),this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.onMouseDownHandlerFn=this.mouseDownHandler.bind(this),this.onMouseMoveHandlerFn=this.mouseMoveHandler.bind(this),this.onMouseUpHandlerFn=this.mouseUpHandler.bind(this),this.mouseLeaveHandlerFn=this.mouseLeaveHandler.bind(this),this.initControls(),this.renderFn=this.render.bind(this)}play(){this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",()=>{this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.videoInitialized=!0,this.doPlay()})}stop(){this.active=!1}startCameraRotation(e,t,s){this.cameraRotationManager.setRotationSpeed(e,t,s),this.cameraRotationManager.startRotation()}stopCameraRotation(e=!1){this.cameraRotationManager.stopRotation(e)}destroy(e){this.stop(),this.container.removeEventListener("mousedown",this.onMouseDownHandlerFn),this.container.removeEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.removeEventListener("mouseup",this.onMouseUpHandlerFn),this.canvas.remove(),e?.()}doPlay(){this.active=!0,requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateViewportSize(),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),r=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),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(s,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(i,0),this.gl.uniform2f(r,-this.camera.rotation.x,-this.camera.rotation.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(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(tr,this.gl.VERTEX_SHADER),s=this.createShader(sr,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),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,s=1;const i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:s=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),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.rotation.x/360,t=.5-this.camera.rotation.y/180,s=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,r=e-s,n=t-i,o=e+s,c=t-i,d=e+s,h=t+i,u=e-s,f=t+i;return[r,n,o,c,d,h,u,f]}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)}updateViewportSize(){this.frameWidth=this.sourceVideoElement.videoWidth||this.sourceVideoElement.width,this.frameHeight=this.sourceVideoElement.videoHeight||this.sourceVideoElement.height,this.viewportWidth=this.sourceVideoElement.offsetWidth,this.viewportHeight=this.sourceVideoElement.offsetHeight,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}initControls(){this.container.addEventListener("mousedown",this.onMouseDownHandlerFn),this.container.addEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.addEventListener("mouseup",this.onMouseUpHandlerFn),this.container.addEventListener("mouseleave",this.mouseLeaveHandlerFn)}mouseDownHandler(e){e.target===this.canvas&&(this.cameraRotationManager.stopRotation(!0),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationT=e.timeStamp,this.mouseDown=!0)}mouseMoveHandler(e){if(this.mouseDown){const t=e.offsetX-this.lastCameraRotationX,s=this.lastCameraRotationY-e.offsetY;this.cameraRotationManager.pointCameraTo(this.camera.rotation.x+t,this.camera.rotation.y+s),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationDX=t,this.lastCameraRotationDY=s,this.lastCameraRotationT=e.timeStamp}}mouseUpHandler(e){this.mouseDown=!1;const t=e.timeStamp-this.lastCameraRotationT;this.cameraRotationManager.setRotationSpeed(this.lastCameraRotationDX*40/t,this.lastCameraRotationDY*40/t)}mouseLeaveHandler(){this.mouseDown=!1,this.lastCameraRotationX=this.lastCameraRotationY=0}}var oe;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(oe||(oe={}));const ar=({id:a,width:e,height:t,bitrate:s,fps:i,quality:r})=>{const n=(r?Ot(r):void 0)??ht({width:e,height:t});return n&&{id:a,quality:n,bitrate:s,size:{width:e,height:t},fps:i}},rr=({id:a,bitrate:e})=>({id:a,bitrate:e}),nr=(a,e,t)=>{const s=e.indexOf(t);return a.at(Math.round(a.length*s/e.length))??a.at(-1)};class or{subscription=new X;videoState=new re(oe.STOPPED);video;scene3D;player;params;elementSize$=new g(void 0);textTracksManager=new Oe;videoTracks=[];audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Gi;constructor(e){this.params=e,this.video=We(this.params.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(ve(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ja({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=Qe(this.video),i=d=>{e.error$.next({id:"DashVKProvider",category:D.WTF,message:"DashVKProvider internal logic error",thrown:d})},r=(d,h)=>this.subscription.add(d.subscribe(h,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.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.isAudioAvailable$,e.isAudioAvailable$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(O(A),pe(),ct(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ut(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(tt(this.video,t.playbackRate,s.playbackRateState$,i)),r(jt(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),w(t.playbackState,l.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),w(t.playbackState,l.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d===$e.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();k(h,"Manifest not loaded or empty");const u=Array.from(h.audio).sort((p,m)=>m.bitrate-p.bitrate),f=Array.from(h.video).sort((p,m)=>m.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of u){const m=rr(p);m&&this.audioTracks.push({track:m,representation:p})}for(const p of f){const m=ar(p);if(m){this.videoTracks.push({track:m,representation:p});const T=!this.params.tuning.isAudioDisabled&&nr(u,f,p);T&&this.audioRepresentations.set(p.id,T)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const S=this.selectVideoRepresentation();k(S),this.player.initRepresentations(S.id,this.audioRepresentations.get(S.id)?.id)}else d===$e.REPRESENTATIOS_READY&&(this.videoState.setState(oe.READY),this.player.initBuffer())},i));const n=d=>e.error$.next({id:"RepresentationSwitch",category:D.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(x(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,B(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),h=this.player.state$.getTransition();if(d!==$e.RUNNING||h||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const u=this.selectVideoRepresentation();if(u){this.player.switchRepresentation(Re.VIDEO,u.id).catch(n);const f=this.audioRepresentations.get(u.id);f&&this.player.switchRepresentation(Re.AUDIO,f.id).catch(n)}},i)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(he(),E(d=>d&&this.videoTracks.find(({representation:{id:h}})=>h===d)?.track)).subscribe(e.currentVideoTrack$,i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d)if(d.is3dVideo)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch{}else this.destroy3DScene(),e.is3DVideo$.next(!1)},i)),this.params.desiredState.cameraRotation.stateChangeEnded$.subscribe(()=>{if(this.scene3D){const d=this.params.desiredState.cameraRotation.getState();d?this.scene3D.startCameraRotation(d.x,d.y,d.z):this.scene3D.stopCameraRotation(!1)}}),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(E(({to:d})=>d===l.READY),he());this.subscription.add(x(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(x(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===l.READY)));const c=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0));this.subscription.add(c.subscribe(this.syncPlayback,i))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState(),s=this.videoTracks.find(({track:{id:u}})=>u===t)?.track,i=this.params.output.currentVideoTrack$.getValue(),r=nt(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(s&&!e?this.audioRepresentations.get(s.id)?.bitrate??0:0,i?this.audioRepresentations.get(i.id)?.bitrate??0:0),d=Nt(this.videoTracks.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:i,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),h=e?d??s:s??d;return h&&this.videoTracks.find(({track:u})=>u===h)?.representation}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state===M.Requested&&s?.to!==l.PAUSED&&e!==oe.STOPPED&&t!==l.STOPPED&&this.seek(i.position,i.forcePrecise),t===l.STOPPED){e!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.player.stop(),this.video.setAttribute("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),w(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),w(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):s?.to===l.READY&&w(this.params.desiredState.playbackState,l.READY);return;case oe.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case oe.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;default:return C(e)}}};init3DScene=e=>{this.scene3D||(this.scene3D=new ir(this.params.container,this.video,e),this.scene3D.play())};destroy3DScene=()=>{this.scene3D&&this.scene3D.destroy(()=>{this.scene3D=null})};destroy(){this.subscription.unsubscribe(),this.destroy3DScene(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}}const dr=5e3,He={};var z;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const qt=(a,e)=>new Mt(t=>{const s=(i,r)=>t.next(r);return a.on(e,s),()=>a.off(e,s)});class cr{subscription=new X;videoState=new re(z.INITIALIZING);video;params;hls;textTracksManager=new Oe;trackLevels=new Map;constructor(e){this.video=We(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(ve(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:D.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),dr);import("hls.js/dist/hls.min.js").then(i=>{e||(He.Hls=i.default,He.Events=i.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){k(He.Hls,"hls.js not loaded"),this.hls=new He.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){k(He.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:D.WTF,message:"HlsJsProvider internal logic error",thrown:d})},i=Qe(this.video),r=(d,h)=>this.subscription.add(d.subscribe(h,s));r(i.timeUpdate$,t.position$),r(i.durationChange$,t.duration$),r(i.ended$,t.endedEvent$),r(i.looped$,t.loopedEvent$),r(i.error$,t.error$),r(i.isBuffering$,t.isBuffering$),r(i.currentBuffer$,t.currentBuffer$),r(i.loadStart$,t.firstBytesEvent$),r(i.playing$,t.firstFrameEvent$),r(i.canplay$,t.canplay$),r(i.seeked$,t.seekedEvent$),r(i.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(ut(this.video,e.isLooped,s)),this.subscription.add(ze(this.video,e.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(tt(this.video,e.playbackRate,i.playbackRateState$,s)),this.subscription.add(qt(this.hls,He.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:D.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),w(e.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),w(e.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},s)),r(qt(this.hls,He.Events.MANIFEST_PARSED).pipe(E(({levels:d})=>d.reduce((h,u)=>{const f=u.name||u.height.toString(10),{width:S,height:p}=u,m=Ot(u.attrs.QUALITY??"")??ht({width:S,height:p});if(!m)return h;const T=u.attrs["FRAME-RATE"]?parseFloat(u.attrs["FRAME-RATE"]):void 0,P={id:f.toString(),quality:m,bitrate:u.bitrate/1e3,size:{width:S,height:p},fps:T};return this.trackLevels.set(f,{track:P,level:u}),h.push(P),h},[]))),t.availableVideoTracks$),r(qt(this.hls,He.Events.LEVEL_LOADING).pipe(E(({url:d})=>ve(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:s}));const n=d=>Array.from(this.trackLevels.values()).find(({level:h})=>h===d)?.track,o=qt(this.hls,He.Events.LEVEL_SWITCHED).pipe(E(({level:d})=>n(this.hls.levels[d])));o.pipe(O(A)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Ne(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel])?.id,d=>{if(W(d))return;const h=this.trackLevels.get(d)?.level;if(!h)return;const u=this.hls.levels.indexOf(h),f=this.hls.currentLevel,S=this.hls.levels[f];!S||h.bitrate>S.bitrate?this.hls.nextLevel=u:(this.hls.loadLevel=u,this.hls.loadLevel=u)},{changed$:o.pipe(E(d=>d?.id)),onError:s})),r(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=x(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!==z.INITIALIZING)switch(s?.to!==l.PAUSED&&i.state===M.Requested&&this.seek(i.position),t){case l.STOPPED:switch(e){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:C(e)}break;case l.READY:switch(e){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:C(e)}break;case l.PLAYING:switch(e){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:C(e)}break;case l.PAUSED:switch(e){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED);break;case z.PLAYING:this.pause();break;default:C(e)}break;default:C(t)}};prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(z.PLAYING),await st(this.video)||(this.videoState.setState(z.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))}pause(){this.videoState.startTransitionTo(z.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.setAttribute("src",""),this.video.load(),this.videoState.setState(z.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0)}}const $s="X-Playback-Duration";var Rs=async a=>{const e=await bt(a,{method:"HEAD"});return e.headers.has($s)?parseInt(e.headers.get($s),10):void 0};const hr=a=>{let e=null;if(a.QUALITY&&(e=Ot(a.QUALITY)),!e&&a.RESOLUTION){const[t,s]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=ht({width:t,height:s})}return e??null},ti=async(a,e=a)=>{const i=(await(await bt(a)).text()).split(`
66
+ `),r=[];for(let n=0;n<i.length;n++){const c=i[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=hr(d);let f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const S=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0;let p;if(d.RESOLUTION){const[T,P]=d.RESOLUTION.split("x").map(L=>parseInt(L,10));T&&P&&(p={width:T,height:P})}const m=new URL(i[++n],e).toString();u&&r.push({id:h,quality:u,url:m,bandwidth:f,size:p,fps:S})}return r};var Z;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(Z||(Z={}));class ur{subscription=new X;videoState=new re(Z.STOPPED);video;params;textTracksManager=new Oe;manifests$=new g([]);maxSeekBackTime$;liveOffset=new hs;manifestStartTime$=new g(void 0);constructor(e){this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:te.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),ti(gt(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ve(this.params.source.url)),this.maxSeekBackTime$=new g(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),r=i?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n)return;const o=s?"master":r;return s&&!i&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:D.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Qe(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c,s));r(i.ended$,e.endedEvent$),r(i.error$,e.error$),r(i.isBuffering$,e.isBuffering$),r(i.currentBuffer$,e.currentBuffer$),r(i.loadedMetadata$,e.firstBytesEvent$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),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(tt(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),w(t.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),w(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(he(),E(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(i.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 f=this.manifests$.getValue().find(S=>S.id===u);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ve(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===Z.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===M.Requested&&this.seek(o.position)},s)),this.subscription.add(i.loadedData$.subscribe(()=>{const o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},s)),this.subscription.add(Ge({startTime:this.manifestStartTime$.pipe(O(A)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),s)),this.subscription.add(this.manifests$.pipe(E(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:f})=>({id:c,quality:d,size:h,fps:f,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,s));const n=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,ke(["init"])).pipe(_e(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(W(e))return;const t=gt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Rs(t).then(s=>{if(!W(s))this.maxSeekBackTime$.next(s);else{const i=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(W(i)||!isFinite(i))try{bt(t).then(r=>r.text()).then(r=>{const n=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(r)?.[1];if(n){const o=new URL(n,t).toString();Rs(o).then(c=>{W(c)||this.maxSeekBackTime$.next(c)})}})}catch{}}})}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===l.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.setAttribute("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),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(i||r){const c=this.videoState.getState();this.videoState.setState(Z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),o.state===M.None&&this.params.desiredState.seekState.setState({state:M.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==l.PAUSED&&o.state===M.Requested){this.videoState.startTransitionTo(Z.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(e){case Z.READY:t===l.READY?w(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case Z.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(Z.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&&(w(this.params.desiredState.playbackState,l.PAUSED),this.liveOffset.pause());return;case Z.CHANGING_MANIFEST:break;default:return C(e)}}}var ae;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(ae||(ae={}));class lr{subscription=new X;videoState=new re(ae.STOPPED);video;params;textTracksManager=new Oe;manifests$=new g([]);constructor(e){this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:te.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),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(ve(this.params.source.url)),ti(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,s=e.getState(),i=t.getTransition(),r=i?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n)return;const o=s?"master":r;return s&&!i&&t.startTransitionTo("master"),n.find(c=>c.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:D.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Qe(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c));r(i.timeUpdate$,e.position$),r(i.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.seeked$,e.seekedEvent$),r(i.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(ut(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(tt(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),w(t.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),w(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ae.READY&&this.videoState.setState(ae.READY),this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},s).add(i.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 f=this.manifests$.getValue().find(S=>S.id===u);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ve(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),c&&c.from===ae.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===M.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe(E(o=>o.map(({id:c,quality:d,size:h,bandwidth:u,fps:f})=>({id:c,quality:d,size:h,fps:f,bitrate:u})))).subscribe(this.params.output.availableVideoTracks$,s));const n=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();W(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===l.STOPPED){e!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.STOPPED),this.video.setAttribute("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(ae.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===ae.STOPPED){this.videoState.startTransitionTo(ae.READY),this.prepare();return}if(i||r){const c=this.videoState.getState();this.videoState.setState(ae.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:d}=this.video;this.prepare(),o.state===M.None&&this.params.desiredState.seekState.setState({state:M.Requested,position:d*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&o.state===M.Requested&&this.seek(o.position),e){case ae.READY:t===l.READY?w(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(ae.PAUSED),w(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()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case ae.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;case ae.CHANGING_MANIFEST:break;default:return C(e)}}}var de;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(de||(de={}));class fr{subscription=new X;videoState=new re(de.STOPPED);video;trackUrls={};params;textTracksManager=new Oe;constructor(e){this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],i)=>{const r=i.toString(10);this.trackUrls[r]={track:{quality:t,id:r},url:s}}),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.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:D.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Qe(this.video),r=(o,c)=>this.subscription.add(o.subscribe(c,s));r(i.timeUpdate$,e.position$),r(i.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),r(i.playing$,e.firstFrameEvent$),r(i.canplay$,e.canplay$),r(i.seeked$,e.seekedEvent$),r(i.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(ut(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(tt(this.video,t.playbackRate,i.playbackRateState$,s)),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),w(t.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),w(t.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===de.READY&&this.videoState.setState(de.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()===de.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();k(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];k(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(ve(t))}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.setAttribute("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),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.seekState.getState();if(e===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(r){const{currentTime:o}=this.video;this.prepare(),n.state===M.None&&this.params.desiredState.seekState.setState({state:M.Requested,position:o*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&n.state===M.Requested&&this.seek(n.position),e){case de.READY:t===l.READY?w(this.params.desiredState.playbackState,l.READY):t===l.PAUSED?(this.videoState.setState(de.PAUSED),w(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()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case de.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;default:return C(e)}}}const Ps=["stun:videostun.mycdn.me:80"],pr=1e3,mr=3,rs=()=>null;class Sr{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=rs;externalStopCallback=rs;externalErrorCallback=rs;constructor(e,t){this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Ps}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:D.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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))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),pr)}normalizeOptions(e={}){const t={stunServerList:Ps,maxRetryNumber:mr,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ee;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(ee||(ee={}));class gr{subscription;params;log;video;videoState=new re(ee.STOPPED);liveStreamClient;maxSeekBackTime$=new g(0);constructor(e){this.subscription=new X,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=We(e.container),this.liveStreamClient=new Sr(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:D.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};x(this.videoState.stateChangeStarted$.pipe(E(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(E(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const i=Qe(this.video),r=(n,o)=>this.subscription.add(n.subscribe(o,s));r(i.timeUpdate$,e.liveTime$),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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ee.READY&&this.videoState.setState(ee.READY)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED)},s)).add(i.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING)},s)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ze(this.video,t.volume,i.volumeState$,s)).add(i.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ee.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(l.STOPPED);break;case ee.READY:break;case ee.PAUSED:t.playbackState.setState(l.PAUSED);break;case ee.PLAYING:t.playbackState.setState(l.PLAYING);break;default:return C(n.to)}},s)).add(x(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(_e(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}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.hostname$.next(ve(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:te.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,l.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ee.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:D.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition();if(e===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(r){this.prepare();return}switch(e){case ee.READY:t===l.PAUSED?(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)):t===l.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:t===l.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):s?.to===l.PLAYING&&w(this.params.desiredState.playbackState,l.PLAYING);return;case ee.PAUSED:t===l.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):s?.to===l.PAUSED&&w(this.params.desiredState.playbackState,l.PAUSED);return;default:return C(e)}}}class Ds{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 Boolean(this.current.done)}}var br=()=>{const a=window.navigator;return a.userAgentData?a.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const si=br(),es=document.createElement("video"),Ye={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(es.canPlayType?.("application/x-mpegurl")||es.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},we={mp4:Boolean(es.canPlayType?.("video/mp4")),webm:Boolean(es.canPlayType?.("video/webm")),cmaf:!0},et={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},pt=(et.h264||et.h265)&&et.aac,is=Ye.hls&&we.mp4,yr=Boolean(window.WebSocket),Tr=()=>Object.keys(et).filter(a=>et[a]),Er=(a,e=!1)=>a.filter(t=>{switch(t){case b.DASH:return Ye.mse&&we.mp4&&pt;case b.DASH_SEP:return Ye.mse&&we.mp4&&pt;case b.DASH_WEBM:return Ye.mse&&we.webm&&et.vp9&&et.opus;case b.DASH_LIVE:return Ye.mse&&we.mp4&&pt;case b.DASH_LIVE_CMAF:return Ye.mse&&we.mp4&&pt&&we.cmaf;case b.DASH_ONDEMAND:return Ye.mse&&we.mp4&&pt;case b.HLS:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.HLS_ONDEMAND:return is||e&&Ye.mse&&we.mp4&&pt;case b.MPEG:return we.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Ye.webrtc&&yr&&et.h264&&(we.mp4||we.webm);default:return C(t)}}),vr=()=>si?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:is?[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG,b.DASH]:[b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG],Ar=()=>si?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF]:is?[b.WEB_RTC_LIVE,b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE,b.DASH_LIVE_CMAF]:[b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF,b.HLS_LIVE,b.HLS_LIVE_CMAF],_s=a=>a?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var kr=a=>new Mt(e=>{const t=new X,s=a.desiredPlaybackState$.stateChangeStarted$.pipe(E(({from:d,to:h})=>`${d}-${h}`)),i=a.desiredPlaybackState$.stateChangeEnded$,r=a.providerChanged$,n=new _;let o=0,c="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),c="provider change",o=0})),t.add(r.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Is={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},wr={cacheDuration:12e4},$r={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Rr={maxPausedTime:3e4},xs={maxPausedTime:3e4};class Pr{current$=new g({type:void 0});providerError$=new _;noAvailableProvidersError$=new _;providerOutput={position$:new g(0),duration$:new g(1/0),volume$:new g({muted:!1,volume:1}),currentVideoTrack$:new g(void 0),availableVideoTracks$:new g([]),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),autoVideoTrackLimitingAvailable$:new g(!1),currentBuffer$:new g(void 0),isBuffering$:new g(!0),error$:new _,willSeekEvent$:new _,seekedEvent$:new _,loopedEvent$:new _,endedEvent$:new _,firstBytesEvent$:new _,firstFrameEvent$:new _,canplay$:new _,isLive$:new g(void 0),liveTime$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),element$:new g(void 0),is3DVideo$:new g(!1)};subscription=new X;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Er([...Ar(),...vr()],this.params.tuning.useHlsJs).filter(n=>A(e.sources[n])),{formatsToAvoid:s}=this.params.tuning,i=s.length?[...t.filter(n=>!s.includes(n)),...t.filter(n=>s.includes(n))]:t;this.screenFormatsIterator=new Ds(i);const r=[..._s(!0),..._s(!1)];this.chromecastFormatsIterator=new Ds(r.filter(n=>A(e.sources[n])))}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(W(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:D.WTF,message:"Failed to create provider",thrown:i})}s?this.current$.next({type:t,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;k(e,"No current provider"),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,s=this.params.desiredState.seekState.getState(),i=s.state!==M.None;this.params.desiredState.seekState.setState({state:M.Requested,position:i?s.position:t,forcePrecise:i?s.forcePrecise:!1}),e.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return C(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:i}=this.params,r=this.providerOutput,n={container:s,source:null,desiredState:i,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH:{const o=this.applyFailoverHost(t[e]);return k(o),new pa({...n,source:o,config:wr})}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return k(o),this.params.tuning.useDashJs?new bs({...n,source:o,format:e,config:xs}):new or({...n,source:o})}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return k(o),new bs({...n,source:o,format:e,config:xs})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return k(o),is||!this.params.tuning.useHlsJs?new lr({...n,source:o}):new cr({...n,source:o})}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return k(o),new ur({...n,source:o,config:Rr})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return k(o),new fr({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return k(o),new ca({...n,source:o,config:$r})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return k(o),new gr({container:s,source:o,desiredState:i,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return C(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:i,meta:r}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return k(o),new Ri({connection:o,meta:r,container:s,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ae.CHROMECAST:Ae.SCREEN}chooseFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return C(e)}}skipFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.next();case Ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return C(e)}}handleNoFormatsError(e){switch(e){case Ae.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case Ae.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return C(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=i=>{const r=new URL(i);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:s(e.url)}}return Object.fromEntries(Object.entries(e).map(([i,r])=>[i,s(r)]))}initProviderErrorHandling(){const e=new X;let t=!1,s=0;return e.add(x(this.providerOutput.error$,kr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Is.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(O(({type:i})=>i!==void 0))}).pipe(E(i=>({id:`ProviderHangup:${i}`,category:D.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const i=this.params.desiredState.playbackState.transitionEnded$.pipe(O(({to:r})=>r===l.PLAYING),pe()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{if(this.current$.getValue().destination===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const r=i.category===D.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<Is.providerErrorLimit;n&&(r&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var De;(function(a){a[a.LOCAL_STORAGE=0]="LOCAL_STORAGE",a[a.SESSION_STORAGE=1]="SESSION_STORAGE",a[a.RUNTIME=2]="RUNTIME"})(De||(De={}));const ii=new Map;let dt=De.RUNTIME;const ns=`vk-videoplayer-dummy-key-${Math.random()}`,Dr=()=>{try{localStorage.setItem(ns,"test"),localStorage.removeItem(ns),dt=De.LOCAL_STORAGE}catch(a){if(a instanceof DOMException||a instanceof TypeError)try{sessionStorage.getItem(ns),dt=De.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)dt=De.RUNTIME;else throw e}else throw a}};Dr();const _r=a=>{switch(dt){case De.LOCAL_STORAGE:return localStorage.getItem(a)??void 0;case De.SESSION_STORAGE:return sessionStorage.getItem(a)??void 0;case De.RUNTIME:return ii.get(a);default:C(dt)}},Cs=(a,e)=>{switch(dt){case De.LOCAL_STORAGE:try{localStorage.setItem(a,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case De.SESSION_STORAGE:try{sessionStorage.setItem(a,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case De.RUNTIME:return void ii.set(a,e);default:C(dt)}},cs=(a,e,t)=>t*e+(1-t)*a,ai=(a,e)=>a.reduce((t,s)=>t+s,0)/e,Ir=(a,e,t,s)=>{let i=0,r=t;const n=ai(a,e),o=e<s?e:s;for(let c=0;c<o;c++)a[r]>n?i++:i--,r=(a.length+r-1)%a.length;return Math.abs(i)===o};class ri{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new g(e.initial),this.debounced$=new g(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Be(`raw_${t}`),this.smoothedSeries$=new Be(`smoothed_${t}`),this.reportedSeries$=new Be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const i=Math.sqrt(t),r=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;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)&&(W(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 xr extends ri{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cs(this.slow,e,this.params.emaAlphaSlow),this.fast=cs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Cr extends ri{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ai(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cs(this.emaSmoothed,e,this.params.emaAlpha);const s=Ir(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Ls{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new xr({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Cr({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const Lr=5e3,Bs="one_video_throughput",Ms="one_video_rtt",Ct=window.navigator.connection,Ns=()=>{const a=Ct?.downlink;if(A(a)&&a!==10)return a*1e3},Os=()=>{const a=Ct?.rtt;if(A(a)&&a!==3e3)return a},Us=(a,e,t)=>{const s=t*8,i=s/a;return s/(i+e)};class Lt{throughput;rtt;subscription=new X;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Lt.load(Bs)||(e.useBrowserEstimation?Ns():void 0)||Lr,s=Lt.load(Ms)??(e.useBrowserEstimation?Os():void 0)??0;if(this.throughput$=new g(t),this.rtt$=new g(s),this.rttAdjustedThroughput$=new g(Us(t,s,e.rttPenaltyRequestSize)),this.throughput=Ls.getSmoothedValue(t,-1,e),this.rtt=Ls.getSmoothedValue(s,1,e),e.useBrowserEstimation){const i=()=>{const n=Ns();n&&this.throughput.next(n);const o=Os();A(o)&&this.rtt.next(o)};Ct&&"onchange"in Ct&&this.subscription.add(B(Ct,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{Cs(Bs,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{Cs(Ms,i.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ge({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(E(({throughput:i,rtt:r})=>Us(i,r,e.rttPenaltyRequestSize)),O(i=>{const r=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(i-r)/r>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=ce();const i=new X;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(B(e,"progress").pipe(pe()).subscribe(r=>{t=r.loaded,s=ce()}));break;case 1:case 0:i.add(B(e,"loadstart").subscribe(()=>{t=0,s=ce()}));break}i.add(B(e,"loadend").subscribe(r=>{if(e.status===200){const n=r.loaded,o=ce(),c=n-t,d=o-s;this.addRawSpeed(c,d,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let s=0;const i=ce();let r=0,n=ce();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(s,ce()-i,1),this.concurrentDownloads.delete(e)):h&&(s+=h.byteLength,r+=h.byteLength,r>=this.tuningConfig.streamMinSampleSize&&ce()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,ce()-n,this.concurrentDownloads.size),r=0,n=ce()),await t?.read().then(c,o))};this.concurrentDownloads.add(e),t?.read().then(c,o)}addRawSpeed(e,t,s=1){if(Lt.sanityCheck(e,t)){const i=e*8/t;this.throughput.next(i*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){const t=_r(e);if(A(t))return parseInt(t,10)??void 0}}const Vs={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},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},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,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,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},Br=a=>{const e={};for(const t of Object.keys(Vs)){const s=Vs[t],i=a[t];Array.isArray(s)&&Array.isArray(i)?e[t]=i:typeof s=="object"&&typeof i=="object"?e[t]={...s,...i}:e[t]=i??s}return e};var Mr=({seekState:a,position$:e})=>x(a.stateChangeEnded$.pipe(E(({to:t})=>t.state===M.None?void 0:(t.position??NaN)/1e3),O(A)),e.pipe(O(()=>a.getState().state===M.None))),Nr=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return k(e,`Wrong container or containerId {${a.container}}`),e};const Fs=({playbackState:a,seekState:e,playbackAbort$:t,looped$:s,position$:i})=>new Mt(r=>{let n;const o=a.transitionEnded$.pipe(O(S=>(S.from===l.PAUSED||S.from===l.STOPPED)&&S.to===l.PLAYING)),c=a.stateChangeEnded$.pipe(O(S=>S.from===l.PLAYING&&S.to===l.PAUSED)),d=e.stateChangeEnded$.pipe(O(({to:S})=>S.state===M.Requested&&(a.getTransition()?.from??a.getState())===l.PLAYING)),h=e.stateChangeEnded$.pipe(O(({from:S,to:p})=>S.state===M.Applying&&p.state===M.None&&(a.getTransition()?.from??a.getState())===l.PLAYING)),u=x(o,h).pipe(E(()=>i.getValue()),O(A)),f=x(x(c,d,t),s).pipe(E(()=>i.getValue()),O(A));return new X().add(u.subscribe(S=>{n=S})).add(f.subscribe(S=>{if(W(n)||n===S)return;const p={from:n,to:S};n=void 0,r.next(p)}))});class Yr{subscription=new X;domContainer;providerContainer;chromecastInitializer;logger=new ui;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new re(l.STOPPED),seekState:new re({state:M.None}),volume:new re({volume:1,muted:!1}),videoTrack:new re(void 0),autoVideoTrackSwitching:new re(!1),autoVideoTrackLimits:new re({}),isLooped:new re(!1),playbackRate:new re(1),externalTextTracks:new re([]),currentTextTrack:new re(void 0),textTrackCuesSettings:new re({}),cameraRotation:new re(!1)};info={playbackState$:new g(l.STOPPED),position$:new g(0),duration$:new g(1/0),muted$:new g(!1),volume$:new g(1),availableQualities$:new g([]),availableQualitiesFps$:new g({}),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),currentQuality$:new g(void 0),isAutoQualityEnabled$:new g(!0),autoQualityLimitingAvailable$:new g(!1),autoQualityLimits$:new g({}),currentPlaybackRate$:new g(1),currentBuffer$:new g({start:0,end:0}),isBuffering$:new g(!0),isStalled$:new g(!1),isEnded$:new g(!1),isLooped$:new g(!1),isLive$:new g(void 0),liveTime$:new g(void 0),currentFormat$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),throughputEstimation$:new g(void 0),rttEstimation$:new g(void 0),videoBitrate$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),chromecastState$:new g(Te.NOT_AVAILABLE),chromecastDeviceName$:new g(void 0),intrinsicVideoSize$:new g(void 0),is3DVideo$:new g(!1)};events={inited$:new _,started$:new _,willPause$:new _,willResume$:new _,willDestruct$:new _,watchCoverageRecord$:new _,watchCoverageLive$:new _,managedError$:new _,fatalError$:new _,ended$:new _,looped$:new _,seeked$:new _,willSeek$:new _,firstBytes$:new _,firstFrame$:new _,canplay$:new _,log$:new _};experimental={element$:new g(void 0),enableDebugTelemetry$:new g(!1),dumpTelemetry:Hi};constructor(e={}){if(this.initLogs(),this.tuning=Br(e),this.chromecastInitializer=new Si({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Lt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,i)=>{const r=Reflect.get(t,s,i);return typeof r!="function"?r:(...n)=>{try{return r.apply(t,n)}catch(o){const c=n.map(u=>JSON.stringify(u,(f,S)=>{const p=typeof S;return["number","string","boolean"].includes(p)?S:S===null?null:`<${p}>`})),d=`Player.${String(s)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:D.WTF,message:h,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Nr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Pr({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},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.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=this.desiredState.playbackState;return e.getState()!==l.PLAYING&&e.startTransitionTo(l.PLAYING),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){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:M.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()===Te.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()===Te.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){k(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const s=t.find(i=>i.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){k(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.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()}startCameraRotation(e,t){return this.desiredState.cameraRotation.setState({x:e,y:t,z:0}),this}stopCameraRotation(){return this.desiredState.cameraRotation.setState(!1),this}getExactTime(){k(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(W(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===M.None?void 0:t.position;return A(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:i})=>s||i||0,0),height:e.reduce((s,{height:i})=>s||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(x(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(E(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(E(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(E(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(E(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(E(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e===l.STOPPED),pe()).subscribe(()=>{this.initedAt=ce(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(()=>!this.isPlaybackStarted),O(e=>e.to===l.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.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();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const c=this.desiredState.seekState.getState();c.state===M.Requested?this.desiredState.seekState.setState({...c,state:M.Applying}):this.events.managedError$.next({id:`WillSeekIn${c.state}`,category:D.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===M.Applying&&(this.desiredState.seekState.setState({state:M.None}),this.events.seeked$.next())})).add(e.current$.pipe(E(c=>c.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(E(c=>c.destination),he()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(E(c=>c.map(({quality:d})=>d).sort((d,h)=>Wt(d)?1:Wt(h)?-1:Gt(h,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(c=>{const d={};for(const h of c)h.fps&&(d[h.quality]=h.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(c=>{this.info.currentQuality$.next(c?.quality),this.info.videoBitrate$.next(c?.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.currentBuffer$.pipe(E(c=>c?{start:c.from,end:c.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(E(c=>c.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(E(c=>c.volume),he()).subscribe(this.info.volume$)).add(Mr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(x(e.providerOutput.endedEvent$.pipe(ct(!0)),e.providerOutput.seekedEvent$.pipe(ct(!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(E(c=>({id:"NoProviders",category:D.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(pe(),E(()=>ce()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(pe(),E(()=>ce()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(pe(),E(()=>ce()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new g(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new g(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(({to:c})=>c===l.PLAYING),pe()).subscribe(()=>s.next(!1)));let i=0;const r=x(e.providerOutput.isBuffering$,t,s).pipe(E(()=>{const c=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||s.getValue();return c&&!d}),he());this.subscription.add(r.subscribe(c=>{c?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))}));const n=new X;this.subscription.add(n);const o=x(B(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(O(c=>Boolean(c?.provider))));e.providerOutput.isLive$.pipe(he()).subscribe(c=>{switch(k(this.providerContainer),n.unsubscribe(),c){case!0:{const d=new g(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(h=>d.next(h&&Math.floor(h/1e3)))),n.add(Fs({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe(E(({from:h,to:u})=>({start:h,end:u}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(Fs({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe(E(({from:d,to:h})=>({start:d,end:h}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(x(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:c?.videoWidth,height:c?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(c=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:c?.size?.width,height:c?.size?.height},{width:d?.videoWidth,height:d?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(c=>{this.info.is3DVideo$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(E(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new X;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((s,i)=>s.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(s=>s.length>0),pe()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Nt(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})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(x(this.desiredState.videoTrack.stateChangeStarted$.pipe(E(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(E(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(E(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(E(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(E(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(E(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(E(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(E(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(E(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;k(this.providerContainer),k(e),Fi(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Vi(t)),this.providerContainer.current$.subscribe(({type:t})=>Ft("provider",t)),e.duration$.subscribe(t=>Ft("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),pe()).subscribe(t=>Ft("tracks",t)),this.events.fatalError$.subscribe(new Be("fatalError")),this.events.managedError$.subscribe(new Be("managedError")),e.position$.subscribe(new Be("position")),e.currentVideoTrack$.pipe(E(t=>t?.quality)).subscribe(new Be("quality")),this.info.currentBuffer$.subscribe(new Be("buffer")),e.isBuffering$.subscribe(new Be("isBuffering"))].forEach(t=>this.subscription.add(t)),Ft("codecs",Tr())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>this.events.managedError$.next({id:"WakeLock",category:D.DOM,message:String(i)}))};this.subscription.add(x(B(document,"visibilitychange"),B(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const i=document.visibilityState==="visible",r=this.desiredState.playbackState.getState()===l.PLAYING,n=Boolean(e)&&!e?.released;i&&r?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const qr=`${pi}@${fi}`;export{Te as ChromecastState,Bt as HttpConnectionType,Wr as Observable,l as PlaybackState,Yr as Player,qr as SDK_VERSION,Qr as Subject,jr as Subscription,Jr as ValueSubject,b as VideoFormat,te as VideoQuality};