@vkontakte/videoplayer-core 2.0.78-dev.196c6f0.0 → 2.0.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +3 -3
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +3 -3
- package/es2018.esm.js +3 -3
- package/esnext.cjs.js +3 -3
- package/esnext.esm.js +3 -3
- package/package.json +2 -2
package/esnext.esm.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.78
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.78
|
|
3
|
+
* Thu, 02 Feb 2023 10:14:35 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-78/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as g,Subject as D,Subscription as K,isNonNullable as $,ErrorCategory as _,isNullable as z,fromEvent as M,assertNever as N,merge as O,tap as rs,map as v,observableFrom as ke,filterChanged as he,assertNonNullable as A,debounce as Ie,timeout as Ks,combine as qe,once as pe,mapTo as nt,filter as U,now as ce,Observable as _t,abortable as _e,getExponentialDelay as as,interval as Xs,Logger as Zs}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as na,Subject as oa,Subscription as da,ValueSubject as ca}from"@vkontakte/videoplayer-shared/esnext.esm.js";import ei from"lodash/debounce.js";const ti="2.0.78-dev.196c6f0.0",si="@vkontakte/videoplayer-core";var f;(function(r){r.STOPPED="stopped",r.PLAYING="playing",r.PAUSED="paused"})(f||(f={}));var b;(function(r){r.MPEG="MPEG",r.DASH="DASH",r.DASH_SEP="DASH_SEP",r.DASH_SEP_VK="DASH_SEP",r.DASH_WEBM="DASH_WEBM",r.DASH_WEBM_VK="DASH_WEBM",r.DASH_ONDEMAND="DASH_ONDEMAND",r.DASH_ONDEMAND_VK="DASH_ONDEMAND",r.DASH_LIVE="DASH_LIVE",r.DASH_LIVE_WEBM="DASH_LIVE_WEBM",r.HLS="HLS",r.HLS_ONDEMAND="HLS_ONDEMAND",r.HLS_JS="HLS",r.HLS_LIVE="HLS_LIVE",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var $e;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})($e||($e={}));var Te;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(Te||(Te={}));var Dt;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(Dt||(Dt={}));var B;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(B||(B={}));var ii=r=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",r),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class ri{connection$=new g(void 0);castState$=new g(Te.NOT_AVAILABLE);errorEvent$=new D;contentId;realCastState$=new g(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=$(window.chrome?.cast),i=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},i||ii("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.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();z(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();z(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(M(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(O(M(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(rs(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),v(i=>i.castState)),ke([s.getCastState()])).pipe(he(),v(ai),rs(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{const a=i===Te.CONNECTED,n=$(this.connection$.getValue());if(a&&!n){const o=s.getCurrentSession();A(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(z(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i===Te.CONNECTED?$(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:_.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}}const ai=r=>{switch(r){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 N(r)}};var ht;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ht||(ht={}));var ft=(r,e=0,t=ht.OFFSET_P)=>{switch(t){case ht.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ht.PLAYBACK_SHIFT:{if(e===0)return r;const s=new URL(r);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:N(t)}return r},w=(r,e,t=!1)=>{const s=r.getTransition();(t||!s||s.to===e)&&r.setState(e)},te;(function(r){r.INVARIANT="Invariant quality",r.Q_144P="144p",r.Q_240P="240p",r.Q_360P="360p",r.Q_480P="480p",r.Q_720P="720p",r.Q_1080P="1080p",r.Q_1440P="1440p",r.Q_2160P="2160p",r.Q_4320P="4320p"})(te||(te={}));const Ce={[te.Q_144P]:{width:256,height:144},[te.Q_240P]:{width:428,height:240},[te.Q_360P]:{width:640,height:360},[te.Q_480P]:{width:856,height:480},[te.Q_720P]:{width:1280,height:720},[te.Q_1080P]:{width:1920,height:1080},[te.Q_1440P]:{width:2560,height:1440},[te.Q_2160P]:{width:3840,height:2160},[te.Q_4320P]:{width:7680,height:4320}},Ut=(r,e)=>Ce[r].height>Ce[e].height,ni=(r,e)=>Ce[r].height>=Ce[e].height,At=(r,e)=>Ce[r].height<Ce[e].height,oi=(r,e)=>Ce[r].height<=Ce[e].height,di=r=>r.sort((e,t)=>e===t?0:e===te.INVARIANT?1:t===te.INVARIANT?-1:At(e,t)?1:-1)[0],ci=Object.keys(Ce).sort((r,e)=>At(r,e)?-1:1),ot=({width:r,height:e})=>{const t=Math.min(r,e),s=Math.max(r,e);return ci.find(i=>{const a=Ce[i];return a.width>=s&&a.height>=t})},ui=r=>Ce[r].height,Vt=r=>r===te.INVARIANT;class ae{state;transition;transitionStarted$=new D;transitionEnded$=new D;transitionUpdated$=new D;forceChanged$=new D;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(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 hi=r=>{switch(r){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.HLS_LIVE:case b.DASH_LIVE:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return N(r)}};var G;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(G||(G={}));const li=5,fi=5,pi=500,ns=7e3;class mi{subscription=new K;loadMediaTimeoutSubscription=new K;videoState=new ae(G.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(hi(e.format)),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(O(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,a)=>this.subscription.add(i.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new D;e.add(i.pipe(Ie(pi)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===B.Applying||Math.abs(o-a)>li)&&i.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);const{remotePlayer:a}=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()&&a.duration-a.currentTime<fi&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,f.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:N(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});const s=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(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(G.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):(this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,f.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:B.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===G.PAUSED||e===G.PLAYING)&&(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===G.PLAYING||e===G.PAUSED)&&(this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,f.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY)}handleRemoteStop(){this.videoState.getState()!==G.STOPPED&&this.videoState.setState(G.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,a;switch(e){case b.MPEG:{const d=t[e];A(d);const u=di(Object.keys(d));A(u);const h=d[u];A(h),s=h,i="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const d=t[e];A(d),s=d.url,i="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const d=t[e];A(d),s=d.url,i="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS_LIVE:{const d=t[e];A(d),s=ft(d.url),i="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",u=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_.VIDEO_PIPELINE,message:d,thrown:u}),u}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=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return $(o)&&(n.metadata.title=o),$(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===B.Applying||s.state===B.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,a)=>{this.loadMediaTimeoutSubscription.add(Ks(ns).subscribe(()=>a(`timeout(${ns})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:_.VIDEO_PIPELINE,message:a,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(),a=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(a)};`}),s===f.STOPPED){e!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.stop());return}if(!t){if(i?.to!==f.PAUSED&&a.state===B.Requested&&e!==G.STOPPED){this.seek(a.position);return}switch(s){case f.PLAYING:{switch(e){case G.PLAYING:break;case G.PAUSED:this.videoState.startTransitionTo(G.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case G.READY:this.videoState.startTransitionTo(G.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case G.PLAYING:this.videoState.startTransitionTo(G.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case G.PAUSED:break;case G.READY:this.videoState.startTransitionTo(G.PAUSED),this.videoState.setState(G.PAUSED);break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:N(e)}break}default:N(s)}}}}class os{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let i=0,a=s.length;i<a;i++)if(s[i].callback===t){s.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let i=0,a=s.length;i<a;i++){const n=s[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Is extends os{constructor(){super(),this.listeners||os.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Cs=class{constructor(){Object.defineProperty(this,"signal",{value:new Is,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Cs.prototype[Symbol.toStringTag]="AbortController",Is.prototype[Symbol.toStringTag]="AbortSignal");function Ls(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Si(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=r;if(!Ls({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||i)&&(a=function(d,u){let h;u&&u.signal&&(h=u.signal,delete u.signal);const l=new t(d,u);return h&&Object.defineProperty(l,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),l},a.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const u=a&&a.prototype.isPrototypeOf(c)?c.signal:d?d.signal:void 0;if(u){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(u.aborted)return Promise.reject(h);const l=new Promise((p,S)=>{u.addEventListener("abort",()=>S(h),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([l,n(c,d)])}return n(c,d)},Request:a}}const Qt=Ls({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xs=Qt?Si({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,pt=Qt?xs.fetch:window.fetch;Qt?xs.Request:window.Request;const rt=Qt?Cs:window.AbortController,Et=r=>r.range?r.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class wt{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){const{url:t}=e.request,s=this.dashJsRequestQueue.get(t)??[];s.push(e),this.dashJsRequestQueue.set(t,s)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const i=t[0];if(!i||!i.request.range)continue;const[a,n]=Et(i.request);if(a>=s.from&&n<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const i=this.sendBigRequest(e,t.map(({request:a})=>a));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 a=s[0][1];for(let l=1;l<s.length&&a<this.params.minDataSize;l++){const p=s[l][1];p-i<=2*this.params.minDataSize&&(a=Math.max(a,p))}i===0?a=Math.max(a,i+this.params.minInitSize):a=Math.max(a,i+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${i}-${a}`);const o=n.toString(),c=new rt,d=c.signal,u={url:e,from:i,to:a,loaded:0,data:null,abortController:c};d.addEventListener("abort",()=>this.onBigRequestAbort(u));const h=l=>{throw this.params.onError?.({id:"BigRequestParsing",category:_.PARSER,message:"Error parsing response data",thrown:l}),l};return pt(o,{signal:d}).then(l=>{if(u.response=l,!l.ok||!l.body){this.onBigRequestError(u);return}const[p,S]=l.body.tee();this.params.onDownloadStream?.(S);const m=p.getReader(),T=parseInt(l.headers.get("Content-Length")??"",10)||a-i+1;u.data=new ArrayBuffer(T);const P=new Uint8Array(u.data),L=async({done:se,value:k})=>{se?this.onBigRequestProgress(u):k&&(P.set(k,u.loaded),u.loaded+=k.byteLength,this.onBigRequestProgress(u),await m?.read().then(L,wt.suppressStreamErrors).catch(h))};m?.read().then(L,wt.suppressStreamErrors).catch(h)},wt.suppressAbort).catch(l=>this.onBigRequestError(u,l)),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:a,response:n}){if(!this.activeRequests.has(e)||!a)return;const o=this.dashJsRequestQueue.get(e)??[];for(const c of o){const{request:d}=c,[u,h]=Et(d),l=u>=t&&h<=t+i,p=t>=u&&t+i<h,S=a.slice(u-t,Math.min(h-t+1,i));if((l||p)&&(d.requestStartDate=d.requestStartDate??new Date,d.firstByteDate=d.firstByteDate??new Date,d.bytesLoaded=S.byteLength,d.bytesTotal=s-t),l){d.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter(T=>T!==c)),c.success?.(S,"",e);const m=n?Array.from(n.headers.entries()).map(([T,P])=>`${T}: ${P}`).join(`\r
|
|
6
|
+
import{ValueSubject as g,Subject as D,Subscription as K,isNonNullable as $,ErrorCategory as _,isNullable as z,fromEvent as M,assertNever as N,merge as O,tap as rs,map as v,observableFrom as ke,filterChanged as he,assertNonNullable as A,debounce as Ie,timeout as Ks,combine as qe,once as pe,mapTo as nt,filter as U,now as ce,Observable as _t,abortable as _e,getExponentialDelay as as,interval as Xs,Logger as Zs}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{Observable as na,Subject as oa,Subscription as da,ValueSubject as ca}from"@vkontakte/videoplayer-shared/esnext.esm.js";import ei from"lodash/debounce.js";const ti="2.0.78",si="@vkontakte/videoplayer-core";var f;(function(r){r.STOPPED="stopped",r.PLAYING="playing",r.PAUSED="paused"})(f||(f={}));var b;(function(r){r.MPEG="MPEG",r.DASH="DASH",r.DASH_SEP="DASH_SEP",r.DASH_SEP_VK="DASH_SEP",r.DASH_WEBM="DASH_WEBM",r.DASH_WEBM_VK="DASH_WEBM",r.DASH_ONDEMAND="DASH_ONDEMAND",r.DASH_ONDEMAND_VK="DASH_ONDEMAND",r.DASH_LIVE="DASH_LIVE",r.DASH_LIVE_WEBM="DASH_LIVE_WEBM",r.HLS="HLS",r.HLS_ONDEMAND="HLS_ONDEMAND",r.HLS_JS="HLS",r.HLS_LIVE="HLS_LIVE",r.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var $e;(function(r){r.SCREEN="SCREEN",r.CHROMECAST="CHROMECAST"})($e||($e={}));var Te;(function(r){r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED"})(Te||(Te={}));var Dt;(function(r){r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic"})(Dt||(Dt={}));var B;(function(r){r.None="none",r.Requested="requested",r.Applying="applying"})(B||(B={}));var ii=r=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",r),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class ri{connection$=new g(void 0);castState$=new g(Te.NOT_AVAILABLE);errorEvent$=new D;contentId;realCastState$=new g(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=$(window.chrome?.cast),i=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},i||ii("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.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();z(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();z(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(M(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(O(M(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(rs(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),v(i=>i.castState)),ke([s.getCastState()])).pipe(he(),v(ai),rs(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{const a=i===Te.CONNECTED,n=$(this.connection$.getValue());if(a&&!n){const o=s.getCurrentSession();A(o);const c=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(z(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:c}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i===Te.CONNECTED?$(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:_.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:i})}}}const ai=r=>{switch(r){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 N(r)}};var ht;(function(r){r[r.OFFSET_P=0]="OFFSET_P",r[r.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ht||(ht={}));var ft=(r,e=0,t=ht.OFFSET_P)=>{switch(t){case ht.OFFSET_P:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ht.PLAYBACK_SHIFT:{if(e===0)return r;const s=new URL(r);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:N(t)}return r},w=(r,e,t=!1)=>{const s=r.getTransition();(t||!s||s.to===e)&&r.setState(e)},te;(function(r){r.INVARIANT="Invariant quality",r.Q_144P="144p",r.Q_240P="240p",r.Q_360P="360p",r.Q_480P="480p",r.Q_720P="720p",r.Q_1080P="1080p",r.Q_1440P="1440p",r.Q_2160P="2160p",r.Q_4320P="4320p"})(te||(te={}));const Ce={[te.Q_144P]:{width:256,height:144},[te.Q_240P]:{width:428,height:240},[te.Q_360P]:{width:640,height:360},[te.Q_480P]:{width:856,height:480},[te.Q_720P]:{width:1280,height:720},[te.Q_1080P]:{width:1920,height:1080},[te.Q_1440P]:{width:2560,height:1440},[te.Q_2160P]:{width:3840,height:2160},[te.Q_4320P]:{width:7680,height:4320}},Ut=(r,e)=>Ce[r].height>Ce[e].height,ni=(r,e)=>Ce[r].height>=Ce[e].height,At=(r,e)=>Ce[r].height<Ce[e].height,oi=(r,e)=>Ce[r].height<=Ce[e].height,di=r=>r.sort((e,t)=>e===t?0:e===te.INVARIANT?1:t===te.INVARIANT?-1:At(e,t)?1:-1)[0],ci=Object.keys(Ce).sort((r,e)=>At(r,e)?-1:1),ot=({width:r,height:e})=>{const t=Math.min(r,e),s=Math.max(r,e);return ci.find(i=>{const a=Ce[i];return a.width>=s&&a.height>=t})},ui=r=>Ce[r].height,Vt=r=>r===te.INVARIANT;class ae{state;transition;transitionStarted$=new D;transitionEnded$=new D;transitionUpdated$=new D;forceChanged$=new D;stateChangeStarted$=O(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=O(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 hi=r=>{switch(r){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.HLS_LIVE:case b.DASH_LIVE:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return N(r)}};var G;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(G||(G={}));const li=5,fi=5,pi=500,ns=7e3;class mi{subscription=new K;loadMediaTimeoutSubscription=new K;videoState=new ae(G.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(hi(e.format)),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(O(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,a)=>this.subscription.add(i.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new D;e.add(i.pipe(Ie(pi)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===B.Applying||Math.abs(o-a)>li)&&i.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);const{remotePlayer:a}=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()&&a.duration-a.currentTime<fi&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,f.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:N(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});const s=O(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(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(G.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):(this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,f.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:B.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===G.PAUSED||e===G.PLAYING)&&(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===G.PLAYING||e===G.PAUSED)&&(this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,f.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===G.READY&&this.videoState.setState(G.READY)}handleRemoteStop(){this.videoState.getState()!==G.STOPPED&&this.videoState.setState(G.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,a;switch(e){case b.MPEG:{const d=t[e];A(d);const u=di(Object.keys(d));A(u);const h=d[u];A(h),s=h,i="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const d=t[e];A(d),s=d.url,i="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const d=t[e];A(d),s=d.url,i="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS_LIVE:{const d=t[e];A(d),s=ft(d.url),i="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",u=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:_.VIDEO_PIPELINE,message:d,thrown:u}),u}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=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:o,subtitle:c}=this.params.meta;return $(o)&&(n.metadata.title=o),$(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===B.Applying||s.state===B.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,a)=>{this.loadMediaTimeoutSubscription.add(Ks(ns).subscribe(()=>a(`timeout(${ns})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:_.VIDEO_PIPELINE,message:a,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(),a=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(a)};`}),s===f.STOPPED){e!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.stop());return}if(!t){if(i?.to!==f.PAUSED&&a.state===B.Requested&&e!==G.STOPPED){this.seek(a.position);return}switch(s){case f.PLAYING:{switch(e){case G.PLAYING:break;case G.PAUSED:this.videoState.startTransitionTo(G.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case G.READY:this.videoState.startTransitionTo(G.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case G.PLAYING:this.videoState.startTransitionTo(G.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case G.PAUSED:break;case G.READY:this.videoState.startTransitionTo(G.PAUSED),this.videoState.setState(G.PAUSED);break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:N(e)}break}default:N(s)}}}}class os{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let i=0,a=s.length;i<a;i++)if(s[i].callback===t){s.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let i=0,a=s.length;i<a;i++){const n=s[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Is extends os{constructor(){super(),this.listeners||os.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Cs=class{constructor(){Object.defineProperty(this,"signal",{value:new Is,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch{s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Cs.prototype[Symbol.toStringTag]="AbortController",Is.prototype[Symbol.toStringTag]="AbortSignal");function Ls(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Si(r){typeof r=="function"&&(r={fetch:r});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=r;if(!Ls({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||i)&&(a=function(d,u){let h;u&&u.signal&&(h=u.signal,delete u.signal);const l=new t(d,u);return h&&Object.defineProperty(l,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),l},a.prototype=t.prototype);const n=e;return{fetch:(c,d)=>{const u=a&&a.prototype.isPrototypeOf(c)?c.signal:d?d.signal:void 0;if(u){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(u.aborted)return Promise.reject(h);const l=new Promise((p,S)=>{u.addEventListener("abort",()=>S(h),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([l,n(c,d)])}return n(c,d)},Request:a}}const Qt=Ls({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xs=Qt?Si({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,pt=Qt?xs.fetch:window.fetch;Qt?xs.Request:window.Request;const rt=Qt?Cs:window.AbortController,Et=r=>r.range?r.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class wt{dashJsRequestQueue;activeRequests;dashMetrics;params;constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){const{url:t}=e.request,s=this.dashJsRequestQueue.get(t)??[];s.push(e),this.dashJsRequestQueue.set(t,s)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const i=t[0];if(!i||!i.request.range)continue;const[a,n]=Et(i.request);if(a>=s.from&&n<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const i=this.sendBigRequest(e,t.map(({request:a})=>a));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 a=s[0][1];for(let l=1;l<s.length&&a<this.params.minDataSize;l++){const p=s[l][1];p-i<=2*this.params.minDataSize&&(a=Math.max(a,p))}i===0?a=Math.max(a,i+this.params.minInitSize):a=Math.max(a,i+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${i}-${a}`);const o=n.toString(),c=new rt,d=c.signal,u={url:e,from:i,to:a,loaded:0,data:null,abortController:c};d.addEventListener("abort",()=>this.onBigRequestAbort(u));const h=l=>{throw this.params.onError?.({id:"BigRequestParsing",category:_.PARSER,message:"Error parsing response data",thrown:l}),l};return pt(o,{signal:d}).then(l=>{if(u.response=l,!l.ok||!l.body){this.onBigRequestError(u);return}const[p,S]=l.body.tee();this.params.onDownloadStream?.(S);const m=p.getReader(),T=parseInt(l.headers.get("Content-Length")??"",10)||a-i+1;u.data=new ArrayBuffer(T);const P=new Uint8Array(u.data),L=async({done:se,value:k})=>{se?this.onBigRequestProgress(u):k&&(P.set(k,u.loaded),u.loaded+=k.byteLength,this.onBigRequestProgress(u),await m?.read().then(L,wt.suppressStreamErrors).catch(h))};m?.read().then(L,wt.suppressStreamErrors).catch(h)},wt.suppressAbort).catch(l=>this.onBigRequestError(u,l)),u}onBigRequestProgress({url:e,from:t,to:s,loaded:i,data:a,response:n}){if(!this.activeRequests.has(e)||!a)return;const o=this.dashJsRequestQueue.get(e)??[];for(const c of o){const{request:d}=c,[u,h]=Et(d),l=u>=t&&h<=t+i,p=t>=u&&t+i<h,S=a.slice(u-t,Math.min(h-t+1,i));if((l||p)&&(d.requestStartDate=d.requestStartDate??new Date,d.firstByteDate=d.firstByteDate??new Date,d.bytesLoaded=S.byteLength,d.bytesTotal=s-t),l){d.requestEndDate=new Date,this.dashJsRequestQueue.set(e,(this.dashJsRequestQueue.get(e)??[]).filter(T=>T!==c)),c.success?.(S,"",e);const m=n?Array.from(n.headers.entries()).map(([T,P])=>`${T}: ${P}`).join(`\r
|
|
7
7
|
`):"";this.dashMetrics?.addHttpRequest(d,e,n?.status??200,m,[])}else p&&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:_.NETWORK,message:"Download error",thrown:i}),!this.activeRequests.has(e))return;const a=this.dashJsRequestQueue.get(e)??[];for(const n of a){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 a of i){const[n,o]=Et(a.request);(n>=t&&n<s||o>t&&o<=s)&&a?.abort?.(a.request)}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Ht{baseLoader;config;bigRequest;constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Ht.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Ht.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const gi=(r,e)=>t=>({create:s=>{const i=r(t).create(s);return new Ht(i,e,s)}}),bi=(r,e)=>{const t=new wt(e);return r.extend("SchemeLoaderFactory",function(){const{parent:s}=this,i=s.getLoader;return{getLoader:a=>{const n=i(a);return gi(n,t)}}},!0),()=>t.destroy()};var yi=r=>{let e,t=!1,s=!1;r.on("playbackTimeUpdated",({timeToEnd:i})=>{s=i<=3,t&&s&&e?.()}),r.extend("MediaSourceController",function(){const{parent:i}=this,a=i.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&s&&e?.()}}},!0)},Ti=r=>{const e=new g(1/0),t=new D,s=new g(void 0),i=new g(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},c=u=>{const h=Object.fromEntries(u.getAllResponseHeaders().trim().split(/[\n\r]+/).map(S=>S.split(": ")));if("x-playback-duration"in h||"x-playback-duration-millis"in h){const S=parseInt(u.getResponseHeader("X-Playback-Duration")??"",10),T=parseInt(u.getResponseHeader("X-Playback-Duration-Millis")??"",10)??S*1e3??NaN;$(T)&&!isNaN(T)&&e.next(T)}const l=h["x-delivery-type"]??Dt.HTTP1,p={1:!0,0:!1}[h["x-reused"]]??void 0;s.next(l),i.next(p)},d=u=>{u.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return r.extend("XHRLoader",function(){const{parent:u}=this,h=u.load.bind(u);return{load:function(l){if(l.request.type==="MPD"){const p=l.onload,S=l.progress;l.onload=function(...m){return c(this),p(...m)},l.progress=function(...m){return d(this),S(...m)},o()}return h(l)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:i,connectionType$:s}},mt=r=>{const e=new URL(r);return e.searchParams.set("quic","1"),e.toString()},Ei=r=>r.extend("RequestModifier",()=>({modifyRequestURL:mt}),!0),vi=r=>{r.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[i,a]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${i}-${a}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const Be=(r,e,t,{equal:s=(n,o)=>n===o,changed$:i,onError:a}={})=>{const n=r.getState(),o=e(),c=z(i),d=new K;return i&&d.add(i.subscribe(u=>{const h=r.getState();s(u,h)&&r.setState(u)},a)),s(o,n)||(t(n),c&&r.setState(n)),d.add(r.stateChangeStarted$.subscribe(u=>{t(u.to),c&&r.setState(u.to)},a)),d},dt=(r,e,t)=>Be(e,()=>r.loop,s=>{$(s)&&(r.loop=s)},{onError:t}),Ge=(r,e,t,s)=>Be(e,()=>({muted:r.muted,volume:r.volume}),i=>{$(i)&&(r.muted=i.muted,r.volume=i.volume)},{equal:(i,a)=>i===a||i?.muted===a?.muted&&i?.volume===a?.volume,changed$:t,onError:s}),et=(r,e,t,s)=>Be(e,()=>r.playbackRate,i=>{$(i)&&(r.playbackRate=i)},{changed$:t,onError:s}),$i=r=>["__",r.language,r.label].join("|"),ki=(r,e)=>{if(r.id===e)return!0;const[t,s,i]=e.split("|");return r.language===s&&r.label===i};class Oe{available$=new D;current$=new g(void 0);error$=new D;video;cueSettings;subscription=new K;externalTracks=new Map;connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const i=a=>{this.error$.next({id:"TextTracksManager",category:_.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(Be(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{$(a)&&this.setExternal(a)},{equal:(a,n)=>$(a)&&$(n)&&a.length===n.length&&a.every(({id:o},c)=>o===n[c].id),changed$:this.available$.pipe(v(a=>a.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Be(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:i})),this.subscription.add(Be(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){A(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(O(M(e,"addtrack"),M(e,"removetrack"),ke(["init"])).pipe(v(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),he((s,i)=>s.length===i.length&&s.every(({id:a},n)=>a===i[n].id))).subscribe(this.available$)),this.subscription.add(O(M(e,"change"),ke(["init"])).pipe(v(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),v(s=>s&&this.htmlTextTrackToITextTrack(s).id),he()).subscribe(this.current$));const t=s=>this.applyCueSettings(s.target?.activeCues??null);this.subscription.add(M(e,"addtrack").subscribe(s=>{s.track?.addEventListener("cuechange",t);const i=a=>{const n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",i))};s.track?.addEventListener("cuechange",i)})),this.subscription.add(M(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){A(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Oe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,i=e.id!==""?e.id:$i(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){A(this.video);for(const t of this.htmlTextTracksAsArray(!0))$(e)&&ki(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){A(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){A(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 Ye=r=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r.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 Ns=()=>{const{userAgent:r}=window.navigator;return!/chrome/i.test(r)&&/webkit|safari|khtml/i.test(r)};const Zt=3;class Ai{_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 a=this._source.buffered.end(t);i>e&&i-e<Zt&&(i=e),this._buffer.push({from:i,to:a,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||Zt))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:i,to:a})=>{const n=i>=e&&i<t,o=a>=e&&a<t;n&&o||(n?s(t,a):o?s(i,e):i<e&&a>t?(s(t,a),s(i,e)):s(i,a))})}destroy(){this._buffer=[]}}var Bs=(r,e,t=Zt)=>{let s=0,i=0;for(let a=0;a<r.length;a++){const n=r.start(a),o=r.end(a);if(n<=e&&e<=o){if(s=n,i=o,!t)return{from:s,to:i};for(let c=a-1;c>=0;c--)r.end(c)+t>=s&&(s=r.start(c));for(let c=a+1;c<r.length;c++)r.start(c)-t<=i&&(i=r.end(c))}}return{from:s,to:i}};const ze=r=>{const e=p=>M(r,p).pipe(nt(void 0)),s=O(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(p=>M(r,p))).pipe(v(p=>p.type==="ended"?r.readyState<2:r.readyState<3),he()),i=O(M(r,"progress"),M(r,"timeupdate")).pipe(v(()=>Bs(r.buffered,r.currentTime))),a=Ns()?qe({play:e("play").pipe(pe()),playing:e("playing")}).pipe(nt(void 0)):e("playing"),n=M(r,"volumechange").pipe(v(()=>({muted:r.muted,volume:r.volume}))),o=M(r,"ratechange").pipe(v(()=>r.playbackRate)),c=M(r,"error").pipe(U(()=>Boolean(r.error||r.played.length)),v(()=>{const p=r.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:_.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:r.error??void 0}})),d=M(r,"timeupdate").pipe(v(()=>r.currentTime)),u=new D,h=.3;let l;return d.subscribe(p=>{r.loop&&$(l)&&$(p)&&l>=r.duration-h&&p<=h&&u.next(l),l=p}),{playing$:a,pause$:e("pause").pipe(U(()=>!r.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:u,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:M(r,"durationchange").pipe(v(()=>r.duration)),isBuffering$:s,currentBuffer$:i,volumeState$:n,playbackRateState$:o}},ts=r=>{if(r.includes("/")){const e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};let ss=!1,Ve={};const wi=r=>{ss=r},Pi=()=>{Ve={}},Ri=r=>{r(Ve)},Nt=(r,e)=>{ss&&(Ve.meta=Ve.meta??{},Ve.meta[r]=e)};class Ne{name;constructor(e){this.name=e}next(e){if(!ss)return;Ve.series=Ve.series??{};const t=Ve.series[this.name]??[];t.push([Date.now(),e]),Ve.series[this.name]=t}}const Di=new Ne("best_bitrate"),_i=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;class Ii{last;history={};recordSelection(e){this.history[e.id]=ce()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const It=(r,{container:e,throughput:t,tuning:s,limits:i,reserve:a=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},l=h&&ot(h),p=s.considerPlaybackRate&&$(o)?o:1,S=r.filter(x=>!Vt(x.quality)).sort((x,ie)=>Ut(x.quality,ie.quality)?-1:1),m=S.at(-1)?.quality,T=S.at(0)?.quality,P=z(i)||$(i.min)&&$(i.max)&&At(i.max,i.min)||$(i.min)&&T&&Ut(i.min,T)||$(i.max)&&m&&At(i.max,m),L=p*_i(n??.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),k=S.filter(x=>{const ie=l?At(x.quality,l):!0,V=$(t)&&isFinite(t)&&$(x.bitrate)?t-a>=x.bitrate*L:!0,j=s.lazyQualitySwitch&&$(s.minBufferToSwitchUp)&&c&&!Vt(c.quality)&&(n??0)<s.minBufferToSwitchUp&&Ut(x.quality,c.quality),ne=P||(z(i.max)||oi(x.quality,i.max))&&(z(i.min)||ni(x.quality,i.min));return ie&&V&&!j&&ne})[0];k&&k.bitrate&&Di.next(k.bitrate);const E=k??S[Math.ceil((S.length-1)/2)]??r[0],I=E&&d&&d.history[E.id]&&ce()-d.history[E.id]<=s.trackCooldown&&(!d.last||E.id!==d.last.id);if(E?.id&&d&&!I&&d.recordSelection(E),I&&d?.last){const x=d.last;return d?.recordSwitch(x),x}return d?.recordSwitch(E),E};var ve=r=>new URL(r).hostname;const Ci=300,qt=(r,e=Ci)=>new _t(t=>{const{width:s,height:i}=r.getBoundingClientRect();if(t.next({width:s,height:i}),!window.ResizeObserver)return;const a=new ResizeObserver(ei(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),$(c)&&$(d)&&t.next({width:c,height:d})},e));return a.observe(r),()=>a.disconnect()}),Li=5e3,vt={};var Y;(function(r){r.DOWNLOADING_LIB="downloading_lib",r.STOPPED="stopped",r.STREAM_INITIALIZED="stream_initialized",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(Y||(Y={}));const fe=(r,e)=>new _t(t=>{const s=i=>t.next(i);return r.on(e,s),()=>r.off(e,s)});class xi{subscription=new K;videoState=new ae(Y.DOWNLOADING_LIB);video;player;params;textTracksManager=new Oe;videoTracks=[];frameRatesByFrameHeight={};isLive$=new g(void 0);maxSeekBackTime$=new g(1/0);availableFrom$=new g(void 0);elementSize$=new g(void 0);liveOffset=new es;destroyBigRequest;constructor(e){this.video=Ye(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),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:_.NETWORK,message:`Dash.js failed to load: ${i?.toString?.()}`,thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),Li);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(){A(vt.MediaPlayer,"dashjs not loaded"),A(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===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=bi(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&&vi(this.player),yi(this.player),this.params.tuning.requestQuick&&Ei(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=m=>{e.error$.next({id:"DashIFProvider",category:_.WTF,message:"DashIFProvider internal logic error",thrown:m})},i=(m,T)=>this.subscription.add(m.subscribe(T,s));i(qt(this.video),this.elementSize$),i(fe(this.player,"error").pipe(v(m=>{const T=typeof m.error=="object"?m.error.code:m.error,P=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${T}`,message:P}})),e.error$),i(fe(this.player,"playbackError").pipe(v(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=fe(this.player,"qualityChangeRendered").pipe(U(({mediaType:m})=>m==="video"),v(({newQuality:m})=>this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===m)?.track));a.pipe(U($)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(U(({to:m})=>m===Y.STREAM_INITIALIZED),pe()).subscribe(()=>{this.subscription.add(Be(t.videoTrack,()=>{const m=this.player.getQualityFor("video");return this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===m)?.track?.id},m=>{if(z(m))return;const T=this.videoTracks.find(({track:P})=>P.id===m)?.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:a.pipe(v(m=>m?.id)),onError:s}))},s)),this.subscription.add(Be(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(U(({mediaType:m})=>m==="video"),v(({state:m})=>m==="bufferStalled")),e.isBuffering$),i(fe(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:T}})=>{const P=this.player.getDashMetrics(),L=P.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),se=P.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type")??Dt.HTTP1,k={1:!0,0:!1}[L]??void 0;this.params.output.httpConnectionType$.next(se),this.params.output.httpConnectionReused$.next(k),e.hostname$.next(ve(T))}),i(fe(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:T,availableFrom:P}}})=>{this.isLive$.next(T),this.availableFrom$.next(P.getTime()),T||e.duration$.next(m),this.videoTracks=[];const L=this.player.getQualityFor("video");let se;for(const k of this.player.getBitrateInfoListFor("video")){const E=k.qualityIndex.toString(10),I=ot(k),x=k.bitrate/1e3,ie={width:k.width,height:k.height},V=this.frameRatesByFrameHeight[k.height];if(I){const j={id:E,quality:I,bitrate:x,size:ie,fps:V};this.videoTracks.push({track:j,bitrateInfo:k}),k.qualityIndex===L&&(se=j)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:k})=>k)),se&&e.currentVideoTrack$.next(se),this.videoState.setState(Y.STREAM_INITIALIZED),this.videoState.startTransitionTo(Y.READY)}),i(fe(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const T=m.requestEndDate.getTime()-m.firstByteDate.getTime(),P=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(P,T)}),i(O(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=It(this.videoTracks.map(({track:L})=>L),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),P=this.videoTracks.find(({track:L})=>L===T);P?.bitrateInfo&&this.player.setQualityFor("video",P?.bitrateInfo.qualityIndex,!1)}),i(qe({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(U($))}).pipe(U(({isLive:m})=>m),v(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=fe(this.player,"playbackTimeUpdated").pipe(v(({time:m})=>m??0));i(qe({availableFrom:this.availableFrom$.pipe(U($)),currentTime:n}),({availableFrom:m,currentTime:T})=>this.params.output.liveTime$.next(m+T*1e3)),i(n.pipe(U(()=>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(()=>Bs(this.video.buffered,this.video.currentTime))),e.currentBuffer$),i(fe(this.player,"playbackPlaying"),()=>{this.videoState.setState(Y.PLAYING),w(t.playbackState,f.PLAYING)}),i(fe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),i(fe(this.player,"playbackPaused"),()=>{this.videoState.setState(Y.PAUSED),w(t.playbackState,f.PAUSED)}),i(fe(this.player,"canPlay"),()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY)}),i(this.isLive$,e.isLive$),i(qt(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));i(o,this.syncPlayback);const{playbackDuration$:c,ping$:d,connectionType$:u,connectionReused$:h}=Ti(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(v(m=>m<60))}),({isLive:m,isShort:T})=>{const P=!m&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:P}}})}),i(n.pipe(U(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(),nt(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(dt(this.video,t.isLooped,s));const{volumeState$:l,looped$:p,playbackRateState$:S}=ze(this.video);this.subscription.add(Ge(this.video,t.volume,l,s)),this.subscription.add(l.subscribe(e.volume$,s)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(et(this.video,t.playbackRate,S,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(Y.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Y.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,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(Y.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(e===Y.DOWNLOADING_LIB||e===Y.STREAM_INITIALIZED))switch(s?.to!==f.PAUSED&&i.state===B.Requested&&e!==Y.STOPPED&&t!==f.STOPPED&&(a?this.seek(i.position-this.liveOffset.getTotalPausedTime()):this.seek(i.position)),t){case f.STOPPED:{switch(e){case Y.STOPPED:break;case Y.PLAYING:case Y.PAUSED:case Y.READY:this.stop();break;default:N(e)}break}case f.PLAYING:{switch(e){case Y.PLAYING:break;case Y.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Y.READY:this.play();break;case Y.STOPPED:this.prepare();break;default:N(e)}break}case f.PAUSED:{switch(e){case Y.PLAYING:this.pause(),this.liveOffset.pause();break;case Y.PAUSED:break;case Y.READY:this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED);break;case Y.STOPPED:this.prepare();break;default:N(e)}break}default:N(t)}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy();try{this.player?.destroy()}catch{}this.video.remove(),this.params.output.element$.next(void 0),this.destroyBigRequest?.()}}var Ct=r=>{switch(r){case"mobile":return te.Q_144P;case"lowest":return te.Q_240P;case"low":return te.Q_360P;case"sd":case"medium":return te.Q_480P;case"hd":case"high":return te.Q_720P;case"fullhd":case"full":return te.Q_1080P;case"quadhd":case"quad":return te.Q_1440P;case"ultrahd":case"ultra":return te.Q_2160P}},tt=async r=>{const e=r.muted;try{await r.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;r.muted=!0;try{await r.play()}catch(s){return r.muted=!1,console.warn(s),!1}}return!0};function ye(){return ce()}function Os(r){return ye()-r}function ds(r){const e=r.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 Ni(r,e,t){const s=(...i)=>{t.apply(null,i),r.removeEventListener(e,s)};r.addEventListener(e,s)}function Ft(r,e,t,s){const i=window.XMLHttpRequest;let a,n,o,c=!1,d=0,u,h,l=!1,p="arraybuffer",S=7e3,m=2e3,T=()=>{if(c)return;A(u);const W=Os(u);let le;if(W<m){le=m-W,setTimeout(T,le);return}m*=2,m>S&&(m=S),n&&n.abort(),n=new i,I()};const P=W=>(a=W,ne),L=W=>(h=W,ne),se=()=>(p="json",ne),k=()=>{if(!c){if(--d>=0){T(),s&&s();return}c=!0,h&&h(),t&&t()}},E=W=>(l=W,ne),I=()=>{u=ye(),n=new i,n.open("get",r);let W=0,le,Le=0;const We=()=>(A(u),Math.max(u,Math.max(le||0,Le||0)));if(a&&n.addEventListener("progress",C=>{const X=ye();a.updateChunk&&C.loaded>W&&(a.updateChunk(We(),C.loaded-W),W=C.loaded,le=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>k())),n.addEventListener("load",()=>{if(c)return;A(n);const C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&a){const X=n.response.byteLength-W;X&&a.updateChunk&&a.updateChunk(We(),X)}h&&h(),n&&e(n.response)}else k()}),n.addEventListener("error",()=>{k()}),l){const C=()=>{A(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=ye(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=p,n.send(),ne},ne={withBitrateReporting:P,withParallel:E,withJSONResponse:se,withRetryCount:W=>(d=W,ne),withRetryInterval:(W,le)=>($(W)&&(m=W),$(le)&&(S=le),ne),withTimeout:W=>(o=W,ne),withFinally:L,send:I,abort:()=>{n&&(n.abort(),n=void 0),c=!0,h&&h()}};return ne}const Bi=100,Oi=2e3,Mi=500;let Ui=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-Mi;if(t-e>Oi){let s=0,i=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,i+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const c=a.bytes*n/o;i+=c,a.start=t,a.bytes-=c}}}if(i>0&&s>0){const a=i*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(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>Bi&&(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 Fi{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,s,i,a){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=i,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const 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)},a=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=Ft(t,a,()=>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 a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=i,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=i,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Bt=1e4,Ot=3,Vi=300,Hi=2e3,qi=6e4,Gi=10,Yi=1,zi=500;class Wi{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 Ui(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,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!i||a.bitrate>i.bitrate)&&(i=a):(!s||s.bitrate>a.bitrate)&&(s=a));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:a}=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=()=>{Ni(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Fi(Ot,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 a=!1,n=null,o=null,c=null,d=null,u=!1;const h=()=>{const k=a&&(!u||u===this.rep);return k||t("Not running!"),k},l=(k,E,I)=>{c&&c.abort(),c=Ft(this.urlResolver.resolve(k,!1),E,I,()=>this._retryCallback()).withTimeout(Bt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ot).withFinally(()=>{c=null}).send()},p=(k,E,I)=>{A(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),E,I,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},S=k=>{const E=s.playbackRate;s.playbackRate!==k&&(t(`Playback rate switch: ${E}=>${k}`),s.playbackRate=k)},m=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),T()},T=()=>{if(!this.lowLatency)S(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const I=ye()-6e4;let x=0;for(let V=0;V<this.bufferStates.length;V++){const j=this.bufferStates[V];k=Math.min(k,j.buf),j.ts<I&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${k} drop=${x} jitter=${this.sourceJitter}`);let ie=k-Yi;this.sourceJitter>=0?ie-=this.sourceJitter/2:this.sourceJitter-=1,ie>3?S(1.15):ie>1?S(1.1):ie>.3?S(1.01):S(1)}},P=k=>{let E;const I=()=>E&&E.start?E.start.length:0,x=C=>E.start[C]/1e3,ie=C=>E.dur[C]/1e3,V=C=>E.fragIndex+C,j=(C,X)=>({chunkIdx:V(C),startTS:x(C),dur:ie(C),discontinuity:X}),ne=()=>{let C=0;if(E&&E.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=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);C=Math.min(Ee,E.dur.length-1-ue),C=Math.max(C,0)}return j(C,!0)},W=C=>{const X=I();if(!(X<=0)){if($(C)){for(let ue=0;ue<X;ue++)if(x(ue)>C)return j(ue)}return ne()}},le=C=>{const X=I(),ue=C?C.chunkIdx+1:0,me=ue-E.fragIndex;if(!(X<=0)){if(!C||me<0||me-X>Gi)return t(`Resync: offset=${me} bChunks=${X} chunk=`+JSON.stringify(C)),ne();if(!(me>=X))return j(ue-E.fragIndex,!1)}},Le=(C,X,ue)=>{d&&d.abort(),d=Ft(this.urlResolver.resolve(C,!0,this.lowLatency),X,ue,()=>this._retryCallback()).withTimeout(Bt).withRetryCount(Ot).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(C,X)=>{Le(k,ue=>{if(!h())return;E=ue;const me=Boolean(E.lowLatency);me!==this.lowLatency&&m(me);let Ee=0;for(let Qe=0;Qe<E.dur.length;++Qe)Ee+=E.dur[Qe];Ee>0&&(A(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,C(W(X))},()=>this._handleNetworkError())},nextChunk:le}},L=()=>{a=!1,o&&o.abort(),c&&c.abort(),d&&d.abort(),A(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:k=>{const{videoElement:E,logger:I}=this.params;let x=P(e.jidxUrl),ie,V,j,ne,W=0,le,Le,We;const C=()=>{le&&(clearTimeout(le),le=void 0);const H=Math.max(zi,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=W+H,Se=ye(),be=Math.min(1e4,ge-Se);W=Se;const Me=()=>{d||h()&&x.seek(()=>{h()&&(W=ye(),X(),C())})};be>0?le=window.setTimeout(()=>{this.paused?C():Me()},be):Me()},X=()=>{let H;for(;H=x.nextChunk(ne);)ne=H,gt(H);const ge=x.nextChunk(j);if(ge){if(j&&ge.discontinuity){I("Detected discontinuity; restarting playback"),this.paused?C():(L(),this._initPlayerWith(e));return}Qe(ge)}else C()},ue=(H,ge)=>{if(!h()||!this.sourceBuffer)return;let Se,be,Me;const Ue=De=>{window.setTimeout(()=>{h()&&ue(H,ge)},De)};if(this.sourceBuffer.updating)I("Source buffer is updating; delaying appendBuffer"),Ue(100);else{const De=ye(),je=E.currentTime;!this.paused&&E.buffered.length>1&&Le===je&&De-We>500&&(I("Stall suspected; trying to fix"),this._fixupStall()),Le!==je&&(Le=je,We=De);const Je=this._getBufferSizeSec();if(Je>30)I(`Buffered ${Je} seconds; delaying appendBuffer`),Ue(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:De,buf:Je}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Ke){if(Ke.name==="QuotaExceededError")I("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(Se=this.sourceBuffer.buffered.start(0),be=je,be-Se>4&&this.sourceBuffer.remove(Se,be-3)),Ue(1e3);else throw Ke}}},me=()=>{V&&ie&&(I([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(j)]),ue(V,function(){V=null,X()}))},Ee=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),Qe=H=>{h()&&p(Ee(H),(ge,Se)=>{if(h()){if(Se/=1e3,V=ge,j=H,n=H.startTS,Se){const be=Math.min(10,H.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}me()}},()=>this._handleNetworkError())},gt=H=>{h()&&(A(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(H),!1)))},xt=H=>{h()&&(e.cachedHeader=H,ue(H,()=>{ie=!0,me()}))};a=!0,x.seek(H=>{if(h()){if(W=ye(),!H){C();return}ne=H,!z(k)||H.startTS>k?Qe(H):(j=H,X())}},k),e.cachedHeader?xt(e.cachedHeader):l(e.headerUrl,xt,()=>this._handleNetworkError())},stop:L,getTimestampSec:()=>n},u}_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,A(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 l,p,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),S=h/this.bitrate,p>10&&S>.8||p>15&&S>.5||p>20&&S>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}l=this._selectQuality(h),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${h}`)},a=(()=>({updateChunk:(l,p)=>{const S=ye();if(this.chunkRateEstimator.addInterval(l,S,p)){const T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:S-l,speed:T}),!0}},get:()=>{const l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}}))();let n=-1/0,o,c=!0;const d=()=>{let h=a.get();if(h&&o&&this.autoQuality){if(c&&h>o&&Os(n)<3e4)return;s(h)}c=this.autoQuality};return{updateChunk:(h,l)=>{const p=a.updateChunk(h,l);return p&&d(),p},notifySwitch:h=>{const l=ye();h<o&&(n=l),o=h}}}_fetchManifest(e,t,s){this.manifestRequest=Ft(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Bt).withRetryCount(Ot).withRetryInterval(Vi,Hi).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;tt(t).then(s=>{s||e?.()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:i}=this.params,a=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=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},qi))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var F;(function(r){r.STOPPED="stopped",r.MANIFEST_READY="manifest_ready",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(F||(F={}));const Qi=[F.PAUSED,F.PLAYING,F.READY],ji=[F.PAUSED,F.PLAYING,F.READY];class Ji{subscription=new K;video;videoState=new ae(F.STOPPED);dash;representations$=new g([]);textTracksManager=new Oe;maxSeekBackTime$=new g(1/0);zeroTime$=new g(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:_.WTF,message:"DashLiveProvider internal logic error",thrown:i})};O(this.videoState.stateChangeStarted$.pipe(v(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(v(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(i)}`})}),this.video=Ye(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.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===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(F.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(he(),v(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(qe({zeroTime:this.zeroTime$.pipe(U($)),position:s.timeUpdate$}).subscribe(({zeroTime:i,position:a})=>this.params.output.liveTime$.next(i+a*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(Ge(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(et(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:i}})=>{const a=i&&ui(i);this.dash.setMaxAutoQuality(a)})).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(f.STOPPED);break;case F.MANIFEST_READY:case F.READY:break;case F.PAUSED:this.params.desiredState.playbackState.setState(f.PAUSED);break;case F.PLAYING:this.params.desiredState.playbackState.setState(f.PLAYING);break;default:return N(i.to)}},t)).add(O(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Wi({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},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:It(e.map(({track:n})=>n),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()})?.id,a=e.find(({track:n})=>n.id===i)?.representation;A(a,"Representations missing"),this.dash.startPlay(a,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;A(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.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:_.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,s=[];for(const i of t){const a=i.name??i.index.toString(10),n=Ct(i.name)??ot(i.video),o=i.bitrate/1e3,c={...i.video};if(!n)continue;const d={id:a,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===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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(a)};`}),s===f.STOPPED){e!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(F.STOPPED));return}if(!t){if(ji.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!==f.PAUSED&&a.state===B.Requested&&Qi.includes(e)){this.seek(a.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:s===f.PAUSED?this.videoState.setState(F.PAUSED):s===f.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(F.PAUSED)}));return;case F.PLAYING:s===f.PAUSED&&(this.videoState.startTransitionTo(F.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case F.PAUSED:s===f.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 Ms=r=>{const e=r.get("X-Delivery-Type"),t=r.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}},lt=(r,e)=>{let t=0;for(let s=0;s<r.length;s++){const i=r.start(s)*1e3,a=r.end(s)*1e3;i<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Ki=r=>{const e=document.createElement("a");return e.href=r,e.origin},Xi=r=>{const e=document.createElement("a");return e.href=r,e.host};class Us{_failoverIndex=0;_failoverCount=0;_xhr=null;_url;_failoverHosts;_completeCb;_progressCb;_headersCb;_errorCb;_retryTimeout=0;constructor(e,t=[],s,i,a,n){this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=i,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{if(A(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(Xi(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 Gt{_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 a=0;for(let n=0,o=i.length;n<o;n++)a+=i.end(n)-i.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,i,a,n,o){this.abort(()=>{let c=0;const d=Date.now();let u=0,h=0,l=0;const p=m=>{i(Gt._str2ua(m.substr(c))),c=m.length};let S=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(S=mt(S)),this._lastXhr=new Us(S,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const T=Date.now()-d;this._params.onBandwidthChange({size:m.length,duration:T,speed:8*m.length/(T/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),a?.()},m=>{if(m.length-c>o&&p(m),h===0){h=Date.now();return}l=m.length-u;const T=Date.now()-h;l>=100*1024&&T>=1e3&&(this._params.onBandwidthChange({size:l,duration:T,speed:8*l/(T/1e3)}),l=0,u=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},n,(m,T,P)=>this._params.onError(m,T,P))})}abort(e){this._lastXhr?.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e?.()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Gt._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 Zi{_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),a=i?.[1]==="-"?-1:1,n={years:s(i?.[2],a),months:s(i?.[3],a),weeks:s(i?.[4],a),days:s(i?.[5],a),hours:s(i?.[6],a),minutes:s(i?.[7],a),seconds:s(i?.[8],a)};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 Us(s,t,i=>{this.attachManifest(i,t,Ki(s))},void 0,i=>{this._params.onResponseHeaders(i)},(i,a,n)=>this._params.onError(i,a,n))}attachManifest(e,t,s){const a=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(a,"mediaPresentationDuration")));const o=[],c=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{const u=d.getElementsByTagName("SegmentBase")[0],h=u&&n(u,"indexRange").split("-"),l=u&&u.getElementsByTagName("Initialization")[0],p=l&&n(l,"range").split("-");if(!p||!h){const se=d.parentElement;if(se?.getAttribute("contentType")==="text"){const k=d.getAttribute("id")??void 0,E=(s?s+"/":"")+d.getElementsByTagName("BaseURL")?.[0]?.childNodes?.[0]?.data,I=se.getAttribute("lang")??void 0;E&&c.push({id:k,url:E,language:I})}return}const S=.1,m=Number(d.attributes.getNamedItem("bandwidth")?.value),T=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let P;const L=d.attributes.getNamedItem("frameRate")?.value??void 0;P=L?ts(L):void 0,o.push({width:Number(d.attributes.getNamedItem("width")?.value),height:Number(d.attributes.getNamedItem("height")?.value),bandwidth:m,baseURL:T,failoverHosts:t,indexFrom:Number(h[0]),indexTo:Number(h[1]),initFrom:Number(p[0]),initTo:Number(p[1]),codecs:d.attributes.getNamedItem("codecs")?.value??void 0,mimeType:d.attributes.getNamedItem("mimeType")?.value??void 0,fps:P,bufferSize:S*m/8,bufferLength:S,name:d.attributes.getNamedItem("okQuality")?.value??void 0,id:d.attributes.getNamedItem("id")?.value??void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}c.forEach(({id:d,language:u,url:h})=>{const l=document.createElement("track");l.setAttribute("src",h),d&&l.setAttribute("id",d),u&&l.setAttribute("srclang",u),this._video.appendChild(l)}),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 a=e.initTo-e.initFrom+1;if(!i.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(i.buffer,0,a);const n=new DataView(i.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let c=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const u=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let l=0;l<u;l+=1){const p=d+(n.getUint32(a,!1)&2147483647),S=c+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:c/o,toTime:S/o,fromOffset:d,toOffset:p-1}),d=p,c=S}const 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,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const u=this._appendVector[String(d.fromTime)];u!==i&&(i=u,this._params.onRepresentationPlay(u));let h;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const S=this._buffer.getNextWithGap(p);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},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 Gt({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 a=this._findRef(t);if(a){if(s){this._isLastRef(a)&&t>=a.toTime&&(t=a.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||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const 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 a=.1;if(i.toTime<s.to+a){const n=this._findRef(i.toTime);n&&n.toTime<s.to+a?(this._buffer.smartRemove(i.fromTime-a,n.toTime+a,(o,c)=>this._stream.remove(o,c)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(i.fromTime-a,i.toTime+a,(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||z(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 a=t[i];if(a.fromTime<=e&&a.toTime>e)return a;a.fromTime>e&&(!s||a.fromTime<s.fromTime)&&(s=a)}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 q;(function(r){r.STOPPED="stopped",r.MANIFEST_LOADED="manifest-loaded",r.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",r.METADATA_LOADED="metadata-loaded",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(q||(q={}));const er=[q.PAUSED,q.PLAYING];class tr{videoState=new ae(q.STOPPED);subscription=new K;video;buffer;dash;representations$=new g([]);currentRepresentation$=new g(void 0);params;textTracksManager=new Oe;elementSize$=new g(void 0);dashLiteEvents={idxRequestPing$:new D,responseHeaders$:new D,manifestReady$:new D,representationPlay$:new D,error$:new D};log;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),O(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=Ye(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.source.type==="url"&&this.params.output.hostname$.next(ve(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Ai(this.video),this.dash=new Zi({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:_.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:_.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},a=ze(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),this.subscription.add(a.seeking$.subscribe(()=>{z(this.params.desiredState.seekState.getState().state!==B.Applying)&&(this.videoState.getState()===q.PLAYING||this.videoState.getState()===q.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(qt(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===q.READY&&this.videoState.setState(q.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),w(this.params.desiredState.playbackState,f.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(q.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe(v(({id:o,message:c,thrown:d})=>({id:`DashLite_${o}`,category:_.WTF,message:c,thrown:d}))).subscribe(this.params.output.error$)).add(O(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,M(this.video,"progress")).pipe(v(()=>{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(),l=this.elementSize$.getValue(),p=i();d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to);let S;if(!p&&$(u))S=u;else{const m=lt(this.video.buffered,this.video.currentTime*1e3),T=p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,P=Math.min(m/T,1);S=It(c.map(({track:L})=>L),{container:l,throughput:h,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:P,playbackRate:this.video.playbackRate,current:c.find(({representation:L})=>L===o)?.track})?.id}return $(S)?c.find(({track:m})=>m.id===S)?.representation:void 0}),he()).subscribe(this.currentRepresentation$,s)).add(qe({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(U(o=>o.to===q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(U($))}).pipe(pe()).subscribe(()=>this.videoState.setState(q.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(U($),he((o,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&i()?o.height<=c.height:o===c)).subscribe(o=>{const c=lt(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}=Ms(o);this.params.output.httpConnectionType$.next(c),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(pe(),nt(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(U($)).subscribe(this.handleRepresentationPlay,s)).add(O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return N(e)}}handleManifestReady=e=>{const t=[];for(const s of e){const i=s.name??s.id??s.height.toString(10),a=(s.name&&Ct(s.name))??ot(s),n=s.bandwidth/1e3,o={width:s.width,height:s.height},c=s.fps;if(!a)continue;const d={id:i,quality:a,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(q.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 A(e,"Can't select representation. something went wrong"),e};seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(a)};`}),s===f.STOPPED){e!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(!t)switch(i?.to!==f.PAUSED&&a.state===B.Requested&&er.includes(e)&&this.seek(a.position,a.forcePrecise),e){case q.STOPPED:this.videoState.startTransitionTo(q.MANIFEST_LOADED),this.prepare();return;case q.MANIFEST_LOADED:this.videoState.startTransitionTo(q.INITIAL_REPRESENTATION_SELECTED);return;case q.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(q.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case q.METADATA_LOADED:this.videoState.startTransitionTo(q.READY),this.dash.updateRefsForCurrentTime();return;case q.READY:s===f.PAUSED?(this.videoState.setState(q.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):s===f.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:s===f.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):i?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case q.PAUSED:s===f.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):i?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}var we;(function(r){r.VIDEO="video",r.AUDIO="audio",r.TEXT="text"})(we||(we={}));var Yt;(function(r){r.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",r.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Yt||(Yt={}));var Pe;(function(r){r.BYTE_RANGE="byteRange",r.TEMPLATE="template"})(Pe||(Pe={}));var Q;(function(r){r.NONE="none",r.DOWNLOADING="downloading",r.DOWNLOADED="downloaded",r.PARTIALLY_FED="partially_fed",r.PARTIALLY_EJECTED="partially_ejected",r.FED="fed"})(Q||(Q={}));var St;(function(r){r.MP4="mp4",r.WEBM="webm"})(St||(St={}));var cs=(r,e)=>{for(let t=0;t<r.length;t++)if(r.start(t)*1e3<=e&&r.end(t)*1e3>e)return!0;return!1};const sr=(r,e={})=>{const s=e.timeout||1,i=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-i-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},ir=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",us=ir?sr:window.requestIdleCallback;let Fs=!1;try{Fs=Ns()&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(r){console.error(r)}class rr{bufferFull$=new D;error$=new D;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 a={operation:"remove",from:e,to:t,signal:s,callback:i};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let s;Fs&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:i}of this.queue)i(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:_.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:_.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 hs=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};const Vs=new TextDecoder("ascii"),Hs=r=>{let e=0,t=r.getUint32(e);e+=4;const s=new DataView(r.buffer,r.byteOffset+e,4),i=Vs.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,r.byteLength)-e,n=new DataView(r.buffer,r.byteOffset+e,a);return{id:i,size:t,contents:n}},ar=r=>Vs.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",nr=r=>{const e=Hs(r),t=[];let s=0;const i=()=>{const p=e.contents.getUint32(s);return s+=4,p};if((i()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");i();const o=i(),c=i(),d=i(),u=i()&4294967295;let h=c/o*1e3,l=r.byteOffset+r.byteLength+d;for(let p=0;p<u;p++){const S=i(),m=S>>>31,T=S<<1>>>1,P=i();if(i(),m!==0)throw new Error("Unsupported multilevel sidx");const L=P/o*1e3;t.push({status:Q.NONE,time:{from:h,to:h+L},byte:{from:l,to:l+T-1}}),h+=L,l+=T}return t},or=r=>{let e=0,t=!1,s=!1;for(;e<=r.byteLength&&!t;){const i=new DataView(r.buffer,r.byteOffset+e);try{const a=Hs(i);if(s||=a.id==="mdat",e+a.size<=r.byteLength)e+=a.size;else break}catch{t=!0}}return e>0&&e<=r.byteLength&&s?new DataView(r.buffer,r.byteOffset,e):null},dr={validateData:ar,parseInit:()=>null,getIndexRange:()=>{},parseSegments:nr,parseFeedableSegmentChunk:or};var y;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.Duration=17545]="Duration",r[r.Tracks=374648427]="Tracks",r[r.Chapters=272869232]="Chapters",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.SilentTracks=22612]="SilentTracks",r[r.SilentTrackNumber=22743]="SilentTrackNumber",r[r.Position=167]="Position",r[r.PrevSize=171]="PrevSize",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.EncryptedBlock=175]="EncryptedBlock",r[r.Attachments=423732329]="Attachments",r[r.Tags=307544935]="Tags",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.CueRelativePosition=240]="CueRelativePosition",r[r.CueDuration=178]="CueDuration",r[r.CueBlockNumber=21368]="CueBlockNumber",r[r.CueCodecState=234]="CueCodecState",r[r.CueReference=219]="CueReference",r[r.CueRefTime=150]="CueRefTime"})(y||(y={}));var R;(function(r){r.SignedInteger="int",r.UnsignedInteger="uint",r.Float="float",r.String="string",r.UTF8="utf8",r.Date="date",r.Master="master",r.Binary="binary"})(R||(R={}));const ls={[y.EBML]:{type:R.Master},[y.EBMLVersion]:{type:R.UnsignedInteger},[y.EBMLReadVersion]:{type:R.UnsignedInteger},[y.EBMLMaxIDLength]:{type:R.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:R.UnsignedInteger},[y.DocType]:{type:R.String},[y.DocTypeVersion]:{type:R.UnsignedInteger},[y.DocTypeReadVersion]:{type:R.UnsignedInteger},[y.Void]:{type:R.Binary},[y.Segment]:{type:R.Master},[y.SeekHead]:{type:R.Master},[y.Seek]:{type:R.Master},[y.SeekID]:{type:R.Binary},[y.SeekPosition]:{type:R.UnsignedInteger},[y.Info]:{type:R.Master},[y.TimestampScale]:{type:R.UnsignedInteger},[y.Duration]:{type:R.Float},[y.Tracks]:{type:R.Master},[y.Chapters]:{type:R.Master},[y.Cluster]:{type:R.Master},[y.Timestamp]:{type:R.UnsignedInteger},[y.SilentTracks]:{type:R.Master},[y.SilentTrackNumber]:{type:R.UnsignedInteger},[y.Position]:{type:R.UnsignedInteger},[y.PrevSize]:{type:R.UnsignedInteger},[y.SimpleBlock]:{type:R.Binary},[y.BlockGroup]:{type:R.Master},[y.EncryptedBlock]:{type:R.Binary},[y.Attachments]:{type:R.Master},[y.Tags]:{type:R.Master},[y.Cues]:{type:R.Master},[y.CuePoint]:{type:R.Master},[y.CueTime]:{type:R.UnsignedInteger},[y.CueTrackPositions]:{type:R.Master},[y.CueTrack]:{type:R.UnsignedInteger},[y.CueClusterPosition]:{type:R.UnsignedInteger},[y.CueRelativePosition]:{type:R.UnsignedInteger},[y.CueDuration]:{type:R.UnsignedInteger},[y.CueBlockNumber]:{type:R.UnsignedInteger},[y.CueCodecState]:{type:R.UnsignedInteger},[y.CueReference]:{type:R.Master},[y.CueRefTime]:{type:R.UnsignedInteger}},qs=r=>{const e=r.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=zt(r,t),i=s in ls,a=i?ls[s].type:R.Binary,n=r.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const c=new DataView(r.buffer,r.byteOffset+t+1,o-1),d=((n&255>>o)<<(o-1)*8)+zt(c),u=t+o;let h;return u+d>r.byteLength?h=new DataView(r.buffer,r.byteOffset+u):h=new DataView(r.buffer,r.byteOffset+u,d),{tag:i?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:u,tagSize:u+d,value:h,valueSize:d}},zt=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint16(0)<<8|r.getUint8(2);case 4:return r.getUint32(0);case 5:return r.getUint32(0)<<8|r.getUint8(4);case 6:return r.getUint32(0)<<16|r.getUint16(4);case 7:return r.getUint32(0)<<32|r.getUint16(4)<<8|r.getUint8(6);case 8:return r.getUint32(0)<<32|r.getUint32(4)}return 0},He=(r,e)=>{switch(e){case R.SignedInteger:return r.getInt8(0);case R.UnsignedInteger:return zt(r);case R.Float:return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case R.String:return new TextDecoder("ascii").decode(r);case R.UTF8:return new TextDecoder("utf-8").decode(r);case R.Date:return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case R.Master:return r;case R.Binary:return r;default:N(e)}},Lt=(r,e)=>{let t=0;for(;t<r.byteLength;){const s=new DataView(r.buffer,r.byteOffset+t),i=qs(s);if(!e(i))return;i.type===R.Master&&Lt(i.value,e),t=i.value.byteOffset-r.byteOffset+i.valueSize}},cr=r=>{if(r.getUint32(0)!==y.EBML)return!1;let e,t,s;const i=qs(r);return Lt(i.value,({tag:a,type:n,value:o})=>(a===y.EBMLReadVersion?e=He(o,n):a===y.DocType?t=He(o,n):a===y.DocTypeReadVersion&&(s=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Gs=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],ur=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],hr=r=>{let e,t,s,i,a=!1,n=!1,o=!1,c,d;return Lt(r,({tag:u,type:h,value:l,valueSize:p})=>{if(u===y.SeekID){const S=He(l,h);d=zt(S)}else u!==y.SeekPosition&&(d=void 0);return u===y.Segment?(e=l.byteOffset,t=l.byteOffset+p):u===y.Info?a=!0:u===y.SeekHead?n=!0:u===y.TimestampScale?s=He(l,h):u===y.Duration?i=He(l,h):u===y.SeekPosition&&d===y.Cues?c=He(l,h):a&&n&&Gs.includes(u)&&(o=!0),!o}),A(e,"Failed to parse webm Segment start"),A(t,"Failed to parse webm Segment end"),A(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}},lr=r=>{if(z(r.cuesSeekPosition))return;const e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},fr=(r,e)=>{let t=!1,s=!1;const i=o=>$(o.time)&&$(o.position),a=[];let n;return Lt(r,({tag:o,type:c,value:d})=>{switch(o){case y.Cues:t=!0;break;case y.CuePoint:n&&i(n)&&a.push(n),n={};break;case y.CueTime:n&&(n.time=He(d,c));break;case y.CueTrackPositions:break;case y.CueClusterPosition:n&&(n.position=He(d,c));break;default:t&&Gs.includes(o)&&(s=!0)}return!(t&&s)}),n&&i(n)&&a.push(n),a.map((o,c)=>{const{time:d,position:u}=o,h=a[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}}})},pr=r=>{let e=0,t=!1;try{Lt(r,s=>s.tag===y.Cluster?s.tagSize<=r.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):ur.includes(s.tag)?(e+s.tagSize<=r.byteLength&&(e+=s.tagSize,t||=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(s.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},mr={validateData:cr,parseInit:hr,getIndexRange:lr,parseSegments:fr,parseFeedableSegmentChunk:pr};class fs{onLastSegment$=new g(!1);fullyBuffered$=new g(!1);playingRepresentation$=new g(void 0);error$=new D;gaps=[];subscription=new K;kind;container;containerParser;initData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new rt;destroyAbortController=new rt;getCurrentPosition;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;constructor(e,t,s,i,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:c=!1}){switch(this.fetcher=a,this.tuning=n,this.compatibilityMode=c,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case St.MP4:this.containerParser=dr;break;case St.WEBM:this.containerParser=mr;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=_e(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);A(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new rr(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>this.checkEjectedSegments(),n=>this.error$.next({id:"SegmentEjection",category:_.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_.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,hs(this.sourceBuffer.buffered));this.bufferLimit=o,this.pruneBuffer(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(A(s,"No init buffer for starting representation"),A(i,"No segments for starting representation"),!(s instanceof ArrayBuffer))return;let a=0;for(const n of i)n.time.from-a>0&&this.gaps.push({representation:t.id,from:a,to:n.time.from}),a=n.time.to;$(t.duration)&&t.duration-a>0&&this.gaps.push({representation:t.id,from:a,to:t.duration}),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this));switchTo=_e(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);A(t,`No such representation ${e}`);let s=this.initData.get(e);if(z(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 rt,this.abortBuffer()}maintain(e){if(z(this.downloadingRepresentationId)||z(this.playingRepresentationId)||z(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(A(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const i=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=lt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&u>=i.time.to-e+100&&(a=h)}if(isFinite(this.bufferLimit)&&hs(this.sourceBuffer.buffered)>=this.bufferLimit*.8&&(this.pruneBuffer(1/0),i&&i.status!==Q.NONE))return;let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),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.allInitsLoaded&&i&&i.status===Q.FED&&!o.length&<(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(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=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:c,time:{from:d,to:u}})=>c===Q.NONE&&(d>s||d<=s&&u>=s)&&u<=s+this.forwardBufferTarget);if(i===-1)return[];if(t!==Pe.BYTE_RANGE)return e.slice(i,i+1);const a=e;let n=0;const o=[];for(let c=i;c<a.length&&n<=this.tuning.dash.segmentRequestSize;c++){const d=a[c];if(n+=d.byte.to+1-d.byte.from,d.status===Q.NONE||d.status===Q.PARTIALLY_EJECTED)o.push(d);else break}return o}async loadSegments(e,t,s="auto"){if(!e.length)return;let i,a,n=e;const{type:o}=t.segmentReference;switch(o){case Pe.BYTE_RANGE:{i=t.segmentReference.url,a={from:e.at(0).byte.from,to:e.at(-1).byte.to};break}case Pe.TEMPLATE:{const d=e.at(0);i=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default: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:c}=this.downloadAbortController;if(this.failedDownloads&&(await _e(c,async function*(){const d=as(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:a,onProgress:(d,u)=>{if(!c.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,u,c)}catch(h){this.error$.next({id:"SegmentFeeding",category:_.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&&$(s)&&(t=lt(this.sourceBuffer?.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:_.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,i,a){if(!this.activeSegments.size)return;const n=h=>{this.abortSegment(h.segment)},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 l of this.representations.values())if(l.id!==t)for(const p of this.segments.get(l.id)??[])p.status===Q.FED&&p.time.from===h.segment.time.from&&p.time.to===h.segment.time.to&&(p.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:l}=h,p=d===Pe.BYTE_RANGE,S=p?l.byte.to-l.byte.from+1:u;if(h.representationId!==t||!(!p||l.byte.from>=s&&l.byte.to<s+e.byteLength))continue;if(a.aborted){n(h);continue}const T=p?l.byte.from-s:0,P=p?l.byte.to-s:e.byteLength,L=T<i,se=P<=i;if(l.status===Q.DOWNLOADING&&L&&se){l.status=Q.DOWNLOADED,this.activeSegments.delete(h);const k=new DataView(e.buffer,e.byteOffset+T,S);this.sourceBufferTaskQueue.append(k,a).then(E=>E&&!a.aborted?o(h):n(h))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&L&&(h.loadedBytes=Math.min(S,i-T),h.loadedBytes>h.feedingBytes)){const k=new DataView(e.buffer,e.byteOffset+T+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===S?k:this.containerParser.parseFeedableSegmentChunk(k);E?.byteLength&&(l.status=Q.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then(I=>{if(a.aborted)n(h);else if(I)h.fedBytes+=E.byteLength,h.fedBytes===S&&o(h);else{if(h.feedingBytes<S)return;n(h)}}))}}}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,a]of this.initData.entries()){const n=a instanceof Promise;t||=n,a===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=us(()=>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?_e(this.destroyAbortController.signal,async function*(){const o=as(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:_.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e){const t=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||z(t)||this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let i=0,a=1/0,n=-1/0,o=!1;const c=d=>{a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const u="size"in d?d.size??0:d.byte.to-d.byte.from;i+=u};for(const d of s){if(d.time.to>=t||i>=e)break;d.status===Q.FED&&c(d)}if(o=isFinite(a)&&isFinite(n),!o){i=0,a=1/0,n=-1/0;for(const d of s){if(d.time.from<t+this.forwardBufferTarget||i>e)break;d.status===Q.FED&&c(d)}}if(o=isFinite(a)&&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 l of s)if(l.status===Q.NONE&&Math.round(l.time.from)<=Math.round(u)&&Math.round(l.time.to)>=Math.round(h)){a=u,n=h;break}}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=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.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=us(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:_.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(z(this.sourceBuffer)||z(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),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:i,to:a})}const t=1;for(const s of this.segments.values())for(const i of s){const{status:a}=i;if(a!==Q.FED&&a!==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.some(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);c||(d?i.status=Q.PARTIALLY_EJECTED:i.status=Q.NONE)}}}var ut;(function(r){r[r.HEADER=0]="HEADER",r[r.PARAM=1]="PARAM"})(ut||(ut={}));class Sr{throughputEstimator;requestQuic;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);abortAllController=new rt;subscription=new K;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Ms(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchManifest=_e(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=mt(t));const s=yield pt(t,{signal:this.abortAllController.signal}).catch($t);return s?(this.onHeadersReceived(s.headers),s.text()):null}.bind(this));fetch=_e(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?ut.HEADER:ut.PARAM,range:s,onProgress:i,priority:a="auto",signal:n,measureThroughput:o=!0}={}){let c=e;const d=new Headers;if(s)switch(t){case ut.HEADER:{d.append("Range",`${s.from}-${s.to}`);break}case ut.PARAM:{const V=new URL(c,location.href);V.searchParams.append("bytes",`${s.from}-${s.to}`),c=V.toString();break}default:N(t)}this.requestQuic&&(c=mt(c));let u=this.abortAllController.signal;if(n){const V=new rt;if(this.subscription.add(O(M(this.abortAllController.signal,"abort"),M(n,"abort")).subscribe(()=>{try{V.abort()}catch(j){$t(j)}})),this.abortAllController.signal.aborted||n.aborted)try{V.abort()}catch(j){$t(j)}u=V.signal}const h=ce(),l=yield pt(c,{priority:a,headers:d,signal:u}).catch($t),p=ce();if(this.throughputEstimator?.addRawRtt(p-h),!l)return null;if(!l.ok||!l.body)return Promise.reject(new Error(`Fetch error ${l.status}: ${l.statusText}`));this.onHeadersReceived(l.headers);const S=parseInt(l.headers.get("Content-Length")??"",10)||s&&s.to-s.from+1||NaN;if(!S){const V=yield l.arrayBuffer();return this.throughputEstimator?.addRawSpeed(V.byteLength,ce()-p),i?.(new DataView(V),V.byteLength),V}if(!i&&!o)return l.arrayBuffer();const[m,T]=l.body.tee(),P=m.getReader();o&&this.throughputEstimator?.trackStream(T);let L=0;const se=new ArrayBuffer(S),k=new Uint8Array(se),E=new DataView(se);let I=!1;const x=V=>{I=!0,$t(V)},ie=_e(u,async function*({done:V,value:j}){L===0&&this.lastRequestFirstBytes$.next(ce()-h),!u.aborted&&(V?i?.(E,L):j&&(k.set(j,L),L+=j.byteLength,i?.(E,L),yield P?.read().then(ie,x)))}.bind(this));return yield P?.read().then(ie,x),I?null:se}.bind(this));async fetchRepresentation(e,t,s="auto"){const{type:i}=e;switch(i){case Pe.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,s)??null;case Pe.TEMPLATE:return await this.fetchTemplateRepresentation(e,s)??null;default:N(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=_e(this.abortAllController.signal,async function*(e,t,s){if(e.type!==Pe.BYTE_RANGE)return null;const{from:i,to:a}=e.initRange;let n=i,o=a,c=!1,d,u;e.indexRange&&(d=e.indexRange.from,u=e.indexRange.to,c=a+1===d,c&&(n=Math.min(d,i),o=Math.max(u,a))),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 l=new DataView(h,i-n,a-n+1);if(!t.validateData(l))throw new Error("Invalid media file");const p=t.parseInit(l);let S;if(c&&d!==void 0&&u!==void 0)S=new DataView(h,d-n,u-d+1);else{const T=t.getIndexRange(p);if(T){const P=yield this.fetch(e.url,{range:T,priority:s,measureThroughput:!1});if(!P)return null;S=new DataView(P)}}if(!S)throw new ReferenceError("No way to load representation index");const m=t.parseSegments(S,p);return{dataView:new DataView(h),segments:m}}.bind(this));fetchTemplateRepresentation=_e(this.abortAllController.signal,async function*(e,t){if(e.type!==Pe.TEMPLATE)return null;const s=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(s,{priority:t,measureThroughput:!1});return i?{segments:e.segments.map(n=>({...n,status:Q.NONE,size:void 0})),dataView:new DataView(i)}:null}.bind(this))}const $t=r=>{if(!(r instanceof DOMException)||!(r.name==="AbortError"||r.code===20))throw r},ps=r=>{if(!r.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(r),i=s?.[1]==="-"?-1:1,a={days:e(s?.[5],i),hours:e(s?.[6],i),minutes:e(s?.[7],i),seconds:e(s?.[8],i)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Jt=(r,e)=>{let t=r;t=t.replaceAll("$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[i,a]of Object.entries(s)){const n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(n,(o,c)=>z(a)?o:z(c)?a:a.padStart(parseInt(c,10),"0"))}return t},gr=(r,e)=>{const s=new DOMParser().parseFromString(r,"application/xml"),i={video:[],audio:[],text:[]},a=s.children[0],n=a.getElementsByTagName("Period")[0],o=n.children;let c;const d=a.getAttribute("mediaPresentationDuration"),u=n.getAttribute("duration");if(d)c=ps(d);else if(u){const S=ps(u);$(S)&&(c=S)}let h=0;const l=a.getAttribute("profiles")?.split(",")??[],p=l.includes(Yt.WEBM_AS_IN_FFMPEG)||l.includes(Yt.WEBM_AS_IN_SPEC)?St.WEBM:St.MP4;for(const S of o){const m=S.getAttribute("mimeType"),T=S.getAttribute("codecs"),P=S.getAttribute("contentType")??m?.split("/")[0],L=S.getAttribute("profiles")?.split(",")??[],se=S.querySelectorAll("Representation"),k=S.querySelector("SegmentTemplate");if(P!=="text")for(const E of se){const I=E.getAttribute("mimeType")??m,x=E.getAttribute("codecs")??T??"",ie=E.getAttribute("contentType")??I?.split("/")[0]??P,V=S.getAttribute("profiles")?.split(",")??[],j=parseInt(E.getAttribute("width")??"",10),ne=parseInt(E.getAttribute("height")??"",10),W=parseInt(E.getAttribute("bandwidth")??"",10)/1e3,le=E.getAttribute("frameRate")??"",Le=E.getAttribute("quality")??void 0,We=le?ts(le):void 0,C=E.getAttribute("id")??(h++).toString(10),X=ie==="video"?`${ne}p`:ie==="audio"?`${W}Kbps`:x,ue=`${C}@${X}`,me=E.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(me,e).toString(),Qe=[...l,...L,...V];let gt;const xt=E.querySelector("SegmentBase"),H=E.querySelector("SegmentTemplate")??k;if(xt){const Se=E.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[be,Me]=Se.split("-").map(st=>parseInt(st,10)),Ue={from:be,to:Me},De=E.querySelector("SegmentBase")?.getAttribute("indexRange"),[je,Je]=De?De.split("-").map(st=>parseInt(st,10)):[],Ke=De?{from:je,to:Je}:void 0;gt={type:Pe.BYTE_RANGE,url:Ee,initRange:Ue,indexRange:Ke}}else if(H){const Se={representationId:E.getAttribute("id")??void 0,bandwidth:E.getAttribute("bandwidth")??void 0},be=parseInt(H.getAttribute("timescale")??"",10),Me=H.getAttribute("initialization")??"",Ue=H.getAttribute("media"),De=parseInt(H.getAttribute("startNumber")??"",10)??1,je=Jt(Me,Se);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Je=H.querySelectorAll("SegmentTimeline S")??[],Ke=[];if(Je.length){let st=De,it=0;for(const bt of Je){const ct=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=Jt(Ue,{...Se,segmentNumber:st.toString(10),segmentTime:Tt.toString(10)}),js=Tt?Tt/be:it;it+=ct/be;const Js=it;st++,Ke.push({time:{from:js,to:Js},url:Qs})}}}else if($(c)){const it=parseInt(H.getAttribute("duration")??"",10)/be*1e3,bt=Math.ceil(c/it);let ct=0;for(let yt=1;yt<bt;yt++){const Tt=Jt(Ue,{...Se,segmentNumber:yt.toString(10),segmentTime:ct.toString(10)});Ke.push({time:{from:ct,to:ct+it},url:Tt}),ct+=it}}gt={type:Pe.TEMPLATE,baseUrl:Ee,initUrl:je,segments:Ke}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ie||!I)continue;const ge={video:we.VIDEO,audio:we.AUDIO,text:we.TEXT}[ie];ge&&i[ge].push({id:ue,kind:ge,segmentReference:gt,profiles:Qe,duration:c,bitrate:W,mime:I,codecs:x,width:j,height:ne,fps:We,quality:Le})}}return{duration:c,container:p,representations:i}},br=["timeupdate","progress","play","seeked","stalled"];var Ae;(function(r){r.NONE="none",r.MANIFEST_LOADED="manifest_loaded",r.REPRESENTATION_SELECTED="representation_selected"})(Ae||(Ae={}));let yr=class{element=null;source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new K;fetcher;state$=new ae(Ae.NONE);currentVideoRepresentation$=new g(void 0);error$=new D;lastConnectionType$=new g(void 0);lastConnectionReused$=new g(void 0);lastRequestFirstBytes$=new g(void 0);forceEnded$=new D;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new rt;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Sr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initManifest=_e(this.destroyController.signal,async function*(e,t){this.element=e,this.state$.startTransitionTo(Ae.MANIFEST_LOADED);const s=yield this.fetcher.fetchManifest(t).catch(n=>this.error$.next({id:"LoadManifest",category:_.NETWORK,message:"Failed to load manifest",thrown:n}));if(!s)return null;let i;try{i=gr(s??"",t)}catch(n){this.error$.next({id:"ManifestParsing",category:_.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!i)return null;const a=({mime:n,codecs:o})=>Boolean(e.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`));return this.manifest={...i,representations:Object.fromEntries(Object.entries(i.representations).map(([n,o])=>[n,o.filter(a)]))},this.manifest.representations.video.length?this.state$.setState(Ae.MANIFEST_LOADED):this.error$.next({id:"NoRepresentations",category:_.PARSER,message:"No playable video representations"}),this.manifest}.bind(this));initRepresentations=_e(this.destroyController.signal,async function*(e,t){A(this.manifest),A(this.element),this.state$.startTransitionTo(Ae.REPRESENTATION_SELECTED),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 fs(we.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],$(t)&&(this.audioBufferManager=new fs(we.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=O(...this.bufferManagers.map(n=>n.fullyBuffered$)).pipe(v(()=>this.bufferManagers.every(n=>n.fullyBuffered$.getValue()))),a=O(...this.bufferManagers.map(n=>n.onLastSegment$)).pipe(v(()=>this.bufferManagers.some(n=>n.onLastSegment$.getValue())));this.subscription.add(O(this.forceEnded$,qe({allBuffersFull:i,someBufferEnded:a}).pipe(U(({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:_.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}})),this.subscription.add(O(...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(Ae.REPRESENTATION_SELECTED),A(this.element),this.subscription.add(O(...br.map(n=>M(this.element,n)),M(window,"online")).subscribe(this.tick,n=>{this.error$.next({id:"DashVKPlayer",category:_.WTF,message:"Internal logic error",thrown:n})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&cs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}.bind(this));async switchRepresentation(e,t){return{[we.VIDEO]:this.videoBufferManager,[we.AUDIO]:this.audioBufferManager,[we.TEXT]:null}[e]?.switchTo(t)}seek(e,t){A(this.element),A(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),cs(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(Ae.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}tick=()=>{if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Xs(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),t=>{this.error$.next({id:"GapWatchdog",category:_.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(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(oe||(oe={}));const Tr=({id:r,width:e,height:t,bitrate:s,fps:i,quality:a})=>{const n=(a?Ct(a):void 0)??ot({width:e,height:t});return n&&{id:r,quality:n,bitrate:s,size:{width:e,height:t},fps:i}},Er=(r,e,t)=>{const s=e.indexOf(t);return r.at(Math.round(r.length*s/e.length))??r.at(-1)};class vr{subscription=new K;videoState=new ae(oe.STOPPED);video;player;params;elementSize$=new g(void 0);textTracksManager=new Oe;videoTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Ii;constructor(e){this.params=e,this.video=Ye(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),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 yr({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=c=>{e.error$.next({id:"DashVKProvider",category:_.WTF,message:"DashVKProvider internal logic error",thrown:c})},a=(c,d)=>this.subscription.add(c.subscribe(d,i));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(U($),pe(),nt(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Ge(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,i)),a(qt(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),w(t.playbackState,f.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),w(t.playbackState,f.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===oe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(U(({to:c})=>c===Ae.REPRESENTATION_SELECTED)).subscribe(()=>{this.videoState.setState(oe.READY)}));const n=c=>e.error$.next({id:"RepresentationSwitch",category:_.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(O(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,M(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c===Ae.NONE||!this.videoTracks.length)return;const u=c===Ae.MANIFEST_LOADED&&!d,h=c===Ae.REPRESENTATION_SELECTED&&!d,l=t.autoVideoTrackSwitching.getState(),p=t.videoTrack.getState(),S=this.videoTracks.find(({track:{id:I}})=>I===p)?.track,m=e.currentVideoTrack$.getValue(),T=lt(this.video.buffered,this.video.currentTime*1e3),P=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,L=Math.min(T/Math.min(P,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),se=Math.max(S&&!l?this.audioRepresentations.get(S.id)?.bitrate??0:0,m?this.audioRepresentations.get(m.id)?.bitrate??0:0),k=It(this.videoTracks.map(({track:I})=>I),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),reserve:se,forwardBufferHealth:L,current:m,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),E=l?k??S:S??k;if(t.autoVideoTrackSwitching.getTransition()&&(t.autoVideoTrackSwitching.setState(l),this.player.setBufferTarget(P)),u){const I=E&&this.videoTracks.find(({track:x})=>x===E)?.representation;A(I),this.player.initRepresentations(I.id,this.audioRepresentations.get(I.id)?.id)}else if(h){const I=E&&this.videoTracks.find(({track:x})=>x===E)?.representation;if(I){const x=this.audioRepresentations.get(I.id);this.player.switchRepresentation(we.VIDEO,I.id).catch(n),x&&this.player.switchRepresentation(we.AUDIO,x.id).catch(n)}}},i)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(he(),v(c=>c&&this.videoTracks.find(({representation:{id:d}})=>d===c)?.track)).subscribe(e.currentVideoTrack$,i)),this.textTracksManager.connect(this.video,t,e);const o=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort((i,a)=>a.bitrate-i.bitrate),s=Array.from(e.representations.video).sort((i,a)=>a.bitrate-i.bitrate);for(const i of s){const a=Tr(i);if(a){this.videoTracks.push({track:a,representation:i});const n=Er(t,s,i);n&&this.audioRepresentations.set(i.id,n)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:i})=>i))}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===B.Requested&&s?.to!==f.PAUSED&&e!==oe.STOPPED&&t!==f.STOPPED&&this.seek(i.position,i.forcePrecise),t===f.STOPPED){e!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.player.stop(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(e===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}switch(e){case oe.READY:t===f.PAUSED?(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case oe.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}};destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))})}}const $r=5e3,Fe={};var J;(function(r){r.INITIALIZING="initializing",r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(J||(J={}));const Mt=(r,e)=>new _t(t=>{const s=(i,a)=>t.next(a);return r.on(e,s),()=>r.off(e,s)});class kr{subscription=new K;videoState=new ae(J.INITIALIZING);video;params;hls;textTracksManager=new Oe;trackLevels=new Map;constructor(e){this.video=Ye(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ve(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},s=window.setTimeout(()=>t("timeout"),$r);import("hls.js").then(i=>{e||(Fe.Hls=i.default,Fe.Events=i.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){A(Fe.Hls,"hls.js not loaded"),this.hls=new Fe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(J.STOPPED)}subscribe(){A(Fe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:_.WTF,message:"HlsJsProvider internal logic error",thrown:d})},i=ze(this.video),a=(d,u)=>this.subscription.add(d.subscribe(u,s));a(i.timeUpdate$,t.position$),a(i.durationChange$,t.duration$),a(i.ended$,t.endedEvent$),a(i.looped$,t.loopedEvent$),a(i.error$,t.error$),a(i.isBuffering$,t.isBuffering$),a(i.currentBuffer$,t.currentBuffer$),a(i.loadStart$,t.firstBytesEvent$),a(i.playing$,t.firstFrameEvent$),a(i.canplay$,t.canplay$),a(i.seeked$,t.seekedEvent$),this.subscription.add(dt(this.video,e.isLooped,s)),this.subscription.add(Ge(this.video,e.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,e.playbackRate,i.playbackRateState$,s)),this.subscription.add(Mt(this.hls,Fe.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:_.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(J.PLAYING),w(e.playbackState,f.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),w(e.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},s)),a(Mt(this.hls,Fe.Events.MANIFEST_PARSED).pipe(v(({levels:d})=>d.reduce((u,h)=>{const l=h.name||h.height.toString(10),{width:p,height:S}=h,m=Ct(h.attrs.QUALITY??"")??ot({width:p,height:S});if(!m)return u;const T=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:l.toString(),quality:m,bitrate:h.bitrate/1e3,size:{width:p,height:S},fps:T};return this.trackLevels.set(l,{track:P,level:h}),u.push(P),u},[]))),t.availableVideoTracks$),a(Mt(this.hls,Fe.Events.LEVEL_LOADING).pipe(v(({url:d})=>ve(d))),t.hostname$),this.subscription.add(Be(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,Fe.Events.LEVEL_SWITCHED).pipe(v(({level:d})=>n(this.hls.levels[d])));o.pipe(U($)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Be(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel])?.id,d=>{if(z(d))return;const u=this.trackLevels.get(d)?.level;if(!u)return;const h=this.hls.levels.indexOf(u),l=this.hls.currentLevel,p=this.hls.levels[l];!p||u.bitrate>p.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(v(d=>d?.id)),onError:s})),a(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=O(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(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!==J.INITIALIZING)switch(s?.to!==f.PAUSED&&i.state===B.Requested&&this.seek(i.position),t){case f.STOPPED:switch(e){case J.STOPPED:break;case J.READY:case J.PLAYING:case J.PAUSED:this.stop();break;default:N(e)}break;case f.PLAYING:switch(e){case J.PLAYING:break;case J.STOPPED:this.prepare();break;case J.READY:case J.PAUSED:this.playIfAllowed();break;default:N(e)}break;case f.PAUSED:switch(e){case J.PAUSED:break;case J.STOPPED:this.prepare();break;case J.READY:this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED);break;case J.PLAYING:this.pause();break;default:N(e)}break;default:N(t)}};prepare(){this.videoState.startTransitionTo(J.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(J.PLAYING),await tt(this.video)||(this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED,!0))}pause(){this.videoState.startTransitionTo(J.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(J.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0)}}const ms="X-Playback-Duration";var Ss=async r=>{const e=await pt(r,{method:"HEAD"});return e.headers.has(ms)?parseInt(e.headers.get(ms),10):void 0};const Ar=r=>{let e=null;if(r.QUALITY&&(e=Ct(r.QUALITY)),!e&&r.RESOLUTION){const[t,s]=r.RESOLUTION.split("x").map(i=>parseInt(i,10));e=ot({width:t,height:s})}return e??null},Ys=async(r,e=r)=>{const i=(await(await pt(r)).text()).split(`
|
|
8
8
|
`),a=[];for(let n=0;n<i.length;n++){const c=i[n].match(/^#EXT-X-STREAM-INF:(.+)/);if(!c)continue;const d=Object.fromEntries(c[1].split(",").map(T=>T.split("="))),u=d.QUALITY??`stream-${d.BANDWIDTH}`,h=Ar(d);let l;d.BANDWIDTH&&(l=parseInt(d.BANDWIDTH,10)/1e3||void 0),!l&&d["AVERAGE-BANDWIDTH"]&&(l=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const p=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0;let S;if(d.RESOLUTION){const[T,P]=d.RESOLUTION.split("x").map(L=>parseInt(L,10));T&&P&&(S={width:T,height:P})}const m=new URL(i[++n],e).toString();h&&a.push({id:u,quality:h,url:m,bandwidth:l,size:S,fps:p})}return a};var Z;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(Z||(Z={}));class wr{subscription=new K;videoState=new ae(Z.STOPPED);video;params;textTracksManager=new Oe;manifests$=new g([]);maxSeekBackTime$;liveOffset=new es;manifestStartTime$=new g(void 0);constructor(e){this.params=e,this.video=Ye(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:te.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),Ys(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:_.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.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(),a=i?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n)return;const o=s?"master":a;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:_.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ze(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,s));a(i.ended$,e.endedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.loadedMetadata$,e.firstBytesEvent$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),w(t.playbackState,f.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),w(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Z.READY&&this.videoState.setState(Z.READY),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(he(),v(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&&$(d.to)){const h=d.to;this.params.desiredState.videoTrack.setState(h);const l=this.manifests$.getValue().find(p=>p.id===h);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(ve(l.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),c&&c.from===Z.CHANGING_MANIFEST&&this.videoState.setState(c.to),o&&o.state===B.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(U($)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:c})=>this.params.output.liveTime$.next(o+c*1e3),s)),this.subscription.add(this.manifests$.pipe(v(o=>o.map(({id:c,quality:d,size:u,bandwidth:h,fps:l})=>({id:c,quality:d,size:u,fps:l,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,ke(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(z(e))return;const t=ft(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Ss(t).then(s=>{if(!z(s))this.maxSeekBackTime$.next(s);else{const i=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(z(i)||!isFinite(i))try{pt(t).then(a=>a.text()).then(a=>{const n=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(a)?.[1];if(n){const o=new URL(n,t).toString();Ss(o).then(c=>{z(c)||this.maxSeekBackTime$.next(c)})}})}catch{}}})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,f.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(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===f.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(i||a){const c=this.videoState.getState();this.videoState.setState(Z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),o.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==f.PAUSED&&o.state===B.Requested){this.videoState.startTransitionTo(Z.READY),this.seek(o.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(e){case Z.READY:t===f.PAUSED?(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case Z.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):s?.to===f.PAUSED&&(w(this.params.desiredState.playbackState,f.PAUSED),this.liveOffset.pause());return;case Z.CHANGING_MANIFEST:break;default:return N(e)}}}var re;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.CHANGING_MANIFEST="changing_manifest",r.PAUSED="paused"})(re||(re={}));class Pr{subscription=new K;videoState=new ae(re.STOPPED);video;params;textTracksManager=new Oe;manifests$=new g([]);constructor(e){this.params=e,this.video=Ye(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:te.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ve(this.params.source.url)),Ys(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.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(),a=i?.to??t.getState()??"master",n=this.manifests$.getValue();if(!n)return;const o=s?"master":a;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:_.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ze(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.loadedMetadata$,e.firstBytesEvent$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.seeked$,e.seekedEvent$),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),w(t.playbackState,f.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),w(t.playbackState,f.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.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&&$(d.to)){const h=d.to;this.params.desiredState.videoTrack.setState(h);const l=this.manifests$.getValue().find(p=>p.id===h);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(ve(l.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),c&&c.from===re.CHANGING_MANIFEST&&this.videoState.setState(c.to),o.state===B.Requested&&this.seek(o.position)},s))),this.subscription.add(this.manifests$.pipe(v(o=>o.map(({id:c,quality:d,size:u,bandwidth:h,fps:l})=>({id:c,quality:d,size:u,fps:l,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const n=O(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();z(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),w(this.params.desiredState.playbackState,f.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(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(t===f.STOPPED){e!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(re.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.seekState.getState();if(e===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(i||a){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:d}=this.video;this.prepare(),o.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:d*1e3,forcePrecise:!0});return}switch(s?.to!==f.PAUSED&&o.state===B.Requested&&this.seek(o.position),e){case re.READY:t===f.PAUSED?(this.videoState.setState(re.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case re.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return N(e)}}}var de;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(de||(de={}));class Rr{subscription=new K;videoState=new ae(de.STOPPED);video;trackUrls={};params;textTracksManager=new Oe;constructor(e){this.params=e,this.video=Ye(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],i)=>{const a=i.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:_.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ze(this.video),a=(o,c)=>this.subscription.add(o.subscribe(c,s));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.loadedMetadata$,e.firstBytesEvent$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.seeked$,e.seekedEvent$),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Ge(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,s)),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),w(t.playbackState,f.PLAYING)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),w(t.playbackState,f.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=O(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState();A(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];A(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(){tt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),w(this.params.desiredState.playbackState,f.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===f.STOPPED){e!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.seekState.getState();if(e===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(a){const{currentTime:o}=this.video;this.prepare(),n.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:o*1e3,forcePrecise:!0});return}switch(s?.to!==f.PAUSED&&n.state===B.Requested&&this.seek(n.position),e){case de.READY:t===f.PAUSED?(this.videoState.setState(de.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case de.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}const gs=["stun:videostun.mycdn.me:80"],Dr=1e3,_r=3,Kt=()=>null;class Ir{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Kt;externalStopCallback=Kt;externalErrorCallback=Kt;constructor(e,t){this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:gs}]};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:_.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),Dr)}normalizeOptions(e={}){const t={stunServerList:gs,maxRetryNumber:_r,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ee;(function(r){r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused"})(ee||(ee={}));class Cr{subscription;params;log;video;videoState=new ae(ee.STOPPED);liveStreamClient;maxSeekBackTime$=new g(0);constructor(e){this.subscription=new K,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ye(e.container),this.liveStreamClient=new Ir(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:_.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};O(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),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(i.timeUpdate$,e.liveTime$),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===ee.READY&&this.videoState.setState(ee.READY)},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED)},s)).add(i.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING)},s)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(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 ee.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(f.STOPPED);break;case ee.READY:break;case ee.PAUSED:t.playbackState.setState(f.PAUSED);break;case ee.PLAYING:t.playbackState.setState(f.PLAYING);break;default:return N(n.to)}},s)).add(O(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Ie(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.currentVideoTrack$.next({id:"webrtc",quality:te.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,f.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ee.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:_.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,f.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===f.STOPPED){e!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ee.STOPPED),w(this.params.desiredState.playbackState,f.STOPPED,!0));return}if(this.videoState.getTransition())return;const a=this.params.desiredState.videoTrack.getTransition();if(e===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(a){this.prepare();return}switch(e){case ee.READY:t===f.PAUSED?(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,f.PAUSED)):t===f.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:t===f.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):s?.to===f.PLAYING&&w(this.params.desiredState.playbackState,f.PLAYING);return;case ee.PAUSED:t===f.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):s?.to===f.PAUSED&&w(this.params.desiredState.playbackState,f.PAUSED);return;default:return N(e)}}}class bs{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 Lr=()=>{const r=window.navigator;return r.userAgentData?r.userAgentData?.platform?.toLowerCase()==="android":window.navigator.userAgent.toLowerCase().includes("android")};const zs=Lr(),Wt=document.createElement("video"),Xe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:Boolean(Wt.canPlayType?.("application/x-mpegurl")||Wt.canPlayType?.("vnd.apple.mpegURL")),webrtc:Boolean(window.RTCPeerConnection)},xe={mp4:Boolean(Wt.canPlayType?.("video/mp4")),webm:Boolean(Wt.canPlayType?.("video/webm"))},Ze={h264:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(window.MediaSource?.isTypeSupported?.('video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(window.MediaSource?.isTypeSupported?.('video/webm; codecs="vp9"')),aac:Boolean(window.MediaSource?.isTypeSupported?.('audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(window.MediaSource?.isTypeSupported?.('audio/webm; codecs="opus"'))},kt=(Ze.h264||Ze.h265)&&Ze.aac,jt=Xe.hls&&xe.mp4,xr=Boolean(window.WebSocket),Nr=()=>Object.keys(Ze).filter(r=>Ze[r]),Br=(r,e=!1)=>r.filter(t=>{switch(t){case b.DASH:return Xe.mse&&xe.mp4&&kt;case b.DASH_SEP:return Xe.mse&&xe.mp4&&kt;case b.DASH_WEBM:return Xe.mse&&xe.webm&&Ze.vp9&&Ze.opus;case b.DASH_LIVE:return Xe.mse&&xe.mp4&&kt;case b.DASH_ONDEMAND:return Xe.mse&&xe.mp4&&kt;case b.HLS:case b.HLS_LIVE:case b.HLS_ONDEMAND:return jt||e&&Xe.mse&&xe.mp4&&kt;case b.MPEG:return xe.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Xe.webrtc&&xr&&Ze.h264&&(xe.mp4||xe.webm);default:return N(t)}}),Or=()=>zs?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:jt?[b.DASH_WEBM,b.DASH_SEP,b.HLS,b.HLS_ONDEMAND,b.DASH_ONDEMAND,b.MPEG,b.DASH]:[b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG],Mr=()=>zs?[b.HLS_LIVE,b.WEB_RTC_LIVE,b.DASH_LIVE]:jt?[b.WEB_RTC_LIVE,b.HLS_LIVE,b.DASH_LIVE]:[b.WEB_RTC_LIVE,b.DASH_LIVE,b.HLS_LIVE],ys=r=>r?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var Ur=r=>new _t(e=>{const t=new K,s=r.desiredPlaybackState$.stateChangeStarted$.pipe(v(({from:d,to:u})=>`${d}-${u}`)),i=r.desiredPlaybackState$.stateChangeEnded$,a=r.providerChanged$,n=new D;let o=0,c="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),c=d,o=window.setTimeout(()=>n.next(d),r.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),c="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(c),r.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Ts={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Fr={cacheDuration:12e4},Vr={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Hr={maxPausedTime:3e4},qr={maxPausedTime:3e4};class Gr{current$=new g({type:void 0});providerError$=new D;noAvailableProvidersError$=new D;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([]),autoVideoTrackLimitingAvailable$:new g(!1),currentBuffer$:new g(void 0),isBuffering$:new g(!0),error$:new D,willSeekEvent$:new D,seekedEvent$:new D,loopedEvent$:new D,endedEvent$:new D,firstBytesEvent$:new D,firstFrameEvent$:new D,canplay$:new D,isLive$:new g(void 0),liveTime$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),element$:new g(void 0)};subscription=new K;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Br([...Mr(),...Or()],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 bs(i);const a=[...ys(!0),...ys(!1)];this.chromecastFormatsIterator=new bs(a.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(z(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:_.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;A(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!==B.None;this.params.desiredState.seekState.setState({state:B.Requested,position:i?s.position:t,forcePrecise:i?s.forcePrecise:!1}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case $e.SCREEN:return this.createScreenProvider(t);case $e.CHROMECAST:return this.createChromecastProvider(t);default:return N(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:i}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:i,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH:{const o=this.applyFailoverHost(t[e]);return A(o),new tr({...n,source:o,config:Fr})}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return A(o),this.params.tuning.useDashJs?new xi({...n,source:o,format:e,config:qr}):new vr({...n,source:o})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return A(o),jt||!this.params.tuning.useHlsJs?new Pr({...n,source:o}):new kr({...n,source:o})}case b.HLS_LIVE:{const o=this.applyFailoverHost(t[e]);return A(o),new wr({...n,source:o,config:Hr})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return A(o),new Rr({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return A(o),new Ji({...n,source:o,config:Vr})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return A(o),new Cr({container:s,source:o,desiredState:i,output:a,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:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return A(o),new mi({connection:o,meta:a,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 a=new URL(i);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return Object.fromEntries(Object.entries(e).map(([i,a])=>[i,s(a)]))}initProviderErrorHandling(){const e=new K;let t=!1,s=0;return e.add(O(this.providerOutput.error$,Ur({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ts.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(U(({type:i})=>i!==void 0))}).pipe(v(i=>({id:`ProviderHangup:${i}`,category:_.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(U(({to:a})=>a===f.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 a=i.category===_.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<Ts.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Es=(r,e,t)=>t*e+(1-t)*r;class vs{prevReported=void 0;slow;fast;smoothed;pastMeasures=[];measuresCursor=0;params;rawSeries$;smoothedSeries$;reportedSeries$;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=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 Ne(`raw_${t}`),this.smoothedSeries$=new Ne(`smoothed_${t}`),this.reportedSeries$=new Ne(`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 c=0;c<this.pastMeasures.length;c++)this.pastMeasures[c]!==void 0&&(t+=(this.pastMeasures[c]-this.smoothed)**2,s++);t/=s;const i=Math.sqrt(t),a=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.slow=Es(this.slow,e,this.params.emaAlphaSlow),this.fast=Es(this.fast,e,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(z(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))}}var Re;(function(r){r[r.LOCAL_STORAGE=0]="LOCAL_STORAGE",r[r.SESSION_STORAGE=1]="SESSION_STORAGE",r[r.RUNTIME=2]="RUNTIME"})(Re||(Re={}));const Ws=new Map;let at=Re.RUNTIME;const Xt=`vk-videoplayer-dummy-key-${Math.random()}`,Yr=()=>{try{localStorage.setItem(Xt,"test"),localStorage.removeItem(Xt),at=Re.LOCAL_STORAGE}catch(r){if(r instanceof DOMException||r instanceof TypeError)try{sessionStorage.getItem(Xt),at=Re.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)at=Re.RUNTIME;else throw e}else throw r}};Yr();const zr=r=>{switch(at){case Re.LOCAL_STORAGE:return localStorage.getItem(r)??void 0;case Re.SESSION_STORAGE:return sessionStorage.getItem(r)??void 0;case Re.RUNTIME:return Ws.get(r);default:N(at)}},$s=(r,e)=>{switch(at){case Re.LOCAL_STORAGE:try{localStorage.setItem(r,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Re.SESSION_STORAGE:try{sessionStorage.setItem(r,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Re.RUNTIME:return void Ws.set(r,e);default:N(at)}},Wr=5e3,ks="one_video_throughput",As="one_video_rtt",Pt=window.navigator.connection,ws=()=>{const r=Pt?.downlink;if($(r)&&r!==10)return r*1e3},Ps=()=>{const r=Pt?.rtt;if($(r)&&r!==3e3)return r},Rs=(r,e,t)=>{const s=t*8,i=s/r;return s/(i+e)};class Rt{throughput;rtt;subscription=new K;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Rt.load(ks)||(e.useBrowserEstimation?ws():void 0)||Wr,s=Rt.load(As)??(e.useBrowserEstimation?Ps():void 0)??0;if(this.throughput$=new g(t),this.rtt$=new g(s),this.rttAdjustedThroughput$=new g(Rs(t,s,e.rttPenaltyRequestSize)),this.throughput=new vs({initial:t,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"throughput"}),this.rtt=new vs({initial:s,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"rtt"}),e.useBrowserEstimation){const i=()=>{const n=ws();n&&this.throughput.next(n);const o=Ps();$(o)&&this.rtt.next(o)};Pt&&"onchange"in Pt&&this.subscription.add(M(Pt,"change").subscribe(i)),i()}this.subscription.add(this.throughput.smoothed$.subscribe(i=>{$s(ks,i.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(i=>{$s(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(v(({throughput:i,rtt:a})=>Rs(i,a,e.rttPenaltyRequestSize)),U(i=>{const a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(i-a)/a>=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(M(e,"progress").pipe(pe()).subscribe(a=>{t=a.loaded,s=ce()}));break;case 1:case 0:i.add(M(e,"loadstart").subscribe(()=>{t=0,s=ce()}));break}i.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.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 a=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,a+=u.byteLength,a>=this.tuningConfig.streamMinSampleSize&&ce()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,ce()-n,this.concurrentDownloads.size),a=0,n=ce()),await t?.read().then(c,o))};this.concurrentDownloads.add(e),t?.read().then(c,o)}addRawSpeed(e,t,s=1){if(Rt.sanityCheck(e,t)){const i=e*8/t;this.throughput.next(i*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){const t=zr(e);if($(t))return parseInt(t,10)??void 0}}const Ds={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},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,webrtc:{connectionRetryMaxNumber:3}},Qr=r=>{const e={};for(const t of Object.keys(Ds)){const s=Ds[t],i=r[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 jr=({seekState:r,position$:e})=>O(r.stateChangeEnded$.pipe(v(({to:t})=>t.state===B.None?void 0:(t.position??NaN)/1e3),U($)),e.pipe(U(()=>r.getState().state===B.None))),Jr=r=>{const e=typeof r.container=="string"?document.getElementById(r.container):r.container;return A(e,`Wrong container or containerId {${r.container}}`),e};const _s=({playbackState:r,seekState:e,playbackAbort$:t,looped$:s,position$:i})=>new _t(a=>{let n;const o=r.transitionEnded$.pipe(U(p=>(p.from===f.PAUSED||p.from===f.STOPPED)&&p.to===f.PLAYING)),c=r.stateChangeEnded$.pipe(U(p=>p.from===f.PLAYING&&p.to===f.PAUSED)),d=e.stateChangeEnded$.pipe(U(({to:p})=>p.state===B.Requested&&(r.getTransition()?.from??r.getState())===f.PLAYING)),u=e.stateChangeEnded$.pipe(U(({from:p,to:S})=>p.state===B.Applying&&S.state===B.None&&(r.getTransition()?.from??r.getState())===f.PLAYING)),h=O(o,u).pipe(v(()=>i.getValue()),U($)),l=O(O(c,d,t),s).pipe(v(()=>i.getValue()),U($));return new K().add(h.subscribe(p=>{n=p})).add(l.subscribe(p=>{if(z(n)||n===p)return;const S={from:n,to:p};n=void 0,a.next(S)}))});class sa{subscription=new K;domContainer;providerContainer;chromecastInitializer;logger=new Zs;explicitInitialQuality;config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new ae(f.STOPPED),seekState:new ae({state:B.None}),volume:new ae({volume:1,muted:!1}),videoTrack:new ae(void 0),autoVideoTrackSwitching:new ae(!0),autoVideoTrackLimits:new ae({}),isLooped:new ae(!1),playbackRate:new ae(1),externalTextTracks:new ae([]),currentTextTrack:new ae(void 0),textTrackCuesSettings:new ae({})};info={playbackState$:new g(f.STOPPED),position$:new g(0),duration$:new g(1/0),muted$:new g(!1),volume$:new g(1),availableQualities$:new g([]),availableQualitiesFps$:new g({}),currentQuality$:new g(void 0),isAutoQualityEnabled$:new g(!0),autoQualityLimitingAvailable$:new g(!1),autoQualityLimits$:new g({}),currentPlaybackRate$:new g(1),currentBuffer$:new g({start:0,end:0}),isBuffering$:new g(!0),isStalled$:new g(!1),isEnded$:new g(!1),isLooped$:new g(!1),isLive$:new g(void 0),liveTime$:new g(void 0),currentFormat$:new g(void 0),availableTextTracks$:new g([]),currentTextTrack$:new g(void 0),throughputEstimation$:new g(void 0),rttEstimation$:new g(void 0),videoBitrate$:new g(void 0),hostname$:new g(void 0),httpConnectionType$:new g(void 0),httpConnectionReused$:new g(void 0),chromecastState$:new g(Te.NOT_AVAILABLE),chromecastDeviceName$:new g(void 0),intrinsicVideoSize$:new g(void 0)};events={inited$:new D,started$:new D,willPause$:new D,willResume$:new D,willDestruct$:new D,watchCoverageRecord$:new D,watchCoverageLive$:new D,managedError$:new D,fatalError$:new D,ended$:new D,looped$:new D,seeked$:new D,willSeek$:new D,firstBytes$:new D,firstFrame$:new D,canplay$:new D,log$:new D};experimental={element$:new g(void 0),enableDebugTelemetry$:new g(!1),dumpTelemetry:Ri};constructor(e={}){if(this.initLogs(),this.tuning=Qr(e),this.chromecastInitializer=new ri({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Rt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,i)=>{const a=Reflect.get(t,s,i);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const c=n.map(h=>JSON.stringify(h,(l,p)=>{const S=typeof p;return["number","string","boolean"].includes(S)?p:p===null?null:`<${S}>`})),d=`Player.${String(s)}`,u=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:_.WTF,message:u,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Jr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Gr({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.initDebugTelemetry(),this}destroy(){this.events.willDestruct$.next(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const e=this.desiredState.playbackState;return e.getState()!==f.PLAYING&&e.startTransitionTo(f.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==f.PAUSED&&e.startTransitionTo(f.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==f.STOPPED&&e.startTransitionTo(f.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:B.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){return this.chromecastInitializer.castState$.getValue()===Te.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===Te.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){A(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){A(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(){A(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(z(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===B.None?void 0:t.position;return $(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(O(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.stateChangeEnded$.pipe(U(()=>!this.isPlaybackStarted),U(e=>e.to===f.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case f.PAUSED:this.events.willPause$.next();break;case f.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=ce(),this.events.inited$.next());break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const c=this.desiredState.seekState.getState();c.state===B.Requested?this.desiredState.seekState.setState({...c,state:B.Applying}):this.events.managedError$.next({id:`WillSeekIn${c.state}`,category:_.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===B.Applying&&(this.desiredState.seekState.setState({state:B.None}),this.events.seeked$.next())})).add(e.current$.pipe(v(c=>c.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(v(c=>c.destination),he()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(v(c=>c.map(({quality:d})=>d).sort((d,u)=>Vt(d)?1:Vt(u)?-1:Ut(u,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(c=>{const d={};for(const u of c)u.fps&&(d[u.quality]=u.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.currentVideoTrack$.subscribe(c=>{this.info.currentQuality$.next(c?.quality),this.info.videoBitrate$.next(c?.bitrate);const d=e.providerOutput.element$.getValue();d&&this.info.intrinsicVideoSize$.next({width:d.videoWidth,height:d.videoHeight})})).add(e.providerOutput.hostname$.pipe(he()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(he()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(he()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(v(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(v(c=>c.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(v(c=>c.volume),he()).subscribe(this.info.volume$)).add(jr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(O(e.providerOutput.endedEvent$.pipe(nt(!0)),e.providerOutput.seekedEvent$.pipe(nt(!1))).pipe(he()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(v(c=>({id:"NoProviders",category:_.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(()=>ce()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(pe(),v(()=>ce()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(pe(),v(()=>ce()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new g(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new g(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(U(({to:c})=>c===f.PLAYING),pe()).subscribe(()=>s.next(!1)));let i=0;const a=O(e.providerOutput.isBuffering$,t,s).pipe(v(()=>{const c=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||s.getValue();return c&&!d}),he());this.subscription.add(a.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=O(M(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(U(c=>Boolean(c?.provider))));e.providerOutput.isLive$.pipe(he()).subscribe(c=>{switch(A(this.providerContainer),n.unsubscribe(),c){case!0:{const d=new g(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(u=>d.next(u&&Math.floor(u/1e3)))),n.add(_s({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe(v(({from:u,to:h})=>({start:u,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(_s({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe(v(({from:d,to:u})=>({start:d,end:u}))).subscribe(this.events.watchCoverageRecord$));break}})}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 K;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((s,i)=>s.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(U(s=>s.length>0),pe()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=It(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(O(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;A(this.providerContainer),A(e),Pi(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>wi(t)),this.providerContainer.current$.subscribe(({type:t})=>Nt("provider",t)),e.duration$.subscribe(t=>Nt("duration",t)),e.availableVideoTracks$.pipe(U(t=>!!t.length),pe()).subscribe(t=>Nt("tracks",t)),this.events.fatalError$.subscribe(new Ne("fatalError")),this.events.managedError$.subscribe(new Ne("managedError")),e.position$.subscribe(new Ne("position")),e.currentVideoTrack$.pipe(v(t=>t?.quality)).subscribe(new Ne("quality")),this.info.currentBuffer$.subscribe(new Ne("buffer")),e.isBuffering$.subscribe(new Ne("isBuffering"))].forEach(t=>this.subscription.add(t)),Nt("codecs",Nr())}}const ia=`${si}@${ti}`;export{Te as ChromecastState,Dt as HttpConnectionType,na as Observable,f as PlaybackState,sa as Player,ia as SDK_VERSION,oa as Subject,da as Subscription,ca as ValueSubject,b as VideoFormat,te as VideoQuality};
|