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