@vkontakte/videoplayer-core 2.0.85 → 2.0.86-dev.f2e1ec4.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/evergreen.esm.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.85
3
- * Fri, 28 Apr 2023 10:45:06 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-85/doc/
2
+ * @vkontakte/videoplayer-core v2.0.86-dev.f2e1ec4.0
3
+ * Wed, 10 May 2023 11:32:26 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-86/doc/
5
5
  */
6
- import{ValueSubject as b,Subject as _,Subscription as K,isNonNullable as A,ErrorCategory as R,isNullable as W,fromEvent as B,assertNever as L,merge as C,tap as as,map as E,observableFrom as $e,filterChanged as ue,assertNonNullable as k,debounce as _e,timeout as Ws,combine as qe,once as pe,mapTo as ot,filter as O,now as ce,Observable as Rt,abortable as Ce,getExponentialDelay as rs,interval as Qs,Logger as Js}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as sr,Subject as ir,Subscription as ar,ValueSubject as rr}from"@vkontakte/videoplayer-shared/esnext.esm.js";import js from"lodash/debounce.js";const Ks="2.0.85",Xs="evergreen.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 Zs=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 ei{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||Zs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){A(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();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(as(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),E(i=>i.castState)),$e([s.getCastState()])).pipe(ue(),E(ti),as(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:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}}const ti=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}},Ot=(a,e)=>Le[a].height>Le[e].height,si=(a,e)=>Le[a].height>=Le[e].height,$t=(a,e)=>Le[a].height<Le[e].height,ii=(a,e)=>Le[a].height<=Le[e].height,ai=a=>a.sort((e,t)=>e===t?0:e===se.INVARIANT?1:t===se.INVARIANT?-1:$t(e,t)?1:-1)[0],ri=Object.keys(Le).sort((a,e)=>$t(a,e)?-1:1),dt=({width:a,height:e})=>{const t=Math.min(a,e),s=Math.max(a,e);return ri.find(i=>{const r=Le[i];return r.width>=s&&r.height>=t})},ni=a=>Le[a].height,Vt=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 oi=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 di=5,ci=5,ui=500,ns=7e3;class hi{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(oi(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(ui)).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)>di)&&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<ci&&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=ai(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:R.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(Ws(ns).subscribe(()=>r(`timeout(${ns})`)))});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:R.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)}}}}const Et=a=>a.range?a.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class kt{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]=Et(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(Et),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 AbortController,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:R.PARSER,message:"Error parsing response data",thrown:f}),f};return fetch(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,kt.suppressStreamErrors).catch(h))};m?.read().then(x,kt.suppressStreamErrors).catch(h)},kt.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]=Et(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:R.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]=Et(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]=Et(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 Ft{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(Ft.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;Ft.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const li=(a,e)=>t=>({create:s=>{const i=a(t).create(s);return new Ft(i,e,s)}}),fi=(a,e)=>{const t=new kt(e);return a.extend("SchemeLoaderFactory",function(){const{parent:s}=this,i=s.getLoader;return{getLoader:r=>{const n=i(r);return li(n,t)}}},!0),()=>t.destroy()};var pi=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)},mi=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}},mt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Si=a=>a.extend("RequestModifier",()=>({modifyRequestURL:mt}),!0),gi=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}),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("|"),yi=(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:R.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: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)&&yi(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 es{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 Rs=()=>{const{userAgent:a}=window.navigator;return!/chrome/i.test(a)&&/webkit|safari|khtml/i.test(a)};const Kt=3;class Ti{_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<Kt&&(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||Kt))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 _s=(a,e,t=Kt)=>{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 Ei=50,vi=a=>a.webkitAudioDecodedByteCount!==void 0?!!a.webkitAudioDecodedByteCount:a.mozHasAudio!==void 0?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(()=>_s(a.buffered,a.currentTime))),r=Rs()?qe({play:e("play").pipe(pe()),playing:e("playing")}).pipe(ot(void 0)):e("playing"),n=B(a,"playing").pipe(_e(Ei),E(()=>vi(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:R.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}},ts=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let ss=!1,He={};const Ai=a=>{ss=a},$i=()=>{He={}},ki=a=>{a(He)},xt=(a,e)=>{ss&&(He.meta=He.meta??{},He.meta[a]=e)};class Be{name;constructor(e){this.name=e}next(e){if(!ss)return;He.series=He.series??{};const t=He.series[this.name]??[];t.push([Date.now(),e]),He.series[this.name]=t}}const wi=new Be("best_bitrate"),Pi=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class Di{last;history={};recordSelection(e){this.history[e.id]=ce()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const _t=(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=>!Vt(H.quality)).sort((H,ie)=>Ot(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)&&$t(i.max,i.min)||A(i.min)&&y&&Ot(i.min,y)||A(i.max)&&m&&$t(i.max,m),x=S*Pi(n??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),$=p.filter(H=>{const ie=f?$t(H.quality,f):!0,Y=A(t)&&isFinite(t)&&A(H.bitrate)?t-r>=H.bitrate*x:!0,j=s.lazyQualitySwitch&&A(s.minBufferToSwitchUp)&&c&&!Vt(c.quality)&&(n??0)<s.minBufferToSwitchUp&&Ot(H.quality,c.quality),ne=P||(W(i.max)||ii(H.quality,i.max))&&(W(i.min)||si(H.quality,i.min));return ie&&Y&&!j&&ne})[0];$&&$.bitrate&&wi.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 Ri=300,Ht=(a,e=Ri)=>new Rt(t=>{const{width:s,height:i}=a.getBoundingClientRect();if(t.next({width:s,height:i}),!window.ResizeObserver)return;const r=new ResizeObserver(js(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()}),Qe=a=>{try{a.pause(),a.playbackRate=0,a.removeAttribute("src"),a.load(),a.remove()}catch(e){console.error(e)}},_i=5e3,vt={};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 Rt(t=>{const s=i=>t.next(i);return a.on(e,s),()=>a.off(e,s)});class os{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 es;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:R.NETWORK,message:`Dash.js failed to load: ${i?.toString?.()}`,thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),_i);import("dashjs/dist/dash.mediaplayer.min.js").then(i=>{e||(vt.MediaPlayer=i.MediaPlayer,vt.Debug=i.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){k(vt.MediaPlayer,"dashjs not loaded"),k(vt.Debug,"dashjs not loaded"),this.player=vt.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?ts(t.frameRate+""):void 0),!0)),(this.params.format===g.DASH_WEBM||this.params.format===g.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=fi(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&&gi(this.player),pi(this.player),this.params.tuning.requestQuick&&Si(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:R.WTF,message:"DashIFProvider internal logic error",thrown:m})},i=(m,y)=>this.subscription.add(m.subscribe(y,s));i(Ht(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},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===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=_t(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(qe({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(qe({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(()=>_s(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(Ht(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}=mi(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(qe({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(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=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{}Qe(this.video),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var It=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}},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 Is(a){return ye()-a}function ds(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 Ii(a,e,t){const s=(...i)=>{t.apply(null,i),a.removeEventListener(e,s)};a.addEventListener(e,s)}function Ut(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=Is(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 Je=()=>(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(Je(),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(Je(),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 Ci=100,Li=2e3,xi=500;let Bi=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>Li){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>Ci&&(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 Ni{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=Ut(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 Bt=1e4,Nt=3,Mi=300,Oi=2e3,Ui=6e4,Vi=10,Fi=1,Hi=500;class Yi{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 Bi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ds(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=ds(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=()=>{Ii(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 Ni(Nt,Bt,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=Ut(this.urlResolver.resolve($,!1),v,F,()=>this._retryCallback()).withTimeout(Bt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Nt).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 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=$-Fi;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,X)=>({chunkIdx:Y(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>Vi)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=Ut(this.urlResolver.resolve(I,!0,this.lowLatency),X,he,()=>this._retryCallback()).withTimeout(Bt).withRetryCount(Nt).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,Y,j,ne,J=0,le,xe,Je;const I=()=>{le&&(clearTimeout(le),le=void 0);const q=Math.max(Hi,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=J+q,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 q;for(;q=H.nextChunk(ne);)ne=q,gt(q);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=(q,ge)=>{if(!h()||!this.sourceBuffer)return;let Se,be,Oe;const Ue=Ie=>{window.setTimeout(()=>{h()&&he(q,ge)},Ie)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),Ue(100);else{const Ie=ye(),Ke=v.currentTime;!this.paused&&v.buffered.length>1&&xe===Ke&&Ie-Je>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),xe!==Ke&&(xe=Ke,Je=Ie);const Xe=this._getBufferSizeSec();if(Xe>30)F(`Buffered ${Xe} seconds; delaying appendBuffer`),Ue(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:Ie,buf:Xe}),y(),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"),Oe=this.sourceBuffer.buffered.length,Oe!==0&&(Se=this.sourceBuffer.buffered.start(0),be=Ke,be-Se>4&&this.sourceBuffer.remove(Se,be-3)),Ue(1e3);else throw Ze}}},me=()=>{Y&&ie&&(F([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(j)]),he(Y,function(){Y=null,X()}))},Ee=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),je=q=>{h()&&S(Ee(q),(ge,Se)=>{if(h()){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())},gt=q=>{h()&&(k(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(q),!1)))},Lt=q=>{h()&&(e.cachedHeader=q,he(q,()=>{ie=!0,me()}))};r=!0,H.seek(q=>{if(h()){if(J=ye(),!q){I();return}ne=q,!W($)||q.startTS>$?je(q):(j=q,X())}},$),e.cachedHeader?Lt(e.cachedHeader):f(e.headerUrl,Lt,()=>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&&Is(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=Ut(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Bt).withRetryCount(Nt).withRetryInterval(Mi,Oi).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))},Ui))}_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 qi=[V.PAUSED,V.PLAYING,V.READY],Gi=[V.PAUSED,V.PLAYING,V.READY];class zi{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 es;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:R.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(qe({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(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&&ni(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.dash.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}createLiveDashPlayer(){const e=new Yi({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:_t(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:R.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=It(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.removeAttribute("src"),this.video.load(),this.videoState.setState(V.STOPPED));return}if(!t){if(Gi.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&&qi.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 Cs=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}},rt=(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 Wi=a=>{const e=document.createElement("a");return e.href=a,e.origin},Qi=a=>{const e=document.createElement("a");return e.href=a,e.host};class Ls{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],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(Qi(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=mt(p)),this._lastXhr=new Ls(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 Ji{_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=mt(s)),new Ls(s,t,i=>{this.attachManifest(i,t,Wi(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?ts(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 ji=[G.PAUSED,G.PLAYING];class Ki{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 Ti(this.video),this.dash=new Ji({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:R.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"DashProvider",category:R.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(tt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(Ht(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:R.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=rt(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=_t(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(qe({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=rt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!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}=Cs(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.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return L(e)}}handleManifestReady=e=>{const t=[];for(const s of e){const i=s.name??s.id??s.height.toString(10),r=(s.name&&It(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(){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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(G.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(!t)switch(i?.to!==l.PAUSED&&r.state===N.Requested&&ji.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 qt;(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"})(qt||(qt={}));var De;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(De||(De={}));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 St;(function(a){a.MP4="mp4",a.WEBM="webm"})(St||(St={}));var Xt=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};let xs=!1;try{xs=Rs()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Xi{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);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:R.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 cs=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};const Bs=new TextDecoder("ascii"),Ns=a=>{let e=0,t=a.getUint32(e);e+=4;const s=new DataView(a.buffer,a.byteOffset+e,4),i=Bs.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}},Zi=a=>Bs.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ea=(a,e,t)=>{const s=Ns(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},ta=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=Ns(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},sa={validateData:Zi,parseInit:()=>null,getIndexRange:()=>{},parseSegments:ea,parseFeedableSegmentChunk:ta};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 D;(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"})(D||(D={}));const us={[T.EBML]:{type:D.Master},[T.EBMLVersion]:{type:D.UnsignedInteger},[T.EBMLReadVersion]:{type:D.UnsignedInteger},[T.EBMLMaxIDLength]:{type:D.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[T.DocType]:{type:D.String},[T.DocTypeVersion]:{type:D.UnsignedInteger},[T.DocTypeReadVersion]:{type:D.UnsignedInteger},[T.Void]:{type:D.Binary},[T.Segment]:{type:D.Master},[T.SeekHead]:{type:D.Master},[T.Seek]:{type:D.Master},[T.SeekID]:{type:D.Binary},[T.SeekPosition]:{type:D.UnsignedInteger},[T.Info]:{type:D.Master},[T.TimestampScale]:{type:D.UnsignedInteger},[T.Duration]:{type:D.Float},[T.Tracks]:{type:D.Master},[T.Chapters]:{type:D.Master},[T.Cluster]:{type:D.Master},[T.Timestamp]:{type:D.UnsignedInteger},[T.SilentTracks]:{type:D.Master},[T.SilentTrackNumber]:{type:D.UnsignedInteger},[T.Position]:{type:D.UnsignedInteger},[T.PrevSize]:{type:D.UnsignedInteger},[T.SimpleBlock]:{type:D.Binary},[T.BlockGroup]:{type:D.Master},[T.EncryptedBlock]:{type:D.Binary},[T.Attachments]:{type:D.Master},[T.Tags]:{type:D.Master},[T.Cues]:{type:D.Master},[T.CuePoint]:{type:D.Master},[T.CueTime]:{type:D.UnsignedInteger},[T.CueTrackPositions]:{type:D.Master},[T.CueTrack]:{type:D.UnsignedInteger},[T.CueClusterPosition]:{type:D.UnsignedInteger},[T.CueRelativePosition]:{type:D.UnsignedInteger},[T.CueDuration]:{type:D.UnsignedInteger},[T.CueBlockNumber]:{type:D.UnsignedInteger},[T.CueCodecState]:{type:D.UnsignedInteger},[T.CueReference]:{type:D.Master},[T.CueRefTime]:{type:D.UnsignedInteger}},Ms=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Gt(a,t),i=s in us,r=i?us[s].type:D.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=Gt(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}},Gt=(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},Ye=(a,e)=>{switch(e){case D.SignedInteger:return a.getInt8(0);case D.UnsignedInteger:return Gt(a);case D.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(a);case D.UTF8:return new TextDecoder("utf-8").decode(a);case D.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case D.Master:return a;case D.Binary:return a;default:L(e)}},Ct=(a,e)=>{let t=0;for(;t<a.byteLength;){const s=new DataView(a.buffer,a.byteOffset+t),i=Ms(s);if(!e(i))return;i.type===D.Master&&Ct(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},ia=a=>{if(a.getUint32(0)!==T.EBML)return!1;let e,t,s;const i=Ms(a);return Ct(i.value,({tag:r,type:n,value:o})=>(r===T.EBMLReadVersion?e=Ye(o,n):r===T.DocType?t=Ye(o,n):r===T.DocTypeReadVersion&&(s=Ye(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Os=[T.Info,T.SeekHead,T.Tracks,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],aa=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],ra=a=>{let e,t,s,i,r=!1,n=!1,o=!1,c,d;return Ct(a,({tag:u,type:h,value:f,valueSize:S})=>{if(u===T.SeekID){const p=Ye(f,h);d=Gt(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=Ye(f,h):u===T.Duration?i=Ye(f,h):u===T.SeekPosition&&d===T.Cues?c=Ye(f,h):r&&n&&Os.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}},na=a=>{if(W(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},oa=(a,e)=>{let t=!1,s=!1;const i=o=>A(o.time)&&A(o.position),r=[];let n;return Ct(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=Ye(d,c));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=Ye(d,c));break;default:t&&Os.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}}})},da=a=>{let e=0,t=!1;try{Ct(a,s=>s.tag===T.Cluster?s.tagSize<=a.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):aa.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},ca={validateData:ia,parseInit:ra,getIndexRange:na,parseSegments:oa,parseFeedableSegmentChunk:da};class hs{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 AbortController;destroyAbortController=new AbortController;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 St.MP4:this.containerParser=sa;break;case St.WEBM:this.containerParser=ca;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 Xi(this.sourceBuffer),this.subscription.add(B(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(B(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,cs(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 AbortController,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=rt(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)&&cs(this.sourceBuffer.buffered)>=this.bufferLimit){const d=rt(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&&rt(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&&!Xt(this.sourceBuffer.buffered,s))&&y&&x});if(i===-1)return[];if(t!==De.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 De.BYTE_RANGE:{i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case De.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=rs(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:R.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=rt(this.sourceBuffer?.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:R.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===De.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=requestIdleCallback(()=>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=rs(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:R.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=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:R.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 ua{throughputEstimator;requestQuic;lastConnectionType$=new b(void 0);lastConnectionReused$=new b(void 0);lastRequestFirstBytes$=new b(void 0);abortAllController=new AbortController;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}=Cs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=Ce(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=mt(t));const s=yield fetch(t,{signal:this.abortAllController.signal}).catch(At);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 Y=new URL(c,location.href);Y.searchParams.append("bytes",`${s.from}-${s.to}`),c=Y.toString();break}default:L(t)}this.requestQuic&&(c=mt(c));let u=this.abortAllController.signal;if(n){const Y=new AbortController;if(this.subscription.add(C(B(this.abortAllController.signal,"abort"),B(n,"abort")).subscribe(()=>{try{Y.abort()}catch(j){At(j)}})),this.abortAllController.signal.aborted||n.aborted)try{Y.abort()}catch(j){At(j)}u=Y.signal}const h=ce(),f=yield fetch(c,{priority:r,headers:d,signal:u}).catch(At),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 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,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=Y=>{F=!0,At(Y)},ie=Ce(u,async function*({done:Y,value:j}){x===0&&this.lastRequestFirstBytes$.next(ce()-h),!u.aborted&&(Y?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 De.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case De.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!==De.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!==De.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 At=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},ls=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},Qt=(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},ha=(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=ls(d);else if(u){const p=ls(u);A(p)&&(c=p)}let h=0;const f=r.getAttribute("profiles")?.split(",")??[],S=f.includes(qt.WEBM_AS_IN_FFMPEG)||f.includes(qt.WEBM_AS_IN_SPEC)?St.WEBM:St.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,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")??"",xe=v.getAttribute("quality")??void 0,Je=le?ts(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,...Y];let gt;const Lt=v.querySelector("SegmentBase"),q=v.querySelector("SegmentTemplate")??$;if(Lt){const Se=v.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[be,Oe]=Se.split("-").map(it=>parseInt(it,10)),Ue={from:be,to:Oe},Ie=v.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ke,Xe]=Ie?Ie.split("-").map(it=>parseInt(it,10)):[],Ze=Ie?{from:Ke,to:Xe}:void 0;gt={type:De.BYTE_RANGE,url:Ee,initRange:Ue,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),Oe=q.getAttribute("initialization")??"",Ue=q.getAttribute("media"),Ie=parseInt(q.getAttribute("startNumber")??"",10)??1,Ke=Qt(Oe,Se);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Xe=q.querySelectorAll("SegmentTimeline S")??[],Ze=[];if(Xe.length){let it=Ie,at=0;for(const bt of Xe){const ut=parseInt(bt.getAttribute("d")??"",10)*1e3,yt=parseInt(bt.getAttribute("r")??"",10)||0,Tt=parseInt(bt.getAttribute("t")??"",10)??void 0;for(let is=0;is<yt+1;is++){const qs=Qt(Ue,{...Se,segmentNumber:it.toString(10),segmentTime:Tt.toString(10)}),Gs=Tt?Tt/be:at;at+=ut/be;const zs=at;it++,Ze.push({time:{from:Gs,to:zs},url:qs})}}}else if(A(c)){const at=parseInt(q.getAttribute("duration")??"",10)/be*1e3,bt=Math.ceil(c/at);let ut=0;for(let yt=1;yt<bt;yt++){const Tt=Qt(Ue,{...Se,segmentNumber:yt.toString(10),segmentTime:ut.toString(10)});Ze.push({time:{from:ut,to:ut+at},url:Tt}),ut+=at}}gt={type:De.TEMPLATE,baseUrl:Ee,initUrl:Ke,segments:Ze}}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:gt,profiles:je,duration:c,bitrate:J,mime:F,codecs:H,width:j,height:ne,fps:Je,quality:xe})}}return{duration:c,container:S,representations:i}},la=["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 fa=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 AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ua({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:R.NETWORK,message:"Failed to load manifest",thrown:n}));if(!s)return;let i;try{i=ha(s??"",t)}catch(n){this.error$.next({id:"ManifestParsing",category:R.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:R.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 hs(Pe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],A(t)&&(this.audioBufferManager=new hs(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$,qe({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:R.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(...la.map(e=>B(this.element,e)),B(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.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&&Xt(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),Xt(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?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Qs(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),t=>{this.error$.next({id:"GapWatchdog",category:R.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 pa=({id:a,width:e,height:t,bitrate:s,fps:i,quality:r})=>{const n=(r?It(r):void 0)??dt({width:e,height:t});return n&&{id:a,quality:n,bitrate:s,size:{width:e,height:t},fps:i}},ma=({id:a,bitrate:e})=>({id:a,bitrate:e}),Sa=(a,e,t)=>{const s=e.indexOf(t);return a.at(Math.round(a.length*s/e.length))??a.at(-1)};class ga{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 Di;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 fa({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:R.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(tt(this.video,t.playbackRate,s.playbackRateState$,i)),r(Ht(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=ma(p);m&&this.audioTracks.push({track:m,representation:p})}for(const p of f){const m=pa(p);if(m){this.videoTracks.push({track:m,representation:p});const y=!this.params.tuning.isAudioDisabled&&Sa(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:R.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=rt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(r/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),c=Math.max(s&&!e?this.audioRepresentations.get(s.id)?.bitrate??0:0,i?this.audioRepresentations.get(i.id)?.bitrate??0:0),d=_t(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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),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.player.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))})}}const ba=5e3,Ve={};var z;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(z||(z={}));const Mt=(a,e)=>new Rt(t=>{const s=(i,r)=>t.next(r);return a.on(e,s),()=>a.off(e,s)});class ya{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.params.output.element$.next(void 0),Qe(this.video)}loadHlsJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),ba);import("hls.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:R.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(tt(this.video,e.playbackRate,i.playbackRateState$,s)),this.subscription.add(Mt(this.hls,Ve.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(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(Mt(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=It(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(Mt(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=Mt(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 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.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0)}}const fs="X-Playback-Duration";var ps=async a=>{const e=await fetch(a,{method:"HEAD"});return e.headers.has(fs)?parseInt(e.headers.get(fs),10):void 0};const Ta=a=>{let e=null;if(a.QUALITY&&(e=It(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},Us=async(a,e=a)=>{const i=(await(await fetch(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=Ta(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 Ea{subscription=new K;videoState=new re(ee.STOPPED);video;params;textTracksManager=new Me;manifests$=new b([]);maxSeekBackTime$;liveOffset=new es;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]),Us(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:R.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:R.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(tt(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(qe({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.params.output.element$.next(void 0),Qe(this.video)}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(),ps(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{fetch(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();ps(o).then(c=>{W(c)||this.maxSeekBackTime$.next(c)})}})}catch{}}})}playIfAllowed(){st(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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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 va{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)),Us(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.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:R.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(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(),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.params.output.element$.next(void 0),Qe(this.video)}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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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 Aa{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:R.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(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=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.params.output.element$.next(void 0),Qe(this.video)}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=mt(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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),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 ms=["stun:videostun.mycdn.me:80"],$a=1e3,ka=3,Jt=()=>null;class wa{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Jt;externalStopCallback=Jt;externalErrorCallback=Jt;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:ms}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:R.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),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),$a)}normalizeOptions(e={}){const t={stunServerList:ms,maxRetryNumber:ka,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 Pa{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 wa(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Qe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.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:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){st(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 Ss{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 Da=()=>{const a=window.navigator;return a.userAgentData?a.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const Vs=Da(),zt=document.createElement("video"),Fe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(zt.canPlayType?.("application/x-mpegurl")||zt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},ke={mp4:Boolean(zt.canPlayType?.("video/mp4")),webm:Boolean(zt.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"'))},ht=(et.h264||et.h265)&&et.aac,Wt=Fe.hls&&ke.mp4,Ra=Boolean(window.WebSocket),_a=()=>Object.keys(et).filter(a=>et[a]),Ia=(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&&et.vp9&&et.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 Wt||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&&Ra&&et.h264&&(ke.mp4||ke.webm);default:return L(t)}}),Ca=()=>Vs?[g.MPEG,g.DASH_WEBM,g.DASH_SEP,g.DASH,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND]:Wt?[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],La=()=>Vs?[g.HLS_LIVE,g.HLS_LIVE_CMAF,g.WEB_RTC_LIVE,g.DASH_LIVE,g.DASH_LIVE_CMAF]:Wt?[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],gs=a=>a?[g.HLS_LIVE]:[g.DASH_WEBM,g.DASH_SEP,g.DASH_ONDEMAND,g.HLS,g.HLS_ONDEMAND,g.MPEG];var xa=a=>new Rt(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 bs={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Ba={cacheDuration:12e4},Na={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Ma={maxPausedTime:3e4},ys={maxPausedTime:3e4};class Oa{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=Ia([...La(),...Ca()],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 Ss(i);const r=[...gs(!0),...gs(!1)];this.chromecastFormatsIterator=new Ss(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:R.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 Ki({...n,source:o,config:Ba})}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 os({...n,source:o,format:e,config:ys}):new ga({...n,source:o})}case g.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return k(o),new os({...n,source:o,format:e,config:ys})}case g.HLS:case g.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return k(o),Wt||!this.params.tuning.useHlsJs?new va({...n,source:o}):new ya({...n,source:o})}case g.HLS_LIVE:case g.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return k(o),new Ea({...n,source:o,config:Ma})}case g.MPEG:{const o=this.applyFailoverHost(t[e]);return k(o),new Aa({...n,source:o})}case g.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return k(o),new zi({...n,source:o,config:Na})}case g.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return k(o),new Pa({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 hi({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$,xa({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:bs.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(O(({type:i})=>i!==void 0))}).pipe(E(i=>({id:`ProviderHangup:${i}`,category:R.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===R.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<bs.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 Re;(function(a){a[a.LOCAL_STORAGE=0]="LOCAL_STORAGE",a[a.SESSION_STORAGE=1]="SESSION_STORAGE",a[a.RUNTIME=2]="RUNTIME"})(Re||(Re={}));const Fs=new Map;let nt=Re.RUNTIME;const jt=`vk-videoplayer-dummy-key-${Math.random()}`,Ua=()=>{try{localStorage.setItem(jt,"test"),localStorage.removeItem(jt),nt=Re.LOCAL_STORAGE}catch(a){if(a instanceof DOMException||a instanceof TypeError)try{sessionStorage.getItem(jt),nt=Re.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)nt=Re.RUNTIME;else throw e}else throw a}};Ua();const Va=a=>{switch(nt){case Re.LOCAL_STORAGE:return localStorage.getItem(a)??void 0;case Re.SESSION_STORAGE:return sessionStorage.getItem(a)??void 0;case Re.RUNTIME:return Fs.get(a);default:L(nt)}},Ts=(a,e)=>{switch(nt){case Re.LOCAL_STORAGE:try{localStorage.setItem(a,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Re.SESSION_STORAGE:try{sessionStorage.setItem(a,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Re.RUNTIME:return void Fs.set(a,e);default:L(nt)}},Zt=(a,e,t)=>t*e+(1-t)*a,Hs=(a,e)=>a.reduce((t,s)=>t+s,0)/e,Fa=(a,e,t,s)=>{let i=0,r=t;const n=Hs(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 Ys{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 Ha extends Ys{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Zt(this.slow,e,this.params.emaAlphaSlow),this.fast=Zt(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Ya extends Ys{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Hs(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Zt(this.emaSmoothed,e,this.params.emaAlpha);const s=Fa(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Es{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Ha({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Ya({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const qa=5e3,vs="one_video_throughput",As="one_video_rtt",wt=window.navigator.connection,$s=()=>{const a=wt?.downlink;if(A(a)&&a!==10)return a*1e3},ks=()=>{const a=wt?.rtt;if(A(a)&&a!==3e3)return a},ws=(a,e,t)=>{const s=t*8,i=s/a;return s/(i+e)};class Pt{throughput;rtt;subscription=new K;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Pt.load(vs)||(e.useBrowserEstimation?$s():void 0)||qa,s=Pt.load(As)??(e.useBrowserEstimation?ks():void 0)??0;if(this.throughput$=new b(t),this.rtt$=new b(s),this.rttAdjustedThroughput$=new b(ws(t,s,e.rttPenaltyRequestSize)),this.throughput=Es.getSmoothedValue(t,-1,e),this.rtt=Es.getSmoothedValue(s,1,e),e.useBrowserEstimation){const i=()=>{const n=$s();n&&this.throughput.next(n);const o=ks();A(o)&&this.rtt.next(o)};wt&&"onchange"in wt&&this.subscription.add(B(wt,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{Ts(vs,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{Ts(As,i.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(qe({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(E(({throughput:i,rtt:r})=>ws(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(Pt.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=Va(e);if(A(t))return parseInt(t,10)??void 0}}const Ps={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}},Ga=a=>{const e={};for(const t of Object.keys(Ps)){const s=Ps[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 za=({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))),Wa=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return k(e,`Wrong container or containerId {${a.container}}`),e};const Ds=({playbackState:a,seekState:e,playbackAbort$:t,looped$:s,position$:i})=>new Rt(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 Xa{subscription=new K;domContainer;providerContainer;chromecastInitializer;logger=new Js;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:ki};constructor(e={}){if(this.initLogs(),this.tuning=Ga(e),this.chromecastInitializer=new ei({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Pt(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:R.WTF,message:u,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Wa(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Oa({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:R.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)=>Vt(d)?1:Vt(u)?-1:Ot(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(za({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:R.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(Ds({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(Ds({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=_t(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),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),$i(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ai(t)),this.providerContainer.current$.subscribe(({type:t})=>xt("provider",t)),e.duration$.subscribe(t=>xt("duration",t)),e.availableVideoTracks$.pipe(O(t=>!!t.length),pe()).subscribe(t=>xt("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)),xt("codecs",_a())}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=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:R.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 Za=`${Xs}@${Ks}`;export{Te as ChromecastState,Dt as HttpConnectionType,sr as Observable,l as PlaybackState,Xa as Player,Za as SDK_VERSION,ir as Subject,ar as Subscription,rr as ValueSubject,g as VideoFormat,se as VideoQuality};
6
+ import{ValueSubject as g,Subject as I,Subscription as ie,isNonNullable as $,ErrorCategory as R,isNullable as J,fromEvent as B,assertNever as N,merge as M,tap as is,map as v,observableFrom as Ae,filterChanged as ce,assertNonNullable as k,debounce as Re,timeout as zs,combine as Be,once as pe,mapTo as lt,filter as j,now as ue,Observable as Gt,abortable as Ie,getExponentialDelay as as,interval as Ws,safeStorage as Wt,Logger as Qs,ACTIVE_LIVE_VALID_DELAY as Js}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as tr,Subject as sr,Subscription as ir,ValueSubject as ar}from"@vkontakte/videoplayer-shared/esnext.esm.js";import js from"lodash/debounce.js";const Ks="2.0.86-dev.f2e1ec4.0",Xs="evergreen.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 $e;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})($e||($e={}));var ge;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(ge||(ge={}));var Pt;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(Pt||(Pt={}));var U;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(U||(U={}));var Ze;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(Ze||(Ze={}));var Zs=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 ei{connection$=new g(void 0);castState$=new g(ge.NOT_AVAILABLE);errorEvent$=new I;contentId;realCastState$=new g(ge.NOT_AVAILABLE);subscription=new ie;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=$(window.chrome?.cast),i=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=r=>{delete window.__onGCastApiAvailable,r&&this.initializeCastApi()},i||Zs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){$(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();J(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();J(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),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 N(i.sessionState)}})).add(M(B(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(is(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),v(i=>i.castState)),Ae([s.getCastState()])).pipe(ce(),v(ti),is(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{const r=i===ge.CONNECTED,n=$(this.connection$.getValue());if(r&&!n){const o=s.getCurrentSession();k(o);const u=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(J(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!r&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i===ge.CONNECTED?$(this.connection$.getValue())?ge.CONNECTED:ge.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:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}}const ti=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ge.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ge.AVAILABLE;case cast.framework.CastState.CONNECTING:return ge.CONNECTING;case cast.framework.CastState.CONNECTED:return ge.CONNECTED;default:return N(a)}};var ht;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ht||(ht={}));var ft=(a,e=0,t=ht.OFFSET_P)=>{switch(t){case ht.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ht.PLAYBACK_SHIFT:{if(e===0)return a;const s=new URL(a);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:N(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 Ce={[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}},Nt=(a,e)=>Ce[a].height>Ce[e].height,si=(a,e)=>Ce[a].height>=Ce[e].height,$t=(a,e)=>Ce[a].height<Ce[e].height,ii=(a,e)=>Ce[a].height<=Ce[e].height,ai=a=>a.sort((e,t)=>e===t?0:e===se.INVARIANT?1:t===se.INVARIANT?-1:$t(e,t)?1:-1)[0],ri=Object.keys(Ce).sort((a,e)=>$t(a,e)?-1:1),nt=({width:a,height:e})=>{const t=Math.min(a,e),s=Math.max(a,e);return ri.find(i=>{const r=Ce[i];return r.width>=s&&r.height>=t})},ni=a=>Ce[a].height,Ot=a=>a===se.INVARIANT;class ne{state;transition;transitionStarted$=new I;transitionEnded$=new I;transitionUpdated$=new I;forceChanged$=new I;stateChangeStarted$=M(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=M(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||$(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 oi=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 N(a)}};var O;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(O||(O={}));const di=5,ui=5,ci=500,rs=7e3;class hi{subscription=new ie;loadMediaTimeoutSubscription=new ie;videoState=new ne(O.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(oi(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 ie;this.subscription.add(e),this.subscription.add(M(this.videoState.stateChangeStarted$.pipe(v(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(v(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 I;e.add(i.pipe(Re(ci)).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===U.Applying||Math.abs(o-r)>di)&&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(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&r.duration-r.currentTime<ui&&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:N(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=M(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(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(O.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED)):(this.videoState.setState(O.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:U.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===O.PAUSED||e===O.PLAYING)&&(this.videoState.setState(O.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===O.PLAYING||e===O.PAUSED)&&(this.videoState.setState(O.PLAYING),w(this.params.desiredState.playbackState,l.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===O.READY&&this.videoState.setState(O.READY),this.params.desiredState.playbackState.getTransition()?.to===l.READY&&w(this.params.desiredState.playbackState,l.READY)}handleRemoteStop(){this.videoState.getState()!==O.STOPPED&&this.videoState.setState(O.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 c=ai(Object.keys(d));k(c);const h=d[c];k(h),s=h,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=ft(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",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.VIDEO_PIPELINE,message:d,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return N(e)}const n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??s,i);n.contentUrl=s,n.streamType=r,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:u}=this.params.meta;return $(o)&&(n.metadata.title=o),$(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===U.Applying||s.state===U.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(zs(rs).subscribe(()=>r(`timeout(${rs})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===U.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:R.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!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.stop());return}if(!t){if(i?.to!==l.PAUSED&&r.state===U.Requested&&e!==O.STOPPED){this.seek(r.position/1e3);return}switch(s){case l.READY:{switch(e){case O.PLAYING:case O.PAUSED:case O.READY:break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:N(e)}break}case l.PLAYING:{switch(e){case O.PLAYING:break;case O.PAUSED:this.videoState.startTransitionTo(O.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case O.READY:this.videoState.startTransitionTo(O.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:N(e)}break}case l.PAUSED:{switch(e){case O.PLAYING:this.videoState.startTransitionTo(O.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case O.PAUSED:break;case O.READY:this.videoState.startTransitionTo(O.PAUSED),this.videoState.setState(O.PAUSED);break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:N(e)}break}default:N(s)}}}}const Tt=a=>a.range?a.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class At{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]=Tt(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(Tt),i=s[0][0];let r=s[0][1];for(let f=1;f<s.length&&r<this.params.minDataSize;f++){const m=s[f][1];m-i<=2*this.params.minDataSize&&(r=Math.max(r,m))}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(),u=new AbortController,d=u.signal,c={url:e,from:i,to:r,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{throw this.params.onError?.({id:"BigRequestParsing",category:R.PARSER,message:"Error parsing response data",thrown:f}),f};return fetch(o,{signal:d}).then(f=>{if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[m,p]=f.body.tee();this.params.onDownloadStream?.(p);const T=m.getReader(),A=parseInt(f.headers.get("Content-Length")??"",10)||r-i+1;c.data=new ArrayBuffer(A);const S=new Uint8Array(c.data),P=async({done:C,value:D})=>{C?this.onBigRequestProgress(c):D&&(S.set(D,c.loaded),c.loaded+=D.byteLength,this.onBigRequestProgress(c),await T?.read().then(P,At.suppressStreamErrors).catch(h))};T?.read().then(P,At.suppressStreamErrors).catch(h)},At.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}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 u of o){const{request:d}=u,[c,h]=Tt(d),f=c>=t&&h<=t+i,m=t>=c&&t+i<h,p=r.slice(c-t,Math.min(h-t+1,i));if((f||m)&&(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(A=>A!==u)),u.success?.(p,"",e);const T=n?Array.from(n.headers.entries()).map(([A,S])=>`${A}: ${S}`).join(`\r
7
+ `):"";this.dashMetrics?.addHttpRequest(d,e,n?.status??200,T,[])}else m&&u.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:R.NETWORK,message:"Download error",thrown:i}),!this.activeRequests.has(e))return;const r=this.dashJsRequestQueue.get(e)??[];for(const n of r){const[o,u]=Tt(n.request);(o>=t&&o<s||u>t&&u<=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]=Tt(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 Ut{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(Ut.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;Ut.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const li=(a,e)=>t=>({create:s=>{const i=a(t).create(s);return new Ut(i,e,s)}}),fi=(a,e)=>{const t=new At(e);return a.extend("SchemeLoaderFactory",function(){const{parent:s}=this,i=s.getLoader;return{getLoader:r=>{const n=i(r);return li(n,t)}}},!0),()=>t.destroy()};var pi=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)},mi=a=>{const e=new g(1/0),t=new I,s=new g(void 0),i=new g(void 0);let r=NaN,n=!1;const o=()=>{r=Date.now(),n=!1},u=c=>{const h=Object.fromEntries(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(p=>p.split(": ")));if("x-playback-duration"in h||"x-playback-duration-millis"in h){const p=parseInt(c.getResponseHeader("X-Playback-Duration")??"",10),A=parseInt(c.getResponseHeader("X-Playback-Duration-Millis")??"",10)??p*1e3??NaN;$(A)&&!isNaN(A)&&e.next(A)}const f=h["x-delivery-type"]??Pt.HTTP1,m={1:!0,0:!1}[h["x-reused"]]??void 0;s.next(f),i.next(m)},d=c=>{c.readyState>=2&&!n&&(n=!0,t.next(Date.now()-r))};return a.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const m=f.onload,p=f.progress;f.onload=function(...T){return u(this),m(...T)},f.progress=function(...T){return d(this),p(...T)},o()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:i,connectionType$:s}},pt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Si=a=>a.extend("RequestModifier",()=>({modifyRequestURL:pt}),!0),gi=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(),u=J(i),d=new ie;return i&&d.add(i.subscribe(c=>{const h=a.getState();s(c,h)&&a.setState(c)},r)),s(o,n)||(t(n),u&&a.setState(n)),d.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},r)),d},ot=(a,e,t)=>Ne(e,()=>a.loop,s=>{$(s)&&(a.loop=s)},{onError:t}),qe=(a,e,t,s)=>Ne(e,()=>({muted:a.muted,volume:a.volume}),i=>{$(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=>{$(i)&&(a.playbackRate=i)},{changed$:t,onError:s}),bi=a=>["__",a.language,a.label].join("|"),yi=(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 I;current$=new g(void 0);error$=new I;video;cueSettings;subscription=new ie;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:R.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=>{$(r)&&this.setExternal(r)},{equal:(r,n)=>$(r)&&$(n)&&r.length===n.length&&r.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(v(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(M(B(e,"addtrack"),B(e,"removetrack"),Ae(["init"])).pipe(v(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),ce((s,i)=>s.length===i.length&&s.every(({id:r},n)=>r===i[n].id))).subscribe(this.available$)),this.subscription.add(M(B(e,"change"),Ae(["init"])).pipe(v(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),v(s=>s&&this.htmlTextTrackToITextTrack(s).id),ce()).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;$(t.align)&&(i.align=t.align),$(t.position)&&(i.position=t.position),$(t.size)&&(i.size=t.size),$(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: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))$(e)&&yi(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 Ge=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 Zt{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}}const Ds=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ns=a=>{const e=Ds(a);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===a)},Ti=a=>{const e=Ds(a);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var Rs=()=>{const{userAgent:a}=window.navigator;return!/chrome/i.test(a)&&/webkit|safari|khtml/i.test(a)};const jt=3;class Ei{_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<jt&&(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||jt))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 _s=(a,e,t=jt)=>{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 u=r-1;u>=0;u--)a.end(u)+t>=s&&(s=a.start(u));for(let u=r+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:s,to:i}};const vi=50,$i=a=>a.webkitAudioDecodedByteCount!==void 0?!!a.webkitAudioDecodedByteCount:a.mozHasAudio!==void 0?a.mozHasAudio:a.audioTracks?!!a.audioTracks.length:!0,ze=a=>{const e=C=>B(a,C).pipe(lt(void 0)),s=M(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(C=>B(a,C))).pipe(v(C=>C.type==="ended"?a.readyState<2:a.readyState<3),ce()),i=M(B(a,"progress"),B(a,"timeupdate")).pipe(v(()=>_s(a.buffered,a.currentTime))),r=Rs()?Be({play:e("play").pipe(pe()),playing:e("playing")}).pipe(lt(void 0)):e("playing"),n=B(a,"playing").pipe(Re(vi),v(()=>$i(a))),o=B(a,"volumechange").pipe(v(()=>({muted:a.muted,volume:a.volume}))),u=B(a,"ratechange").pipe(v(()=>a.playbackRate)),d=B(a,"error").pipe(j(()=>Boolean(a.error||a.played.length)),v(()=>{const C=a.error;return{id:C?`MediaError#${C.code}`:"HtmlVideoError",category:R.VIDEO_PIPELINE,message:C?C.message:"Error event from HTML video element",thrown:a.error??void 0}})),c=B(a,"timeupdate").pipe(v(()=>a.currentTime)),h=new I,f=.3;let m;c.subscribe(C=>{a.loop&&$(m)&&$(C)&&m>=a.duration-f&&C<=f&&h.next(m),m=C});const p=B(a,"enterpictureinpicture"),T=B(a,"leavepictureinpicture"),A=new g(Ti(a));p.subscribe(()=>A.next(!0)),T.subscribe(()=>A.next(!1));const S=new g(ns(a));return B(a,"fullscreenchange").pipe(v(()=>ns(a))).subscribe(S),{playing$:r,pause$:e("pause").pipe(j(()=>!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$:c,durationChange$:B(a,"durationchange").pipe(v(()=>a.duration)),isBuffering$:s,currentBuffer$:i,volumeState$:o,isAudioAvailable$:n,playbackRateState$:u,inPiP$:A,inFullscreen$:S}},es=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let ts=!1,He={};const Ai=a=>{ts=a},ki=()=>{He={}},wi=a=>{a(He)},Ct=(a,e)=>{ts&&(He.meta=He.meta??{},He.meta[a]=e)};class xe{name;constructor(e){this.name=e}next(e){if(!ts)return;He.series=He.series??{};const t=He.series[this.name]??[];t.push([Date.now(),e]),He.series[this.name]=t}}const Pi=new xe("best_bitrate"),Di=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class Ri{last;history={};recordSelection(e){this.history[e.id]=ue()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Dt=(a,{container:e,throughput:t,tuning:s,limits:i,reserve:r=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{const c=s.usePixelRatio?window.devicePixelRatio??1:1,h=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*c*s.containerSizeFactor,height:e.height*c*s.containerSizeFactor},f=h&&nt(h),m=s.considerPlaybackRate&&$(o)?o:1,p=a.filter(H=>!Ot(H.quality)).sort((H,Z)=>Nt(H.quality,Z.quality)?-1:1),T=p.at(-1)?.quality,A=p.at(0)?.quality,S=J(i)||$(i.min)&&$(i.max)&&$t(i.max,i.min)||$(i.min)&&A&&Nt(i.min,A)||$(i.max)&&T&&$t(i.max,T),P=m*Di(n??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),D=p.filter(H=>{const Z=f?$t(H.quality,f):!0,Y=$(t)&&isFinite(t)&&$(H.bitrate)?t-r>=H.bitrate*P:!0,K=s.lazyQualitySwitch&&$(s.minBufferToSwitchUp)&&u&&!Ot(u.quality)&&(n??0)<s.minBufferToSwitchUp&&Nt(H.quality,u.quality),re=S||(J(i.max)||ii(H.quality,i.max))&&(J(i.min)||si(H.quality,i.min));return Z&&Y&&!K&&re})[0];D&&D.bitrate&&Pi.next(D.bitrate);const E=D??p[Math.ceil((p.length-1)/2)]??a[0],L=E&&d&&d.history[E.id]&&ue()-d.history[E.id]<=s.trackCooldown&&(!d.last||E.id!==d.last.id);if(E?.id&&d&&!L&&d.recordSelection(E),L&&d?.last){const H=d.last;return d?.recordSwitch(H),H}return d?.recordSwitch(E),E};var ve=a=>new URL(a).hostname;const _i=300,Vt=(a,e=_i)=>new Gt(t=>{const{width:s,height:i}=a.getBoundingClientRect();if(t.next({width:s,height:i}),!window.ResizeObserver)return;const r=new ResizeObserver(js(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),$(u)&&$(d)&&t.next({width:u,height:d})},e));return r.observe(a),()=>r.disconnect()}),We=a=>{try{a.pause(),a.playbackRate=0,a.removeAttribute("src"),a.load(),a.remove()}catch(e){console.error(e)}},Ii=5e3,Et={};var V;(function(a){a.DOWNLOADING_LIB="downloading_lib",a.STOPPED="stopped",a.STREAM_INITIALIZED="stream_initialized",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(V||(V={}));const fe=(a,e)=>new Gt(t=>{const s=i=>t.next(i);return a.on(e,s),()=>a.off(e,s)});class os{subscription=new ie;videoState=new ne(V.DOWNLOADING_LIB);video;player;params;textTracksManager=new Me;videoTracks=[];frameRatesByFrameHeight={};isLive$=new g(void 0);maxSeekBackTime$=new g(1/0);availableFrom$=new g(void 0);elementSize$=new g(void 0);liveOffset=new Zt;destroyBigRequest;constructor(e){this.video=Ge(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:R.NETWORK,message:`Dash.js failed to load: ${i?.toString?.()}`,thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),Ii);import("dashjs/dist/dash.mediaplayer.min.js").then(i=>{e||(Et.MediaPlayer=i.MediaPlayer,Et.Debug=i.Debug,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){k(Et.MediaPlayer,"dashjs not loaded"),k(Et.Debug,"dashjs not loaded"),this.player=Et.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?es(t.frameRate+""):void 0),!0)),(this.params.format===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=fi(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&&gi(this.player),pi(this.player),this.params.tuning.requestQuick&&Si(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=S=>{e.error$.next({id:"DashIFProvider",category:R.WTF,message:"DashIFProvider internal logic error",thrown:S})},i=(S,P)=>this.subscription.add(S.subscribe(P,s));i(Vt(this.video),this.elementSize$),i(fe(this.player,"error").pipe(v(S=>{const P=typeof S.error=="object"?S.error.code:S.error,C=typeof S.error=="object"?S.error.message:void 0;return{id:`DashJS#${P}`,message:C}})),e.error$),i(fe(this.player,"playbackError").pipe(v(S=>({id:"DashJSPlayback",message:S.error}))),e.error$);const r=fe(this.player,"qualityChangeRendered").pipe(j(({mediaType:S})=>S==="video"),v(({newQuality:S})=>this.videoTracks.find(({bitrateInfo:P})=>P.qualityIndex===S)?.track));r.pipe(j($)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(j(({to:S})=>S===V.STREAM_INITIALIZED),pe()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{const S=this.player.getQualityFor("video");return this.videoTracks.find(({bitrateInfo:P})=>P.qualityIndex===S)?.track?.id},S=>{if(J(S))return;const P=this.videoTracks.find(({track:C})=>C.id===S)?.bitrateInfo;P&&this.player.setQualityFor("video",P.qualityIndex)},{changed$:r.pipe(v(S=>S?.id)),onError:s}))},s)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>this.player.getSettings().streaming?.abr?.autoSwitchBitrate?.video,S=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:S}}}}),{onError:s})),i(fe(this.player,"bufferStateChanged").pipe(j(({mediaType:S})=>S==="video"),v(({state:S})=>S==="bufferStalled")),e.isBuffering$),i(fe(this.player,"fragmentLoadingStarted"),({mediaType:S,request:{url:P}})=>{const C=this.player.getDashMetrics(),D=C.getLatestFragmentRequestHeaderValueByID(S,"X-Reused"),E=C.getLatestFragmentRequestHeaderValueByID(S,"X-Delivery-Type")??Pt.HTTP1,L={1:!0,0:!1}[D]??void 0;this.params.output.httpConnectionType$.next(E),this.params.output.httpConnectionReused$.next(L),e.hostname$.next(ve(P))}),i(fe(this.player,"streamInitialized"),({streamInfo:{duration:S,manifestInfo:{isDynamic:P,availableFrom:C}}})=>{this.isLive$.next(P),this.availableFrom$.next(C.getTime()),P||e.duration$.next(S),this.videoTracks=[];const D=this.player.getQualityFor("video");let E;for(const L of this.player.getBitrateInfoListFor("video")){const H=L.qualityIndex.toString(10),Z=nt(L),Y=L.bitrate/1e3,K={width:L.width,height:L.height},re=this.frameRatesByFrameHeight[L.height];if(Z){const z={id:H,quality:Z,bitrate:Y,size:K,fps:re};this.videoTracks.push({track:z,bitrateInfo:L}),L.qualityIndex===D&&(E=z)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:L})=>L)),E&&e.currentVideoTrack$.next(E),this.videoState.setState(V.STREAM_INITIALIZED),this.videoState.startTransitionTo(V.READY)}),i(fe(this.player,"fragmentLoadingCompleted"),({request:S})=>{if(!S.requestEndDate||!S.firstByteDate||!S.bytesLoaded)return;const P=S.requestEndDate.getTime()-S.firstByteDate.getTime(),C=S.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(C,P)}),i(M(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const S=this.params.dependencies.throughputEstimator.throughput$.getValue(),P=Dt(this.videoTracks.map(({track:D})=>D),{container:this.elementSize$.getValue(),throughput:S,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),C=this.videoTracks.find(({track:D})=>D===P);C?.bitrateInfo&&this.player.setQualityFor("video",C?.bitrateInfo.qualityIndex,!1)}),i(Be({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(j($))}).pipe(j(({isLive:S})=>S),v(({maxSeekBackTime:S})=>-S/1e3)),this.params.output.duration$);const n=fe(this.player,"playbackTimeUpdated").pipe(v(({time:S})=>S??0));i(Be({availableFrom:this.availableFrom$.pipe(j($)),currentTime:n}),({availableFrom:S,currentTime:P})=>this.params.output.liveTime$.next(S+P*1e3)),i(n.pipe(j(()=>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(v(()=>_s(this.video.buffered,this.video.currentTime))),e.currentBuffer$),i(fe(this.player,"playbackPlaying"),()=>{this.videoState.setState(V.PLAYING),w(t.playbackState,l.PLAYING)}),i(fe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(V.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),i(fe(this.player,"playbackPaused"),()=>{this.videoState.setState(V.PAUSED),w(t.playbackState,l.PAUSED)}),i(fe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY)}),i(this.isLive$,e.isLive$),i(Vt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=M(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(0));i(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:c,connectionReused$:h}=mi(this.player);i(c,this.params.output.httpConnectionType$),i(h,this.params.output.httpConnectionReused$),i(u,this.maxSeekBackTime$),i(d.pipe(pe()),e.firstBytesEvent$),i(fe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&i(Be({isLive:this.isLive$,isShort:e.duration$.pipe(v(S=>S<60))}),({isLive:S,isShort:P})=>{const C=!S&&P;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:C}}})}),i(n.pipe(j(S=>S>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(),lt(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(ot(this.video,t.isLooped,s));const{volumeState$:f,looped$:m,playbackRateState$:p,inPiP$:T,inFullscreen$:A}=ze(this.video);this.subscription.add(qe(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(m.subscribe(e.loopedEvent$)),this.subscription.add(tt(this.video,t.playbackRate,p,s)),this.subscription.add(T.subscribe(e.inPiP$)),this.subscription.add(A.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(V.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(V.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=ft(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ht.PLAYBACK_SHIFT);this.player.attachSource(i)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(V.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(V.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===V.DOWNLOADING_LIB||e===V.STREAM_INITIALIZED))switch(s?.to!==l.PAUSED&&i.state===U.Requested&&e!==V.STOPPED&&t!==l.STOPPED&&(r?this.seek(i.position-this.liveOffset.getTotalPausedTime()):this.seek(i.position)),t){case l.STOPPED:{switch(e){case V.STOPPED:break;case V.PLAYING:case V.PAUSED:case V.READY:this.stop();break;default:N(e)}break}case l.READY:{switch(e){case V.STOPPED:this.prepare();break;case V.PLAYING:case V.PAUSED:case V.READY:break;default:N(e)}break}case l.PLAYING:{switch(e){case V.PLAYING:break;case V.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 V.READY:this.play();break;case V.STOPPED:this.prepare();break;default:N(e)}break}case l.PAUSED:{switch(e){case V.PLAYING:this.pause(),this.liveOffset.pause();break;case V.PAUSED:break;case V.READY:this.videoState.setState(V.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED);break;case V.STOPPED:this.prepare();break;default:N(e)}break}default:N(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch{}We(this.video),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Rt=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}};const ds=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var st=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!ds(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(s){return ds(s)&&(a.muted=!1,console.warn(s)),!1}}return!0};function Te(){return ue()}function Is(a){return Te()-a}function us(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,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ci(a,e,t){const s=(...i)=>{t.apply(null,i),a.removeEventListener(e,s)};a.addEventListener(e,s)}function Mt(a,e,t,s){const i=window.XMLHttpRequest;let r,n,o,u=!1,d=0,c,h,f=!1,m="arraybuffer",p=7e3,T=2e3,A=()=>{if(u)return;k(c);const z=Is(c);let le;if(z<T){le=T-z,setTimeout(A,le);return}T*=2,T>p&&(T=p),n&&n.abort(),n=new i,L()};const S=z=>(r=z,re),P=z=>(h=z,re),C=()=>(m="json",re),D=()=>{if(!u){if(--d>=0){A(),s&&s();return}u=!0,h&&h(),t&&t()}},E=z=>(f=z,re),L=()=>{c=Te(),n=new i,n.open("get",a);let z=0,le,Le=0;const Qe=()=>(k(c),Math.max(c,Math.max(le||0,Le||0)));if(r&&n.addEventListener("progress",x=>{const X=Te();r.updateChunk&&x.loaded>z&&(r.updateChunk(Qe(),x.loaded-z),z=x.loaded,le=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>D())),n.addEventListener("load",()=>{if(u)return;k(n);const x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&r){const X=n.response.byteLength-z;X&&r.updateChunk&&r.updateChunk(Qe(),X)}h&&h(),n&&e(n.response)}else D()}),n.addEventListener("error",()=>{D()}),f){const x=()=>{k(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=Te(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=m,n.send(),re},re={withBitrateReporting:S,withParallel:E,withJSONResponse:C,withRetryCount:z=>(d=z,re),withRetryInterval:(z,le)=>($(z)&&(T=z),$(le)&&(p=le),re),withTimeout:z=>(o=z,re),withFinally:P,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,h&&h()}};return re}const Li=100,xi=2e3,Bi=500;let Ni=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-Bi;if(t-e>xi){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 u=r.bytes*n/o;i+=u,r.start=t,r.bytes-=u}}}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>Li&&(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 Mi{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=Te(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},r=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Mt(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=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const 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 Lt=1e4,xt=3,Oi=300,Ui=2e3,Vi=6e4,Fi=10,Hi=1,Yi=500;class qi{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 Ni(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=us(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=us(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||$(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=()=>{Ci(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 Mi(xt,Lt,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,u=null,d=null,c=!1;const h=()=>{const D=r&&(!c||c===this.rep);return D||t("Not running!"),D},f=(D,E,L)=>{u&&u.abort(),u=Mt(this.urlResolver.resolve(D,!1),E,L,()=>this._retryCallback()).withTimeout(Lt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xt).withFinally(()=>{u=null}).send()},m=(D,E,L)=>{k(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(D,!1),E,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},p=D=>{const E=s.playbackRate;s.playbackRate!==D&&(t(`Playback rate switch: ${E}=>${D}`),s.playbackRate=D)},T=D=>{this.lowLatency=D,t(`lowLatency changed to ${D}`),A()},A=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)p(1);else{let D=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}const L=Te()-1e4;let H=0;for(let Y=0;Y<this.bufferStates.length;Y++){const K=this.bufferStates[Y];D=Math.min(D,K.buf),K.ts<L&&H++}this.bufferStates.splice(0,H),t(`update playback rate; minBuffer=${D} drop=${H} jitter=${this.sourceJitter}`);let Z=D-Hi;this.sourceJitter>=0?Z-=this.sourceJitter/2:this.sourceJitter-=1,Z>3?p(1.15):Z>1?p(1.1):Z>.3?p(1.05):p(1)}},S=D=>{let E;const L=()=>E&&E.start?E.start.length:0,H=x=>E.start[x]/1e3,Z=x=>E.dur[x]/1e3,Y=x=>E.fragIndex+x,K=(x,X)=>({chunkIdx:Y(x),startTS:H(x),dur:Z(x),discontinuity:X}),re=()=>{let x=0;if(E&&E.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=E.dur.length-1;for(;Ee>=0&&(me-=E.dur[Ee],!(me<=0));--Ee);x=Math.min(Ee,E.dur.length-1-he),x=Math.max(x,0)}return K(x,!0)},z=x=>{const X=L();if(!(X<=0)){if($(x)){for(let he=0;he<X;he++)if(H(he)>x)return K(he)}return re()}},le=x=>{const X=L(),he=x?x.chunkIdx+1:0,me=he-E.fragIndex;if(!(X<=0)){if(!x||me<0||me-X>Fi)return t(`Resync: offset=${me} bChunks=${X} chunk=`+JSON.stringify(x)),re();if(!(me>=X))return K(he-E.fragIndex,!1)}},Le=(x,X,he)=>{d&&d.abort(),d=Mt(this.urlResolver.resolve(x,!0,this.lowLatency),X,he,()=>this._retryCallback()).withTimeout(Lt).withRetryCount(xt).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,X)=>{Le(D,he=>{if(!h())return;E=he;const me=Boolean(E.lowLatency);me!==this.lowLatency&&T(me);let Ee=0;for(let Je=0;Je<E.dur.length;++Je)Ee+=E.dur[Je];Ee>0&&(k(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,x(z(X))},()=>this._handleNetworkError())},nextChunk:le}},P=()=>{r=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),k(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:D=>{const{videoElement:E,logger:L}=this.params;let H=S(e.jidxUrl),Z,Y,K,re,z=0,le,Le,Qe;const x=()=>{le&&(clearTimeout(le),le=void 0);const q=Math.max(Yi,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=z+q,Se=Te(),ye=Math.min(1e4,be-Se);z=Se;const Oe=()=>{d||h()&&H.seek(()=>{h()&&(z=Te(),X(),x())})};ye>0?le=window.setTimeout(()=>{this.paused?x():Oe()},ye):Oe()},X=()=>{let q;for(;q=H.nextChunk(re);)re=q,St(q);const be=H.nextChunk(K);if(be){if(K&&be.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?x():(P(),this._initPlayerWith(e));return}Je(be)}else x()},he=(q,be)=>{if(!h()||!this.sourceBuffer)return;let Se,ye,Oe;const Ue=_e=>{window.setTimeout(()=>{h()&&he(q,be)},_e)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Ue(100);else{const _e=Te(),je=E.currentTime;!this.paused&&E.buffered.length>1&&Le===je&&_e-Qe>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),Le!==je&&(Le=je,Qe=_e);const Ke=this._getBufferSizeSec();if(Ke>30)L(`Buffered ${Ke} seconds; delaying appendBuffer`),Ue(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:_e,buf:Ke}),A(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(Xe){if(Xe.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Oe=this.sourceBuffer.buffered.length,Oe!==0&&(Se=this.sourceBuffer.buffered.start(0),ye=je,ye-Se>4&&this.sourceBuffer.remove(Se,ye-3)),Ue(1e3);else throw Xe}}},me=()=>{Y&&Z&&(L([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(K)]),he(Y,function(){Y=null,X()}))},Ee=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),Je=q=>{h()&&m(Ee(q),(be,Se)=>{if(h()){if(Se/=1e3,Y=be,K=q,n=q.startTS,Se){const ye=Math.min(10,q.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ye:ye}me()}},()=>this._handleNetworkError())},St=q=>{h()&&(k(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(q),!1)))},It=q=>{h()&&(e.cachedHeader=q,he(q,()=>{Z=!0,me()}))};r=!0,H.seek(q=>{if(h()){if(z=Te(),!q){x();return}re=q,!J(D)||q.startTS>D?Je(q):(K=q,X())}},D),e.cachedHeader?It(e.cachedHeader):f(e.headerUrl,It,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),$(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 $(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,m,p;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(m=this._getBufferSizeSec(),p=h/this.bitrate,m>10&&p>.8||m>15&&p>.5||m>20&&p>.3)){e(`Not switching: buffer=${Math.floor(m)}; 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,m)=>{const p=Te();if(this.chunkRateEstimator.addInterval(f,p,m)){const A=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:p-f,speed:A}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let h=r.get();if(h&&o&&this.autoQuality){if(u&&h>o&&Is(n)<3e4)return;s(h)}u=this.autoQuality};return{updateChunk:(h,f)=>{const m=r.updateChunk(h,f);return m&&d(),m},notifySwitch:h=>{const f=Te();h<o&&(n=f),o=h}}}_fetchManifest(e,t,s){this.manifestRequest=Mt(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Lt).withRetryCount(xt).withRetryInterval(Oi,Ui).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((u,d)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.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))},Vi))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var F;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(F||(F={}));const Gi=[F.PAUSED,F.PLAYING,F.READY],zi=[F.PAUSED,F.PLAYING,F.READY];class Wi{subscription=new ie;video;videoState=new ne(F.STOPPED);dash;representations$=new g([]);textTracksManager=new Me;maxSeekBackTime$=new g(1/0);zeroTime$=new g(void 0);liveOffset=new Zt;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:R.WTF,message:"DashLiveProvider internal logic error",thrown:i})};M(this.videoState.stateChangeStarted$.pipe(v(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(i)}`})}),this.video=Ge(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=ze(this.video);this.subscription.add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===F.READY&&this.videoState.setState(F.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===U.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(F.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ce(),v(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Be({zeroTime:this.zeroTime$.pipe(j($)),position:s.timeUpdate$}).subscribe(({zeroTime:i,position:r})=>this.params.output.liveTime$.next(i+r*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(qe(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(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:i}})=>{const r=i&&ni(i);this.dash.setMaxAutoQuality(r)})).add(this.videoState.stateChangeEnded$.subscribe(i=>{switch(i.to){case F.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(l.STOPPED);break;case F.MANIFEST_READY:case F.READY:this.params.desiredState.playbackState.getTransition()?.to===l.READY&&this.params.desiredState.playbackState.setState(l.READY);break;case F.PAUSED:this.params.desiredState.playbackState.setState(l.PAUSED);break;case F.PLAYING:this.params.desiredState.playbackState.setState(l.PLAYING);break;default:return N(i.to)}},t)).add(M(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),We(this.video)}createLiveDashPlayer(){const e=new qi({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&&$(t)?t:Dt(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(ft(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:R.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=Rt(i.name)??nt(i.video),o=i.bitrate/1e3,u={...i.video};if(!n)continue;const d={id:r,quality:n,bitrate:o,size:u};s.push({track:d,representation:i})}this.representations$.next(s),this.params.output.availableVideoTracks$.next(s.map(({track:i})=>i)),this.videoState.getTransition()?.to===F.MANIFEST_READY&&this.videoState.setState(F.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),$(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!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(F.STOPPED));return}if(!t){if(zi.includes(e)){const n=this.params.desiredState.videoTrack.getTransition()?.to;$(n)&&this.setVideoTrack(n);const o=this.params.desiredState.autoVideoTrackSwitching.getTransition();o&&this.setAutoQuality(o.to)}if(i?.to!==l.PAUSED&&r.state===U.Requested&&Gi.includes(e)){this.seek(r.position-this.liveOffset.getTotalPausedTime());return}switch(e){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_READY),this.dash.attachSource(ft(this.params.source.url));return;case F.MANIFEST_READY:this.videoState.startTransitionTo(F.READY),this.prepare();break;case F.READY:if(s===l.PAUSED)this.videoState.setState(F.PAUSED);else if(s===l.PLAYING){this.videoState.startTransitionTo(F.PLAYING);const n=i?.from;n&&n===l.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(F.PAUSED)})}return;case F.PLAYING:s===l.PAUSED&&(this.videoState.startTransitionTo(F.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case F.PAUSED:s===l.PLAYING&&(this.videoState.startTransitionTo(F.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(F.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return N(e)}}}}var Cs=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),s=e===null?Pt.HTTP1:e??void 0,i=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:s,reused:i}},rt=(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 Qi=a=>{const e=document.createElement("a");return e.href=a,e.origin},Ji=a=>{const e=document.createElement("a");return e.href=a,e.host};class Ls{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],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(Ji(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 Ft{_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 u=0;const d=Date.now();let c=0,h=0,f=0;const m=T=>{i(Ft._str2ua(T.substr(u))),u=T.length};let p=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(p=pt(p)),this._lastXhr=new Ls(p,e.failoverHosts,T=>{this._lastXhr=void 0,m(T);const A=Date.now()-d;this._params.onBandwidthChange({size:T.length,duration:A,speed:8*T.length/(A/1e3)}),this._onDashCallback("loading",{size:T.length,done:!0}),r?.()},T=>{if(T.length-u>o&&m(T),h===0){h=Date.now();return}f=T.length-c;const A=Date.now()-h;f>=100*1024&&A>=1e3&&(this._params.onBandwidthChange({size:f,duration:A,speed:8*f/(A/1e3)}),f=0,c=T.length,h=Date.now()),this._onDashCallback("loading",{size:T.length,done:!1})},n,(T,A,S)=>this._params.onError(T,A,S))})}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=Ft._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 ji{_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,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},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=pt(s)),new Ls(s,t,i=>{this.attachManifest(i,t,Qi(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,c)=>{const h=d.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(n(r,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(r.getElementsByTagName("Representation"),d=>{const c=d.getElementsByTagName("SegmentBase")[0],h=c&&n(c,"indexRange").split("-"),f=c&&c.getElementsByTagName("Initialization")[0],m=f&&n(f,"range").split("-");if(!m||!h){const C=d.parentElement;if(C?.getAttribute("contentType")==="text"){const D=d.getAttribute("id")??void 0,E=(s?s+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,L=C.getAttribute("lang")??void 0;E&&u.push({id:D,url:E,language:L})}return}const p=.1,T=Number(d.attributes.getNamedItem("bandwidth")?.value),A=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let S;const P=d.attributes.getNamedItem("frameRate")?.value??void 0;S=P?es(P):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:T,baseURL:A,failoverHosts:t,indexFrom:Number(h[0]),indexTo:Number(h[1]),initFrom:Number(m[0]),initTo:Number(m[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:S,bufferSize:p*T/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}u.forEach(({id:d,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),d&&f.setAttribute("id",d),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((d,c)=>c.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 u=n.getUint32(r,!1),d=n.getUint32(r+4,!1)+(e.indexTo+1);r+=8;const c=n.getUint16(r+2,!1);r+=4,e.refs=[];for(let f=0;f<c;f+=1){const m=d+(n.getUint32(r,!1)&2147483647),p=u+n.getUint32(r+4,!1);r+=12,e.refs.push({fromTime:u/o,toTime:p/o,fromOffset:d,toOffset:m-1}),d=m,u=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 m=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),m)}const c=this._appendVector[String(d.fromTime)];c!==i&&(i=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(d.toTime)){const m=this._buffer.getByTime(this._video.currentTime);if(!m){this._onDashCallback("buffering");return}h=m.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),r!==m.to&&(r=m.to,window.setTimeout(()=>{try{const p=this._buffer.getNextWithGap(m);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)},u=()=>{if(!this._stream)try{const d=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ft({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",u),s.removeEventListener("webkitsourceopen",u)};s.addEventListener("sourceopen",u,!1),s.addEventListener("webkitsourceopen",u,!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),u=i||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?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,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(i.fromTime-r,i.toTime+r,(o,u)=>this._stream.remove(o,u)),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||J(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){const t=this._currentRepresentation?.refs;if(!t)return;if(Array.isArray(t)&&t.length===0){this._params.onError("emptyrefs","Empty refs");return}let 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 Ki=[G.PAUSED,G.PLAYING];class Xi{videoState=new ne(G.STOPPED);subscription=new ie;video;buffer;dash;representations$=new g([]);currentRepresentation$=new g(void 0);params;textTracksManager=new Me;elementSize$=new g(void 0);dashLiteEvents={idxRequestPing$:new I,responseHeaders$:new I,manifestReady$:new I,representationPlay$:new I,error$:new I};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),M(this.videoState.stateChangeStarted$.pipe(v(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=Ge(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 Ei(this.video),this.dash=new ji({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:R.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"DashProvider",category:R.WTF,message:"DashProvider internal logic error",thrown:o})},i=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},r=ze(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,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$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(r.seeking$.subscribe(()=>{J(this.params.desiredState.seekState.getState().state!==U.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(ot(this.video,t.isLooped,s)),this.subscription.add(qe(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(Vt(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(v(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:R.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(M(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,B(this.video,"progress")).pipe(v(()=>{const o=this.currentRepresentation$.getValue(),u=this.representations$.getValue(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),c=this.params.desiredState.videoTrack.getState(),h=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),m=i();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let p;if(!m&&$(c))p=c;else{const T=rt(this.video.buffered,this.video.currentTime*1e3),A=m?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,S=Math.min(T/A,1);p=Dt(u.map(({track:P})=>P),{container:f,throughput:h,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:S,playbackRate:this.video.playbackRate,current:u.find(({representation:P})=>P===o)?.track})?.id}return $(p)?u.find(({track:T})=>T.id===p)?.representation:void 0}),ce()).subscribe(this.currentRepresentation$,s)).add(Be({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(j(o=>o.to===G.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(j($))}).pipe(pe()).subscribe(()=>this.videoState.setState(G.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(j($),ce((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&i()?o.height<=u.height:o===u)).subscribe(o=>{const u=rt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(u/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:u,reused:d}=Cs(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(pe(),lt(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(j($)).subscribe(this.handleRepresentationPlay,s)).add(M(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),We(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return N(e)}}handleManifestReady=e=>{const t=[];for(const s of e){const i=s.name??s.id??s.height.toString(10),r=(s.name&&Rt(s.name))??nt(s),n=s.bandwidth/1e3,o={width:s.width,height:s.height},u=s.fps;if(!r)continue;const d={id:i,quality:r,bitrate:n,size:o,fps:u};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))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(G.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0));return}if(!t)switch(i?.to!==l.PAUSED&&r.state===U.Requested&&Ki.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 N(e)}}}var Pe;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Pe||(Pe={}));var Ht;(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"})(Ht||(Ht={}));var De;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(De||(De={}));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 mt;(function(a){a.MP4="mp4",a.WEBM="webm"})(mt||(mt={}));var Kt=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};let xs=!1;try{xs=Rs()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Zi{bufferFull$=new I;error$=new I;buffer;queue=[];currentTask=null;destroyed=!1;constructor(e){this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(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);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;const{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(i){i instanceof DOMException&&i.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):i instanceof DOMException&&i.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:R.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:N(t)}}}var cs=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};const Bs=new TextDecoder("ascii"),Ns=a=>{let e=0,t=a.getUint32(e);e+=4;const s=new DataView(a.buffer,a.byteOffset+e,4),i=Bs.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}},ea=a=>Bs.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ta=(a,e,t)=>{const s=Ns(a),i=[];let r=0;const n=()=>{const T=s.contents.getUint32(r);return r+=4,T};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),c=n(),h=n(),f=n()&4294967295;let m=c/d*1e3,p=(t?t.to+1:a.byteOffset+a.byteLength)+h;for(let T=0;T<f;T++){const A=n(),S=A>>>31,P=A<<1>>>1,C=n();if(n(),S!==0)throw new Error("Unsupported multilevel sidx");const D=C/d*1e3;i.push({status:Q.NONE,time:{from:m,to:m+D},byte:{from:p,to:p+P-1}}),m+=D,p+=P}return i},sa=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=Ns(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},ia={validateData:ea,parseInit:()=>null,getIndexRange:()=>{},parseSegments:ta,parseFeedableSegmentChunk:sa};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.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 _;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(_||(_={}));const hs={[y.EBML]:{type:_.Master},[y.EBMLVersion]:{type:_.UnsignedInteger},[y.EBMLReadVersion]:{type:_.UnsignedInteger},[y.EBMLMaxIDLength]:{type:_.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[y.DocType]:{type:_.String},[y.DocTypeVersion]:{type:_.UnsignedInteger},[y.DocTypeReadVersion]:{type:_.UnsignedInteger},[y.Void]:{type:_.Binary},[y.Segment]:{type:_.Master},[y.SeekHead]:{type:_.Master},[y.Seek]:{type:_.Master},[y.SeekID]:{type:_.Binary},[y.SeekPosition]:{type:_.UnsignedInteger},[y.Info]:{type:_.Master},[y.TimestampScale]:{type:_.UnsignedInteger},[y.Duration]:{type:_.Float},[y.Tracks]:{type:_.Master},[y.Chapters]:{type:_.Master},[y.Cluster]:{type:_.Master},[y.Timestamp]:{type:_.UnsignedInteger},[y.SilentTracks]:{type:_.Master},[y.SilentTrackNumber]:{type:_.UnsignedInteger},[y.Position]:{type:_.UnsignedInteger},[y.PrevSize]:{type:_.UnsignedInteger},[y.SimpleBlock]:{type:_.Binary},[y.BlockGroup]:{type:_.Master},[y.EncryptedBlock]:{type:_.Binary},[y.Attachments]:{type:_.Master},[y.Tags]:{type:_.Master},[y.Cues]:{type:_.Master},[y.CuePoint]:{type:_.Master},[y.CueTime]:{type:_.UnsignedInteger},[y.CueTrackPositions]:{type:_.Master},[y.CueTrack]:{type:_.UnsignedInteger},[y.CueClusterPosition]:{type:_.UnsignedInteger},[y.CueRelativePosition]:{type:_.UnsignedInteger},[y.CueDuration]:{type:_.UnsignedInteger},[y.CueBlockNumber]:{type:_.UnsignedInteger},[y.CueCodecState]:{type:_.UnsignedInteger},[y.CueReference]:{type:_.Master},[y.CueRefTime]:{type:_.UnsignedInteger}},Ms=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Yt(a,t),i=s in hs,r=i?hs[s].type:_.Binary,n=a.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(a.buffer,a.byteOffset+t+1,o-1),d=n&255>>o,c=Yt(u),h=d*2**((o-1)*8)+c,f=t+o;let m;return f+h>a.byteLength?m=new DataView(a.buffer,a.byteOffset+f):m=new DataView(a.buffer,a.byteOffset+f,h),{tag:i?s:"0x"+s.toString(16).toUpperCase(),type:r,tagHeaderSize:f,tagSize:f+h,value:m,valueSize:h}},Yt=(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},Ye=(a,e)=>{switch(e){case _.SignedInteger:return a.getInt8(0);case _.UnsignedInteger:return Yt(a);case _.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(a);case _.UTF8:return new TextDecoder("utf-8").decode(a);case _.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case _.Master:return a;case _.Binary:return a;default:N(e)}},_t=(a,e)=>{let t=0;for(;t<a.byteLength;){const s=new DataView(a.buffer,a.byteOffset+t),i=Ms(s);if(!e(i))return;i.type===_.Master&&_t(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},aa=a=>{if(a.getUint32(0)!==y.EBML)return!1;let e,t,s;const i=Ms(a);return _t(i.value,({tag:r,type:n,value:o})=>(r===y.EBMLReadVersion?e=Ye(o,n):r===y.DocType?t=Ye(o,n):r===y.DocTypeReadVersion&&(s=Ye(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Os=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],ra=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],na=a=>{let e,t,s,i,r=!1,n=!1,o=!1,u,d;return _t(a,({tag:c,type:h,value:f,valueSize:m})=>{if(c===y.SeekID){const p=Ye(f,h);d=Yt(p)}else c!==y.SeekPosition&&(d=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+m):c===y.Info?r=!0:c===y.SeekHead?n=!0:c===y.TimestampScale?s=Ye(f,h):c===y.Duration?i=Ye(f,h):c===y.SeekPosition&&d===y.Cues?u=Ye(f,h):r&&n&&Os.includes(c)&&(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:u}},oa=a=>{if(J(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},da=(a,e)=>{let t=!1,s=!1;const i=o=>$(o.time)&&$(o.position),r=[];let n;return _t(a,({tag:o,type:u,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=Ye(d,u));break;case y.CueTrackPositions:break;case y.CueClusterPosition:n&&(n.position=Ye(d,u));break;default:t&&Os.includes(o)&&(s=!0)}return!(t&&s)}),n&&i(n)&&r.push(n),r.map((o,u)=>{const{time:d,position:c}=o,h=r[u+1];return{status:Q.NONE,time:{from:d,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},ua=a=>{let e=0,t=!1;try{_t(a,s=>s.tag===y.Cluster?s.tagSize<=a.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):ra.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},ca={validateData:aa,parseInit:na,getIndexRange:oa,parseSegments:da,parseFeedableSegmentChunk:ua};class ls{onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);error$=new I;gaps=[];subscription=new ie;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new AbortController;destroyAbortController=new AbortController;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;constructor(e,t,s,i,{fetcher:r,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.fetcher=r,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case mt.MP4:this.containerParser=ia;break;case mt.WEBM:this.containerParser=ca;break;default:N(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=Ie(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 Zi(this.sourceBuffer),this.subscription.add(B(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(B(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;const o=Math.min(this.bufferLimit,cs(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;$(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=Ie(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(J(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();$(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 AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(J(e)||J(this.downloadingRepresentationId)||J(this.playingRepresentationId)||J(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 c=rt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&c>=i.time.to-e+100&&(r=h)}if(isFinite(this.bufferLimit)&&cs(this.sourceBuffer.buffered)>=this.bufferLimit){const d=rt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c);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 c=o.at(0);c&&c.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&&rt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=s.at(-1);u&&u.status===Q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(i===u))}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(){if(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();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const i=e.findIndex(({status:h,time:{from:f,to:m}},p)=>{const T=f<=s&&m>=s,A=f>s||T||p===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&f<=s+S||m<=s+S;return(h===Q.NONE||h===Q.PARTIALLY_EJECTED&&A&&P&&this.sourceBuffer&&!Kt(this.sourceBuffer.buffered,s))&&A&&P});if(i===-1)return[];if(t!==De.BYTE_RANGE)return e.slice(i,i+1);const r=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=i;h<r.length&&(n<=d||o<=c);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)u.push(f);else break}return u}async loadSegments(e,t,s="auto"){if(!e.length)return;let i,r,n=e;const{type:o}=t.segmentReference;switch(o){case De.BYTE_RANGE:{i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case De.TEMPLATE:{const d=e.at(0);i=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:N(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:u}=this.downloadAbortController;if(this.failedDownloads&&(await Ie(u,async function*(){const d=as(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),u.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,c)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,r?r.from:0,c,u)}catch(h){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:u,priority:s}).then(()=>this.failedDownloads=0,d=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(d)})}onSegmentDownloadError(e){let t=!1;const s=this.getCurrentPosition();this.sourceBuffer&&$(s)&&(t=rt(this.sourceBuffer?.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:R.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 m of this.segments.get(f.id)??[])m.status===Q.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=Q.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,m=d===De.BYTE_RANGE,p=m?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!m||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(r.aborted){n();continue}const A=m?f.byte.from-s:0,S=m?f.byte.to-s:e.byteLength,P=A<i,C=S<=i;if(f.status===Q.DOWNLOADING&&P&&C){f.status=Q.DOWNLOADED,this.activeSegments.delete(h);const D=new DataView(e.buffer,e.byteOffset+A,p);this.sourceBufferTaskQueue.append(D,r).then(E=>E&&!r.aborted?o(h):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&P&&(h.loadedBytes=Math.min(p,i-A),h.loadedBytes>h.feedingBytes)){const D=new DataView(e.buffer,e.byteOffset+A+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===p?D:this.containerParser.parseFeedableSegmentChunk(D);E?.byteLength&&(f.status=Q.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,r).then(L=>{if(r.aborted)n();else if(L)h.fedBytes+=E.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=requestIdleCallback(()=>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?Ie(this.destroyAbortController.signal,async function*(){const o=as(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,i)).then(o=>{if(!o)return;const{dataView:u,segments:d}=o,c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||J(e)||this.sourceBuffer.updating)return!1;let i=0,r=1/0,n=-1/0,o=!1;const u=d=>{r=Math.min(r,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?d.size??0:d.byte.to-d.byte.from;i+=c};for(const d of this.segments.values())for(const c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;c.status===Q.FED&&u(c)}if(o=isFinite(r)&&isFinite(n),!o){i=0,r=1/0,n=-1/0;for(const d of this.segments.values())for(const c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;c.status===Q.FED&&u(c)}}if(o=isFinite(r)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const c=this.sourceBuffer.buffered.start(d)*1e3,h=this.sourceBuffer.buffered.end(d)*1e3;for(const f of this.segments.values())for(const m of f)if(m.status===Q.NONE&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.time.to)>=Math.round(h)){r=c,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 c of this.segments.values())for(const h of c)h.time.from>e+d&&h.status===Q.FED&&u(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=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(J(this.sourceBuffer)||J(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),u=e.some(c=>c.from-t<=n&&c.to+t>=o),d=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d.length===1?i.status=Q.PARTIALLY_EJECTED:i.status=Q.NONE)}}}var ct;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(ct||(ct={}));class ha{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new AbortController;subscription=new ie;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}=Cs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=Ie(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=pt(t));const s=yield fetch(t,{signal:this.abortAllController.signal}).catch(vt);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=Ie(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?ct.HEADER:ct.PARAM,range:s,onProgress:i,priority:r="auto",signal:n,measureThroughput:o=!0}={}){let u=e;const d=new Headers;if(s)switch(t){case ct.HEADER:{d.append("Range",`bytes=${s.from}-${s.to}`);break}case ct.PARAM:{const Y=new URL(u,location.href);Y.searchParams.append("bytes",`${s.from}-${s.to}`),u=Y.toString();break}default:N(t)}this.requestQuic&&(u=pt(u));let c=this.abortAllController.signal;if(n){const Y=new AbortController;if(this.subscription.add(M(B(this.abortAllController.signal,"abort"),B(n,"abort")).subscribe(()=>{try{Y.abort()}catch(K){vt(K)}})),this.abortAllController.signal.aborted||n.aborted)try{Y.abort()}catch(K){vt(K)}c=Y.signal}const h=ue(),f=yield fetch(u,{priority:r,headers:d,signal:c}).catch(vt),m=ue();if(this.throughputEstimator?.addRawRtt(m-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 Y=yield f.arrayBuffer();return this.throughputEstimator?.addRawSpeed(Y.byteLength,ue()-m),i?.(new DataView(Y),Y.byteLength),Y}if(!i&&!o)return f.arrayBuffer();const[T,A]=f.body.tee(),S=T.getReader();o&&this.throughputEstimator?.trackStream(A);let P=0;const C=new ArrayBuffer(p),D=new Uint8Array(C),E=new DataView(C);let L=!1;const H=Y=>{L=!0,vt(Y)},Z=Ie(c,async function*({done:Y,value:K}){P===0&&this.lastRequestFirstBytes$.next(ue()-h),!c.aborted&&(Y?i?.(E,P):K&&(D.set(K,P),P+=K.byteLength,i?.(E,P),yield S?.read().then(Z,H)))}.bind(this));return yield S?.read().then(Z,H),L?null:C}.bind(this));async fetchRepresentation(e,t,s="auto"){const{type:i}=e;switch(i){case De.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case De.TEMPLATE:return await this.fetchTemplateRepresentation(e,s)??null;default:N(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=Ie(this.abortAllController.signal,async function*(e,t,s){if(e.type!==De.BYTE_RANGE)return null;const{from:i,to:r}=e.initRange;let n=i,o=r,u=!1,d,c;e.indexRange&&(d=e.indexRange.from,c=e.indexRange.to,u=r+1===d,u&&(n=Math.min(d,i),o=Math.max(c,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 m=t.parseInit(f),p=e.indexRange??t.getIndexRange(m);if(!p)throw new ReferenceError("No way to load representation index");let T;if(u)T=new DataView(h,p.from-n,p.to-p.from+1);else{const S=yield this.fetch(e.url,{range:p,priority:s,measureThroughput:!1});if(!S)return null;T=new DataView(S)}const A=t.parseSegments(T,m,p);return{dataView:new DataView(h),segments:A}}.bind(this));fetchTemplateRepresentation=Ie(this.abortAllController.signal,async function*(e,t){if(e.type!==De.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 vt=a=>{if(!(a instanceof DOMException)||!(a.name==="AbortError"||a.code===20))throw a},fs=a=>{if(!a.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*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},Qt=(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,u)=>J(r)?o:J(u)?r:r.padStart(parseInt(u,10),"0"))}return t},la=(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 u;const d=r.getAttribute("mediaPresentationDuration"),c=n.getAttribute("duration");if(d)u=fs(d);else if(c){const p=fs(c);$(p)&&(u=p)}let h=0;const f=r.getAttribute("profiles")?.split(",")??[],m=f.includes(Ht.WEBM_AS_IN_FFMPEG)||f.includes(Ht.WEBM_AS_IN_SPEC)?mt.WEBM:mt.MP4;for(const p of o){const T=p.getAttribute("mimeType"),A=p.getAttribute("codecs"),S=p.getAttribute("contentType")??T?.split("/")[0],P=p.getAttribute("profiles")?.split(",")??[],C=p.querySelectorAll("Representation"),D=p.querySelector("SegmentTemplate");if(S!=="text")for(const E of C){const L=E.getAttribute("mimeType")??T,H=E.getAttribute("codecs")??A??"",Z=E.getAttribute("contentType")??L?.split("/")[0]??S,Y=p.getAttribute("profiles")?.split(",")??[],K=parseInt(E.getAttribute("width")??"",10),re=parseInt(E.getAttribute("height")??"",10),z=parseInt(E.getAttribute("bandwidth")??"",10)/1e3,le=E.getAttribute("frameRate")??"",Le=E.getAttribute("quality")??void 0,Qe=le?es(le):void 0,x=E.getAttribute("id")??(h++).toString(10),X=Z==="video"?`${re}p`:Z==="audio"?`${z}Kbps`:H,he=`${x}@${X}`,me=E.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(me,e).toString(),Je=[...f,...P,...Y];let St;const It=E.querySelector("SegmentBase"),q=E.querySelector("SegmentTemplate")??D;if(It){const Se=E.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ye,Oe]=Se.split("-").map(it=>parseInt(it,10)),Ue={from:ye,to:Oe},_e=E.querySelector("SegmentBase")?.getAttribute("indexRange"),[je,Ke]=_e?_e.split("-").map(it=>parseInt(it,10)):[],Xe=_e?{from:je,to:Ke}:void 0;St={type:De.BYTE_RANGE,url:Ee,initRange:Ue,indexRange:Xe}}else if(q){const Se={representationId:E.getAttribute("id")??void 0,bandwidth:E.getAttribute("bandwidth")??void 0},ye=parseInt(q.getAttribute("timescale")??"",10),Oe=q.getAttribute("initialization")??"",Ue=q.getAttribute("media"),_e=parseInt(q.getAttribute("startNumber")??"",10)??1,je=Qt(Oe,Se);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Ke=q.querySelectorAll("SegmentTimeline S")??[],Xe=[];if(Ke.length){let it=_e,at=0;for(const gt of Ke){const dt=parseInt(gt.getAttribute("d")??"",10)*1e3,bt=parseInt(gt.getAttribute("r")??"",10)||0,yt=parseInt(gt.getAttribute("t")??"",10)??void 0;for(let ss=0;ss<bt+1;ss++){const Ys=Qt(Ue,{...Se,segmentNumber:it.toString(10),segmentTime:yt.toString(10)}),qs=yt?yt/ye:at;at+=dt/ye;const Gs=at;it++,Xe.push({time:{from:qs,to:Gs},url:Ys})}}}else if($(u)){const at=parseInt(q.getAttribute("duration")??"",10)/ye*1e3,gt=Math.ceil(u/at);let dt=0;for(let bt=1;bt<gt;bt++){const yt=Qt(Ue,{...Se,segmentNumber:bt.toString(10),segmentTime:dt.toString(10)});Xe.push({time:{from:dt,to:dt+at},url:yt}),dt+=at}}St={type:De.TEMPLATE,baseUrl:Ee,initUrl:je,segments:Xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Z||!L)continue;const be={video:Pe.VIDEO,audio:Pe.AUDIO,text:Pe.TEXT}[Z];be&&i[be].push({id:he,kind:be,segmentReference:St,profiles:Je,duration:u,bitrate:z,mime:L,codecs:H,width:K,height:re,fps:Qe,quality:Le})}}return{duration:u,container:m,representations:i}},fa=["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 pa=class{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new ie;fetcher;state$=new ne(we.NONE);currentVideoRepresentation$=new g(void 0);error$=new I;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);forceEnded$=new I;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new AbortController;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ha({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=Ie(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:R.NETWORK,message:"Failed to load manifest",thrown:n}));if(!s)return;let i;try{i=la(s??"",t)}catch(n){this.error$.next({id:"ManifestParsing",category:R.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:R.PARSER,message:"No playable video representations"})}.bind(this));initRepresentations=Ie(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 ls(Pe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],$(t)&&(this.audioBufferManager=new ls(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=M(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(v(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),r=M(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(v(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.subscription.add(M(this.forceEnded$,Be({allBuffersFull:i,someBufferEnded:r}).pipe(j(({allBuffersFull:n,someBufferEnded:o})=>n&&o))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))try{this.source?.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.subscription.add(M(...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))),$(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&$(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(M(...fa.map(e=>B(this.element,e)),B(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.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&&Kt(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),Kt(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?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ws(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),t=>{this.error$.next({id:"GapWatchdog",category:R.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 ma=({id:a,width:e,height:t,bitrate:s,fps:i,quality:r})=>{const n=(r?Rt(r):void 0)??nt({width:e,height:t});return n&&{id:a,quality:n,bitrate:s,size:{width:e,height:t},fps:i}},Sa=({id:a,bitrate:e})=>({id:a,bitrate:e}),ga=(a,e,t)=>{const s=e.indexOf(t);return a.at(Math.round(a.length*s/e.length))??a.at(-1)};class ba{subscription=new ie;videoState=new ne(oe.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new Me;videoTracks=[];audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Ri;constructor(e){this.params=e,this.video=Ge(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 pa({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=ze(this.video),i=d=>{e.error$.next({id:"DashVKProvider",category:R.WTF,message:"DashVKProvider internal logic error",thrown:d})},r=(d,c)=>this.subscription.add(d.subscribe(c,i));r(s.timeUpdate$,e.position$),r(s.durationChange$,e.duration$),r(s.ended$,e.endedEvent$),r(s.looped$,e.loopedEvent$),r(s.error$,e.error$),r(s.isBuffering$,e.isBuffering$),r(s.currentBuffer$,e.currentBuffer$),r(s.playing$,e.firstFrameEvent$),r(s.canplay$,e.canplay$),r(s.isAudioAvailable$,e.isAudioAvailable$),r(s.inPiP$,e.inPiP$),r(s.inFullscreen$,e.inFullscreen$),r(this.player.error$,e.error$),r(this.player.lastConnectionType$,e.httpConnectionType$),r(this.player.lastConnectionReused$,e.httpConnectionReused$),r(this.player.lastRequestFirstBytes$.pipe(j($),pe()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(qe(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(Vt(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 c=this.player.getRepresentations();k(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((p,T)=>T.bitrate-p.bitrate),f=Array.from(c.video).sort((p,T)=>T.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const T=Sa(p);T&&this.audioTracks.push({track:T,representation:p})}for(const p of f){const T=ma(p);if(T){this.videoTracks.push({track:T,representation:p});const A=!this.params.tuning.isAudioDisabled&&ga(h,f,p);A&&this.audioRepresentations.set(p.id,A)}}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 m=this.selectVideoRepresentation();k(m),this.player.initRepresentations(m.id,this.audioRepresentations.get(m.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:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(M(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,B(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!==we.RUNNING||c||!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(ce(),v(d=>d&&this.videoTracks.find(({representation:{id:c}})=>c===d)?.track)).subscribe(e.currentVideoTrack$,i)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(v(({to:d})=>d===l.READY),ce());this.subscription.add(M(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(M(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===l.READY)));const u=M(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(0));this.subscription.add(u.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=rt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(r/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(s&&!e?this.audioRepresentations.get(s.id)?.bitrate??0:0,i?this.audioRepresentations.get(i.id)?.bitrate??0:0),d=Dt(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:u,forwardBufferHealth:o,current:i,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),c=e?d??s:s??d;return c&&this.videoTracks.find(({track:h})=>h===c)?.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===U.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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),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 N(e)}}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),We(this.video)}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}}const ya=5e3,Ve={};var W;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(W||(W={}));const Bt=(a,e)=>new Gt(t=>{const s=(i,r)=>t.next(r);return a.on(e,s),()=>a.off(e,s)});class Ta{subscription=new ie;videoState=new ne(W.INITIALIZING);video;params;hls;textTracksManager=new Me;trackLevels=new Map;constructor(e){this.video=Ge(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.params.output.element$.next(void 0),We(this.video)}loadHlsJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),ya);import("hls.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(W.STOPPED)}subscribe(){k(Ve.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:R.WTF,message:"HlsJsProvider internal logic error",thrown:d})},i=ze(this.video),r=(d,c)=>this.subscription.add(d.subscribe(c,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$),r(i.inPiP$,t.inPiP$),r(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,s)),this.subscription.add(qe(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(Bt(this.hls,Ve.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),w(e.playbackState,l.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),w(e.playbackState,l.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},s)),r(Bt(this.hls,Ve.Events.MANIFEST_PARSED).pipe(v(({levels:d})=>d.reduce((c,h)=>{const f=h.name||h.height.toString(10),{width:m,height:p}=h,T=Rt(h.attrs.QUALITY??"")??nt({width:m,height:p});if(!T)return c;const A=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,S={id:f.toString(),quality:T,bitrate:h.bitrate/1e3,size:{width:m,height:p},fps:A};return this.trackLevels.set(f,{track:S,level:h}),c.push(S),c},[]))),t.availableVideoTracks$),r(Bt(this.hls,Ve.Events.LEVEL_LOADING).pipe(v(({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:c})=>c===d)?.track,o=Bt(this.hls,Ve.Events.LEVEL_SWITCHED).pipe(v(({level:d})=>n(this.hls.levels[d])));o.pipe(j($)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Ne(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel])?.id,d=>{if(J(d))return;const c=this.trackLevels.get(d)?.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(v(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 u=M(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(0));this.subscription.add(u.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!==W.INITIALIZING)switch(s?.to!==l.PAUSED&&i.state===U.Requested&&this.seek(i.position),t){case l.STOPPED:switch(e){case W.STOPPED:break;case W.READY:case W.PLAYING:case W.PAUSED:this.stop();break;default:N(e)}break;case l.READY:switch(e){case W.STOPPED:this.prepare();break;case W.READY:case W.PLAYING:case W.PAUSED:break;default:N(e)}break;case l.PLAYING:switch(e){case W.PLAYING:break;case W.STOPPED:this.prepare();break;case W.READY:case W.PAUSED:this.playIfAllowed();break;default:N(e)}break;case l.PAUSED:switch(e){case W.PAUSED:break;case W.STOPPED:this.prepare();break;case W.READY:this.videoState.setState(W.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED);break;case W.PLAYING:this.pause();break;default:N(e)}break;default:N(t)}};prepare(){this.videoState.startTransitionTo(W.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(W.PLAYING),await st(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:t}))||(this.videoState.setState(W.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))}pause(){this.videoState.startTransitionTo(W.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(W.STOPPED),w(this.params.desiredState.playbackState,l.STOPPED,!0)}}const ps="X-Playback-Duration";var ms=async a=>{const e=await fetch(a,{method:"HEAD"});return e.headers.has(ps)?parseInt(e.headers.get(ps),10):void 0};const Ea=a=>{let e=null;if(a.QUALITY&&(e=Rt(a.QUALITY)),!e&&a.RESOLUTION){const[t,s]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=nt({width:t,height:s})}return e??null},Us=async(a,e=a)=>{const i=(await(await fetch(a)).text()).split(`
8
+ `),r=[];for(let n=0;n<i.length;n++){const u=i[n].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const d=Object.fromEntries(u[1].split(",").map(A=>A.split("="))),c=d.QUALITY??`stream-${d.BANDWIDTH}`,h=Ea(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 m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0;let p;if(d.RESOLUTION){const[A,S]=d.RESOLUTION.split("x").map(P=>parseInt(P,10));A&&S&&(p={width:A,height:S})}const T=new URL(i[++n],e).toString();h&&r.push({id:c,quality:h,url:T,bandwidth:f,size:p,fps:m})}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 va{subscription=new ie;videoState=new ne(ee.STOPPED);video;params;textTracksManager=new Me;manifests$=new g([]);maxSeekBackTime$;liveOffset=new Zt;manifestStartTime$=new g(void 0);constructor(e){this.params=e,this.video=Ge(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]),Us(ft(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.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(u=>u.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:R.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ze(this.video),r=(o,u)=>this.subscription.add(o.subscribe(u,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$),r(i.inPiP$,e.inPiP$),r(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(qe(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(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(ce(),v(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&$(d.to)){const h=d.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ve(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from===ee.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===U.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(Be({startTime:this.manifestStartTime$.pipe(j($)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),this.subscription.add(this.manifests$.pipe(v(o=>o.map(({id:u,quality:d,size:c,bandwidth:h,fps:f})=>({id:u,quality:d,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const n=M(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,Ae(["init"])).pipe(Re(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),We(this.video)}prepare(){const e=this.selectManifest();if(J(e))return;const t=ft(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),ms(t).then(s=>{if(!J(s))this.maxSeekBackTime$.next(s);else{const i=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(J(i)||!isFinite(i))try{fetch(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();ms(o).then(u=>{J(u)||this.maxSeekBackTime$.next(u)})}})}catch{}}})}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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 u=this.videoState.getState();this.videoState.setState(ee.CHANGING_MANIFEST),this.videoState.startTransitionTo(u),this.prepare(),o.state===U.None&&this.params.desiredState.seekState.setState({state:U.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==l.PAUSED&&o.state===U.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 N(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 $a{subscription=new ie;videoState=new ne(ae.STOPPED);video;params;textTracksManager=new Me;manifests$=new g([]);constructor(e){this.params=e,this.video=Ge(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)),Us(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.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(u=>u.id===o)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:R.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ze(this.video),r=(o,u)=>this.subscription.add(o.subscribe(u));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$),r(i.inPiP$,e.inPiP$),r(i.inFullscreen$,e.inFullscreen$),this.subscription.add(ot(this.video,t.isLooped,s)),this.subscription.add(qe(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(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&$(d.to)){const h=d.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ve(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from===ae.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===U.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe(v(o=>o.map(({id:u,quality:d,size:c,bandwidth:h,fps:f})=>({id:u,quality:d,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const n=M(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),We(this.video)}prepare(){const e=this.selectManifest();J(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))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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 u=this.videoState.getState();this.videoState.setState(ae.CHANGING_MANIFEST),this.videoState.startTransitionTo(u);const{currentTime:d}=this.video;this.prepare(),o.state===U.None&&this.params.desiredState.seekState.setState({state:U.Requested,position:d*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&o.state===U.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 N(e)}}}var de;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(de||(de={}));class Aa{subscription=new ie;videoState=new ne(de.STOPPED);video;trackUrls={};params;textTracksManager=new Me;constructor(e){this.params=e,this.video=Ge(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:R.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ze(this.video),r=(o,u)=>this.subscription.add(o.subscribe(u,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$),r(i.inPiP$,e.inPiP$),r(i.inFullscreen$,e.inFullscreen$),this.subscription.add(ot(this.video,t.isLooped,s)),this.subscription.add(qe(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&&$(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=M(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),We(this.video)}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=pt(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))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(t===l.STOPPED){e!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),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===U.None&&this.params.desiredState.seekState.setState({state:U.Requested,position:o*1e3,forcePrecise:!0});return}switch(s?.to!==l.PAUSED&&n.state===U.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 N(e)}}}const Ss=["stun:videostun.mycdn.me:80"],ka=1e3,wa=3,Jt=()=>null;class Pa{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Jt;externalStopCallback=Jt;externalErrorCallback=Jt;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:Ss}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:R.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),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),ka)}normalizeOptions(e={}){const t={stunServerList:Ss,maxRetryNumber:wa,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 Da{subscription;params;log;video;videoState=new ne(te.STOPPED);liveStreamClient;maxSeekBackTime$=new g(0);constructor(e){this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ge(e.container),this.liveStreamClient=new Pa(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),We(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};M(this.videoState.stateChangeStarted$.pipe(v(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const i=ze(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(qe(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 N(n.to)}},s)).add(M(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ae(["init"])).pipe(Re(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:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){st(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,l.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),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 N(e)}}}class gs{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 Ra=()=>{const a=window.navigator;return a.userAgentData?a.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const Vs=Ra(),qt=document.createElement("video"),Fe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(qt.canPlayType?.("application/x-mpegurl")||qt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},ke={mp4:Boolean(qt.canPlayType?.("video/mp4")),webm:Boolean(qt.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"'))},ut=(et.h264||et.h265)&&et.aac,zt=Fe.hls&&ke.mp4,_a=Boolean(window.WebSocket),Ia=()=>Object.keys(et).filter(a=>et[a]),Ca=(a,e=!1)=>a.filter(t=>{switch(t){case b.DASH:return Fe.mse&&ke.mp4&&ut;case b.DASH_SEP:return Fe.mse&&ke.mp4&&ut;case b.DASH_WEBM:return Fe.mse&&ke.webm&&et.vp9&&et.opus;case b.DASH_LIVE:return Fe.mse&&ke.mp4&&ut;case b.DASH_LIVE_CMAF:return Fe.mse&&ke.mp4&&ut&&ke.cmaf;case b.DASH_ONDEMAND:return Fe.mse&&ke.mp4&&ut;case b.HLS:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.HLS_ONDEMAND:return zt||e&&Fe.mse&&ke.mp4&&ut;case b.MPEG:return ke.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Fe.webrtc&&_a&&et.h264&&(ke.mp4||ke.webm);default:return N(t)}}),La=()=>Vs?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:zt?[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],xa=()=>Vs?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF]:zt?[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],bs=a=>a?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var Ba=a=>new Gt(e=>{const t=new ie,s=a.desiredPlaybackState$.stateChangeStarted$.pipe(v(({from:d,to:c})=>`${d}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,r=a.providerChanged$,n=new I;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="provider change",o=0})),t.add(r.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const ys={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Na={cacheDuration:12e4},Ma={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Oa={maxPausedTime:3e4},Ts={maxPausedTime:3e4};class Ua{current$=new g({type:void 0});providerError$=new I;noAvailableProvidersError$=new I;providerOutput={position$:new g(0),duration$:new g(1/0),volume$:new g({muted:!1,volume:1}),currentVideoTrack$:new g(void 0),availableVideoTracks$:new g([]),availableAudioTracks$:new g([]),isAudioAvailable$:new g(!0),autoVideoTrackLimitingAvailable$:new g(!1),currentBuffer$:new g(void 0),isBuffering$:new g(!0),error$:new I,willSeekEvent$:new I,seekedEvent$:new I,loopedEvent$:new I,endedEvent$:new I,firstBytesEvent$:new I,firstFrameEvent$:new I,canplay$:new I,isLive$:new g(void 0),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),inPiP$:new g(!1),inFullscreen$:new g(!1),element$:new g(void 0)};subscription=new ie;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Ca([...xa(),...La()],this.params.tuning.useHlsJs).filter(n=>$(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 gs(i);const r=[...bs(!0),...bs(!1)];this.chromecastFormatsIterator=new gs(r.filter(n=>$(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(J(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:R.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!==U.None;this.params.desiredState.seekState.setState({state:U.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 $e.SCREEN:return this.createScreenProvider(t);case $e.CHROMECAST:return this.createChromecastProvider(t);default:return N(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 Xi({...n,source:o,config:Na})}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 os({...n,source:o,format:e,config:Ts}):new ba({...n,source:o})}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return k(o),new os({...n,source:o,format:e,config:Ts})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return k(o),zt||!this.params.tuning.useHlsJs?new $a({...n,source:o}):new Ta({...n,source:o})}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return k(o),new va({...n,source:o,config:Oa})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return k(o),new Aa({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return k(o),new Wi({...n,source:o,config:Ma})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return k(o),new Da({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 N(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 hi({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()?$e.CHROMECAST:$e.SCREEN}chooseFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case $e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return N(e)}}skipFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.next();case $e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return N(e)}}handleNoFormatsError(e){switch(e){case $e.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case $e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return N(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const 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 ie;let t=!1,s=0;return e.add(M(this.providerOutput.error$,Ba({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:ys.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(j(({type:i})=>i!==void 0))}).pipe(v(i=>({id:`ProviderHangup:${i}`,category:R.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(j(({to:r})=>r===l.PLAYING),pe()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{if(this.current$.getValue().destination===$e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const r=i.category===R.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<ys.providerErrorLimit;n&&(r&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Xt=(a,e,t)=>t*e+(1-t)*a,Fs=(a,e)=>a.reduce((t,s)=>t+s,0)/e,Va=(a,e,t,s)=>{let i=0,r=t;const n=Fs(a,e),o=e<s?e:s;for(let u=0;u<o;u++)a[r]>n?i++:i--,r=(a.length+r-1)%a.length;return Math.abs(i)===o};class Hs{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 xe(`raw_${t}`),this.smoothedSeries$=new xe(`smoothed_${t}`),this.reportedSeries$=new xe(`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)&&(J(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Fa extends Hs{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Xt(this.slow,e,this.params.emaAlphaSlow),this.fast=Xt(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Ha extends Hs{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Fs(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Xt(this.emaSmoothed,e,this.params.emaAlpha);const s=Va(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Es{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Fa({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Ha({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const Ya=5e3,vs="one_video_throughput",$s="one_video_rtt",kt=window.navigator.connection,As=()=>{const a=kt?.downlink;if($(a)&&a!==10)return a*1e3},ks=()=>{const a=kt?.rtt;if($(a)&&a!==3e3)return a},ws=(a,e,t)=>{const s=t*8,i=s/a;return s/(i+e)};class wt{throughput;rtt;subscription=new ie;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=wt.load(vs)||(e.useBrowserEstimation?As():void 0)||Ya,s=wt.load($s)??(e.useBrowserEstimation?ks():void 0)??0;if(this.throughput$=new g(t),this.rtt$=new g(s),this.rttAdjustedThroughput$=new g(ws(t,s,e.rttPenaltyRequestSize)),this.throughput=Es.getSmoothedValue(t,-1,e),this.rtt=Es.getSmoothedValue(s,1,e),e.useBrowserEstimation){const i=()=>{const n=As();n&&this.throughput.next(n);const o=ks();$(o)&&this.rtt.next(o)};kt&&"onchange"in kt&&this.subscription.add(B(kt,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{Wt.set(vs,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{Wt.set($s,i.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Be({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(v(({throughput:i,rtt:r})=>ws(i,r,e.rttPenaltyRequestSize)),j(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=ue();const i=new ie;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=ue()}));break;case 1:case 0:i.add(B(e,"loadstart").subscribe(()=>{t=0,s=ue()}));break}i.add(B(e,"loadend").subscribe(r=>{if(e.status===200){const n=r.loaded,o=ue(),u=n-t,d=o-s;this.addRawSpeed(u,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=ue();let r=0,n=ue();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:c})=>{d?(this.addRawSpeed(s,ue()-i,1),this.concurrentDownloads.delete(e)):c&&(s+=c.byteLength,r+=c.byteLength,r>=this.tuningConfig.streamMinSampleSize&&ue()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,ue()-n,this.concurrentDownloads.size),r=0,n=ue()),await t?.read().then(u,o))};this.concurrentDownloads.add(e),t?.read().then(u,o)}addRawSpeed(e,t,s=1){if(wt.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=Wt.get(e);if($(t))return parseInt(t,10)??void 0}}const Ps={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}},qa=a=>{const e={};for(const t of Object.keys(Ps)){const s=Ps[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 Ga=({seekState:a,position$:e})=>M(a.stateChangeEnded$.pipe(v(({to:t})=>t.state===U.None?void 0:(t.position??NaN)/1e3),j($)),e.pipe(j(()=>a.getState().state===U.None))),za=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return k(e,`Wrong container or containerId {${a.container}}`),e};class Ka{subscription=new ie;domContainer;providerContainer;chromecastInitializer;logger=new Qs;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new ne(l.STOPPED),seekState:new ne({state:U.None}),volume:new ne({volume:1,muted:!1}),videoTrack:new ne(void 0),autoVideoTrackSwitching:new ne(!0),autoVideoTrackLimits:new ne({}),isLooped:new ne(!1),playbackRate:new ne(1),externalTextTracks:new ne([]),currentTextTrack:new ne(void 0),textTrackCuesSettings:new ne({})};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),atLiveEdge$: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),surface$:new g(Ze.NONE),chromecastState$:new g(ge.NOT_AVAILABLE),chromecastDeviceName$:new g(void 0),intrinsicVideoSize$:new g(void 0)};events={inited$:new I,ready$:new I,started$:new I,playing$:new I,paused$:new I,stopped$:new I,willStart$:new I,willResume$:new I,willPause$:new I,willStop$:new I,willDestruct$:new I,watchCoverageRecord$:new I,watchCoverageLive$:new I,managedError$:new I,fatalError$:new I,ended$:new I,looped$:new I,seeked$:new I,willSeek$:new I,firstBytes$:new I,firstFrame$:new I,canplay$:new I,log$:new I};experimental={element$:new g(void 0),enableDebugTelemetry$:new g(!1),dumpTelemetry:wi};constructor(e={}){if(this.initLogs(),this.tuning=qa(e),this.chromecastInitializer=new ei({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new wt(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 u=n.map(h=>JSON.stringify(h,(f,m)=>{const p=typeof m;return["number","string","boolean"].includes(p)?m:m===null?null:`<${p}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:R.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=za(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ua({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:U.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===ge.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===ge.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){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(J(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===U.None?void 0:t.position;return $(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(M(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(v(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(v(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(j(({from:e})=>e===l.STOPPED),pe()).subscribe(()=>{this.initedAt=ue(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case l.READY:this.events.ready$.next();break;case l.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case l.PAUSED:this.events.paused$.next();break;case l.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case l.PAUSED:this.events.willPause$.next();break;case l.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case l.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===U.Requested?this.desiredState.seekState.setState({...n,state:U.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:R.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===U.Applying&&(this.desiredState.seekState.setState({state:U.None}),this.events.seeked$.next())})).add(e.current$.pipe(v(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(v(n=>n.destination),ce()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(v(n=>n.map(({quality:o})=>o).sort((o,u)=>Ot(o)?1:Ot(u)?-1:Nt(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.hostname$.pipe(ce()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ce()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ce()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(v(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(Be({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$}).pipe(v(({isLive:n,position:o})=>n&&o>-Js),ce()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(v(n=>n.muted),ce()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(v(n=>n.volume),ce()).subscribe(this.info.volume$)).add(Ga({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(M(e.providerOutput.endedEvent$.pipe(lt(!0)),e.providerOutput.seekedEvent$.pipe(lt(!1))).pipe(ce()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(v(n=>({id:"NoProviders",category:R.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(),v(n=>n??ue()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(pe(),v(()=>ue()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(pe(),v(()=>ue()-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(j(({to:n})=>n===l.PLAYING),pe()).subscribe(()=>s.next(!1)));let i=0;const r=M(e.providerOutput.isBuffering$,t,s).pipe(v(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),ce());this.subscription.add(r.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(M(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})),this.subscription.add(M(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let c;d===ge.CONNECTED?c=Ze.SECOND_SCREEN:u?n?c=Ze.PIP:o?c=Ze.FULLSCREEN:c=Ze.INLINE:c=Ze.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(v(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(ce((s,i)=>s.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(j(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=Dt(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(M(this.desiredState.videoTrack.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(v(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(v(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(v(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){const e=this.providerContainer?.providerOutput;k(this.providerContainer),k(e),ki(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ai(t)),this.providerContainer.current$.subscribe(({type:t})=>Ct("provider",t)),e.duration$.subscribe(t=>Ct("duration",t)),e.availableVideoTracks$.pipe(j(t=>!!t.length),pe()).subscribe(t=>Ct("tracks",t)),this.events.fatalError$.subscribe(new xe("fatalError")),this.events.managedError$.subscribe(new xe("managedError")),e.position$.subscribe(new xe("position")),e.currentVideoTrack$.pipe(v(t=>t?.quality)).subscribe(new xe("quality")),this.info.currentBuffer$.subscribe(new xe("buffer")),e.isBuffering$.subscribe(new xe("isBuffering"))].forEach(t=>this.subscription.add(t)),Ct("codecs",Ia())}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=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:R.DOM,message:String(i)})})};this.subscription.add(M(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 Xa=`${Xs}@${Ks}`;export{ge as ChromecastState,Pt as HttpConnectionType,tr as Observable,l as PlaybackState,Ka as Player,Xa as SDK_VERSION,sr as Subject,ir as Subscription,Ze as Surface,ar as ValueSubject,b as VideoFormat,se as VideoQuality};