@vkontakte/videoplayer-core 2.0.98-dev.72824ff7.0 → 2.0.98-dev.97d8def3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +7 -7
- package/evergreen.esm.js +5 -5
- package/package.json +1 -1
package/esnext.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.98-dev.
|
|
3
|
-
* Thu, 15 Feb 2024
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.98-dev.97d8def3.0
|
|
3
|
+
* Thu, 15 Feb 2024 16:10:49 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Ms=Object.create;var Ii=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Fs=Object.getOwnPropertyNames;var Os=Object.getPrototypeOf,Us=Object.prototype.hasOwnProperty;var Hs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fs(e))!Us.call(a,s)&&s!==t&&Ii(a,s,{get:()=>e[s],enumerable:!(i=Vs(e,s))||i.enumerable});return a};var Ni=(a,e,t)=>(t=a!=null?Ms(Os(a)):{},Hs(e||!a||!a.__esModule?Ii(t,"default",{value:a,enumerable:!0}):t,a));var r=require("@vkontakte/videoplayer-shared/esnext.cjs.js");const us="2.0.98-dev.72824ff7.0";exports.PlaybackState=void 0;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(a){a.MPEG="MPEG",a.DASH="DASH",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var ge;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ge||(ge={}));exports.ChromecastState=void 0;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var V;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(V||(V={}));exports.Surface=void 0;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(exports.Surface||(exports.Surface={}));var js=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Ys{connection$=new r.ValueSubject(void 0);castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new r.Subject;contentId;realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new r.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 i=r.isNonNullable(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},s||js("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.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(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.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),i=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return r.assertNever(s.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),r.map(s=>s.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(Gs),r.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const n=s===exports.ChromecastState.CONNECTED,o=r.isNonNullable(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();r.assertNonNullable(u);const d=u.getCastDevice(),c=u.getMediaSession()?.media.contentId;(r.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Gs=a=>{switch(a){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 r.assertNever(a)}};var X;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(X||(X={}));var Se=(a,e=0,t=X.OFFSET_P)=>{switch(t){case X.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case X.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case X.DASH_CMAF_OFFSET_P:{const i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:r.assertNever(t)}return a};const si=(a,e)=>{switch(e){case X.OFFSET_P:return NaN;case X.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case X.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:r.assertNever(e)}};var w=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class q{state;prevState;transition;transitionStarted$=new r.Subject;transitionEnded$=new r.Subject;transitionUpdated$=new r.Subject;forceChanged$=new r.Subject;stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=r.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||r.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const zs=a=>{switch(a){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.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(a)}};var B;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(B||(B={}));const qs=5,Ws=5,Qs=500,_i=7e3;class Js{subscription=new r.Subscription;loadMediaTimeoutSubscription=new r.Subscription;videoState=new q(B.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(zs(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(r.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new r.Subject;e.add(s.pipe(r.debounce(Qs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const u=o.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state===V.Applying||Math.abs(u-n)>qs)&&s.next(u),n=u})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,u=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(u!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Ws&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(B.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:V.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===B.PAUSED||e===B.PLAYING)&&(this.videoState.setState(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===B.PLAYING||e===B.PAUSED)&&(this.videoState.setState(B.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===B.READY&&this.videoState.setState(B.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==B.STOPPED&&this.videoState.setState(B.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,s,n;switch(e){case exports.VideoFormat.MPEG:{const c=t[e];r.assertNonNullable(c);const h=r.getHighestQuality(Object.keys(c));r.assertNonNullable(h);const l=c[h];r.assertNonNullable(l),i=l,s="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=t[e];r.assertNonNullable(c),i=c.url,s="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:case exports.VideoFormat.DASH_WEBM_AV1:{const c=t[e];r.assertNonNullable(c),i=c.url,s="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=t[e];r.assertNonNullable(c),i=c.url,s="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=t[e];r.assertNonNullable(c),i=Se(c.url),s="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 c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);o.contentUrl=i,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return r.isNonNullable(u)&&(o.metadata.title=u),r.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===V.Applying||i.state===V.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(_i).subscribe(()=>n(`timeout(${_i})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.stop());return}if(!t){if(s?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&e!==B.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case B.PLAYING:case B.PAUSED:case B.READY:break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case B.PLAYING:break;case B.PAUSED:this.videoState.startTransitionTo(B.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case B.READY:this.videoState.startTransitionTo(B.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case B.PLAYING:this.videoState.startTransitionTo(B.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case B.PAUSED:break;case B.READY:this.videoState.startTransitionTo(B.PAUSED),this.videoState.setState(B.PAUSED);break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}default:r.assertNever(i)}}}}var Xs=a=>{let e,t=!1,i=!1;a.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),a.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&e?.()}}},!0)},Ks=a=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),s=new r.ValueSubject(void 0);let n=NaN,o=!1;const u=()=>{n=Date.now(),o=!1},d=h=>{const l=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(g=>g.split(": ")));if("x-playback-duration"in l||"x-playback-duration-millis"in l){const g=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??g*1e3??NaN;r.isNonNullable(b)&&!isNaN(b)&&e.next(b)}const f=l["x-delivery-type"]??exports.HttpConnectionType.HTTP1,p={1:!0,0:!1}[l["x-reused"]]??void 0;i.next(f),s.next(p)},c=h=>{h.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return a.extend("XHRLoader",function(){const{parent:h}=this,l=h.load.bind(h);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,g=f.progress;f.onload=function(...y){return d(this),p(...y)},f.progress=function(...y){return c(this),g(...y)},u()}return l(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},ct=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Zs=a=>a.extend("RequestModifier",()=>({modifyRequestURL:ct}),!0),ea=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,n]=i.request.range.split("-").map(u=>parseInt(u,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Ve=(a,e,t,{equal:i=(o,u)=>o===u,changed$:s,onError:n}={})=>{const o=a.getState(),u=e(),d=r.isNullable(s),c=new r.Subscription;return s&&c.add(s.subscribe(h=>{const l=a.getState();i(h,l)&&a.setState(h)},n)),i(u,o)||(t(o),d&&a.setState(o)),c.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),d&&a.setState(h.to)},n)),c},dt=(a,e,t)=>Ve(e,()=>a.loop,i=>{r.isNonNullable(i)&&(a.loop=i)},{onError:t}),Qe=(a,e,t,i)=>Ve(e,()=>({muted:a.muted,volume:a.volume}),s=>{r.isNonNullable(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,n)=>s===n||s?.muted===n?.muted&&s?.volume===n?.volume,changed$:t,onError:i}),rt=(a,e,t,i)=>Ve(e,()=>a.playbackRate,s=>{r.isNonNullable(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),ta=a=>["__",a.language,a.label].join("|"),ia=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class Fe{available$=new r.Subject;current$=new r.ValueSubject(void 0);error$=new r.Subject;video;cueSettings;subscription=new r.Subscription;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ve(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:s})),this.subscription.add(Ve(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ve(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:s})),this.subscription.add(Ve(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,s)=>i.length===s.length&&i.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const s=i;r.isNonNullable(t.align)&&(s.align=t.align),r.isNonNullable(t.position)&&(s.position=t.position),r.isNonNullable(t.size)&&(s.size=t.size),r.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Fe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:ta(e),n=this.externalTracks.has(s),o=s.includes("auto");return n?{id:s,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(s)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:s,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===s&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!ia(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){r.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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Di=a=>{a.removeAttribute("src"),a.load()},sa=a=>{try{a.pause(),a.playbackRate=0,Di(a),a.remove()}catch(e){console.error(e)}};class aa{attribute="data-pool-reused";get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const vi=window.WeakMap?new WeakMap:new aa,Je=a=>{let e=a.querySelector("video");const t=!!e;return e?Di(e):(e=document.createElement("video"),a.appendChild(e)),vi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Xe=a=>{const e=vi.get(a);vi.delete(a),e?Di(a):sa(a)};class Wt{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const cs=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Bi=a=>{const e=cs(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ra=a=>{const e=cs(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},Ei=3;class na{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Ei&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ei))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,u=n>=e&&n<t;o&&u||(o?i(t,n):u?i(s,e):s<e&&n>t?(i(t,n),i(s,e)):i(s,n))})}destroy(){this._buffer=[]}}var ds=(a,e,t=Ei)=>{let i=0,s=0;for(let n=0;n<a.length;n++){const o=a.start(n),u=a.end(n);if(o<=e&&e<=u){if(i=o,s=u,!t)return{from:i,to:s};for(let d=n-1;d>=0;d--)a.end(d)+t>=i&&(i=a.start(d));for(let d=n+1;d<a.length;d++)a.start(d)-t<=s&&(s=a.end(d))}}return{from:i,to:s}};const Ke=a=>{const e=m=>r.fromEvent(a,m).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(m=>r.fromEvent(a,m))).pipe(r.map(m=>m.type==="ended"?a.readyState<2:a.readyState<3),r.filterChanged()),s=r.merge(r.fromEvent(a,"progress"),r.fromEvent(a,"timeupdate")).pipe(r.map(()=>ds(a.buffered,a.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),u=r.fromEvent(a,"volumechange").pipe(r.map(()=>({muted:a.muted,volume:a.volume}))),d=r.fromEvent(a,"ratechange").pipe(r.map(()=>a.playbackRate)),c=r.fromEvent(a,"error").pipe(r.filter(()=>!!(a.error||a.played.length)),r.map(()=>{const m=a.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=r.fromEvent(a,"timeupdate").pipe(r.map(()=>a.currentTime)),l=new r.Subject,f=.3;let p;h.subscribe(m=>{a.loop&&r.isNonNullable(p)&&r.isNonNullable(m)&&p>=a.duration-f&&m<=f&&l.next(p),p=m});const g=r.fromEvent(a,"enterpictureinpicture"),y=r.fromEvent(a,"leavepictureinpicture"),b=new r.ValueSubject(ra(a));g.subscribe(()=>b.next(!0)),y.subscribe(()=>b.next(!1));const k=new r.ValueSubject(Bi(a));return r.fromEvent(a,"fullscreenchange").pipe(r.map(()=>Bi(a))).subscribe(k),{playing$:o,pause$:e("pause").pipe(r.filter(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:r.fromEvent(a,"durationchange").pipe(r.map(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:u,playbackRateState$:d,inPiP$:b,inFullscreen$:k}},mi=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let Ci=!1,st={};const oa=a=>{Ci=a},ua=()=>{st={}},ca=a=>{a(st)},Kt=(a,e)=>{Ci&&(st.meta=st.meta??{},st.meta[a]=e)};class Ge{name;constructor(e){this.name=e}next(e){if(!Ci)return;st.series=st.series??{};const t=st.series[this.name]??[];t.push([Date.now(),e]),st.series[this.name]=t}}var gt;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(gt||(gt={}));const da=new Ge("best_bitrate"),la=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class ls{last;history={};recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ha='Assertion "ABR Tracks is empty array" failed',Tt=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:d,history:c,droppedVideoMaxQualityLimit:h,abrLogger:l})=>{r.assertNotEmptyArray(a,ha);const f=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*i.containerSizeFactor,height:e.height*f*i.containerSizeFactor},g=p&&r.videoSizeToQuality(p),y=i.considerPlaybackRate&&r.isNonNullable(u)?u:1,b=a.filter(S=>!r.isInvariantQuality(S.quality)).sort((S,L)=>r.isHigher(S.quality,L.quality)?-1:1),k=b.at(-1)?.quality,A=b.at(0)?.quality,m=r.isNullable(s)||r.isNonNullable(s.min)&&r.isNonNullable(s.max)&&r.isLower(s.max,s.min)||r.isNonNullable(s.min)&&A&&r.isHigher(s.min,A)||r.isNonNullable(s.max)&&k&&r.isLower(s.max,k),T=y*la(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},_=b.filter(S=>(g?r.isLower(S.quality,g):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(S.bitrate)?t-n>=S.bitrate*T:!0)?i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!r.isInvariantQuality(d.quality)&&(o??0)<i.minBufferToSwitchUp&&r.isHigher(S.quality,d.quality)?($[S.quality]=gt.Buffer,!1):!!h&&r.isHigherOrEqual(S.quality,h)?($[S.quality]=gt.DroppedFramesLimit,!1):m||(r.isNullable(s.max)||r.isLowerOrEqual(S.quality,s.max))&&(r.isNullable(s.min)||r.isHigherOrEqual(S.quality,s.min))?!0:($[S.quality]=gt.FitsQualityLimits,!1):($[S.quality]=gt.FitsThroughput,!1):($[S.quality]=gt.FitsContainer,!1))[0];_&&_.bitrate&&da.next(_.bitrate);const C=_??b[Math.ceil((b.length-1)/2)]??a[0];C.quality!==c?.last?.quality&&l({message:`
|
|
6
|
+
"use strict";var Ms=Object.create;var Ii=Object.defineProperty;var Vs=Object.getOwnPropertyDescriptor;var Fs=Object.getOwnPropertyNames;var Os=Object.getPrototypeOf,Us=Object.prototype.hasOwnProperty;var Hs=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fs(e))!Us.call(a,s)&&s!==t&&Ii(a,s,{get:()=>e[s],enumerable:!(i=Vs(e,s))||i.enumerable});return a};var Ni=(a,e,t)=>(t=a!=null?Ms(Os(a)):{},Hs(e||!a||!a.__esModule?Ii(t,"default",{value:a,enumerable:!0}):t,a));var r=require("@vkontakte/videoplayer-shared/esnext.cjs.js");const us="2.0.98-dev.97d8def3.0";exports.PlaybackState=void 0;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(a){a.MPEG="MPEG",a.DASH="DASH",a.DASH_SEP="DASH_SEP",a.DASH_SEP_VK="DASH_SEP",a.DASH_WEBM="DASH_WEBM",a.DASH_WEBM_AV1="DASH_WEBM_AV1",a.DASH_WEBM_VK="DASH_WEBM",a.DASH_ONDEMAND="DASH_ONDEMAND",a.DASH_ONDEMAND_VK="DASH_ONDEMAND",a.DASH_LIVE="DASH_LIVE",a.DASH_LIVE_CMAF="DASH_LIVE_CMAF",a.DASH_LIVE_WEBM="DASH_LIVE_WEBM",a.HLS="HLS",a.HLS_ONDEMAND="HLS_ONDEMAND",a.HLS_JS="HLS",a.HLS_LIVE="HLS_LIVE",a.HLS_LIVE_CMAF="HLS_LIVE_CMAF",a.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var ge;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ge||(ge={}));exports.ChromecastState=void 0;(function(a){a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(a){a.HTTP1="http1",a.HTTP2="http2",a.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var V;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(V||(V={}));exports.Surface=void 0;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip"})(exports.Surface||(exports.Surface={}));var js=a=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Ys{connection$=new r.ValueSubject(void 0);castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new r.Subject;contentId;realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new r.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 i=r.isNonNullable(window.chrome?.cast),s=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},s||js("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.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(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.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),i=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return r.assertNever(s.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),r.map(s=>s.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(Gs),r.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{const n=s===exports.ChromecastState.CONNECTED,o=r.isNonNullable(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();r.assertNonNullable(u);const d=u.getCastDevice(),c=u.getMediaSession()?.media.contentId;(r.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}}const Gs=a=>{switch(a){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 r.assertNever(a)}};var X;(function(a){a[a.OFFSET_P=0]="OFFSET_P",a[a.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",a[a.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(X||(X={}));var Se=(a,e=0,t=X.OFFSET_P)=>{switch(t){case X.OFFSET_P:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case X.PLAYBACK_SHIFT:{if(e===0)return a;const i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case X.DASH_CMAF_OFFSET_P:{const i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:r.assertNever(t)}return a};const si=(a,e)=>{switch(e){case X.OFFSET_P:return NaN;case X.PLAYBACK_SHIFT:{const t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case X.DASH_CMAF_OFFSET_P:{const t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:r.assertNever(e)}};var w=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class q{state;prevState;transition;transitionStarted$=new r.Subject;transitionEnded$=new r.Subject;transitionUpdated$=new r.Subject;forceChanged$=new r.Subject;stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=r.merge(this.transitionEnded$,this.forceChanged$);constructor(e){this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||r.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const zs=a=>{switch(a){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.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(a)}};var B;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(B||(B={}));const qs=5,Ws=5,Qs=500,_i=7e3;class Js{subscription=new r.Subscription;loadMediaTimeoutSubscription=new r.Subscription;videoState=new q(B.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(zs(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(r.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new r.Subject;e.add(s.pipe(r.debounce(Qs)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const u=o.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state===V.Applying||Math.abs(u-n)>qs)&&s.next(u),n=u})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,u=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(u!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Ws&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(B.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:V.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===B.PAUSED||e===B.PLAYING)&&(this.videoState.setState(B.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===B.PLAYING||e===B.PAUSED)&&(this.videoState.setState(B.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===B.READY&&this.videoState.setState(B.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==B.STOPPED&&this.videoState.setState(B.STOPPED)}handleRemoteVolumeChange(e){const t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){const t=this.params.source;let i,s,n;switch(e){case exports.VideoFormat.MPEG:{const c=t[e];r.assertNonNullable(c);const h=r.getHighestQuality(Object.keys(c));r.assertNonNullable(h);const l=c[h];r.assertNonNullable(l),i=l,s="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=t[e];r.assertNonNullable(c),i=c.url,s="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:case exports.VideoFormat.DASH_WEBM_AV1:{const c=t[e];r.assertNonNullable(c),i=c.url,s="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=t[e];r.assertNonNullable(c),i=c.url,s="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=t[e];r.assertNonNullable(c),i=Se(c.url),s="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 c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,s);o.contentUrl=i,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return r.isNonNullable(u)&&(o.metadata.title=u),r.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===V.Applying||i.state===V.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(_i).subscribe(()=>n(`timeout(${_i})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.stop());return}if(!t){if(s?.to!==exports.PlaybackState.PAUSED&&n.state===V.Requested&&e!==B.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case B.PLAYING:case B.PAUSED:case B.READY:break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case B.PLAYING:break;case B.PAUSED:this.videoState.startTransitionTo(B.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case B.READY:this.videoState.startTransitionTo(B.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case B.PLAYING:this.videoState.startTransitionTo(B.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case B.PAUSED:break;case B.READY:this.videoState.startTransitionTo(B.PAUSED),this.videoState.setState(B.PAUSED);break;case B.STOPPED:this.videoState.startTransitionTo(B.READY),this.prepare();break;default:r.assertNever(e)}break}default:r.assertNever(i)}}}}var Xs=a=>{let e,t=!1,i=!1;a.on("playbackTimeUpdated",({timeToEnd:s})=>{i=s<=3,t&&i&&e?.()}),a.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&e?.()}}},!0)},Ks=a=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),s=new r.ValueSubject(void 0);let n=NaN,o=!1;const u=()=>{n=Date.now(),o=!1},d=h=>{const l=Object.fromEntries(h.getAllResponseHeaders().trim().split(/[\n\r]+/).map(g=>g.split(": ")));if("x-playback-duration"in l||"x-playback-duration-millis"in l){const g=parseInt(h.getResponseHeader("X-Playback-Duration")??"",10),b=parseInt(h.getResponseHeader("X-Playback-Duration-Millis")??"",10)??g*1e3??NaN;r.isNonNullable(b)&&!isNaN(b)&&e.next(b)}const f=l["x-delivery-type"]??exports.HttpConnectionType.HTTP1,p={1:!0,0:!1}[l["x-reused"]]??void 0;i.next(f),s.next(p)},c=h=>{h.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return a.extend("XHRLoader",function(){const{parent:h}=this,l=h.load.bind(h);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,g=f.progress;f.onload=function(...y){return d(this),p(...y)},f.progress=function(...y){return c(this),g(...y)},u()}return l(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:i}},ct=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Zs=a=>a.extend("RequestModifier",()=>({modifyRequestURL:ct}),!0),ea=a=>{a.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[s,n]=i.request.range.split("-").map(u=>parseInt(u,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Ve=(a,e,t,{equal:i=(o,u)=>o===u,changed$:s,onError:n}={})=>{const o=a.getState(),u=e(),d=r.isNullable(s),c=new r.Subscription;return s&&c.add(s.subscribe(h=>{const l=a.getState();i(h,l)&&a.setState(h)},n)),i(u,o)||(t(o),d&&a.setState(o)),c.add(a.stateChangeStarted$.subscribe(h=>{t(h.to),d&&a.setState(h.to)},n)),c},dt=(a,e,t)=>Ve(e,()=>a.loop,i=>{r.isNonNullable(i)&&(a.loop=i)},{onError:t}),Qe=(a,e,t,i)=>Ve(e,()=>({muted:a.muted,volume:a.volume}),s=>{r.isNonNullable(s)&&(a.muted=s.muted,a.volume=s.volume)},{equal:(s,n)=>s===n||s?.muted===n?.muted&&s?.volume===n?.volume,changed$:t,onError:i}),rt=(a,e,t,i)=>Ve(e,()=>a.playbackRate,s=>{r.isNonNullable(s)&&(a.playbackRate=s)},{changed$:t,onError:i}),ta=a=>["__",a.language,a.label].join("|"),ia=(a,e)=>{if(a.id===e)return!0;const[t,i,s]=e.split("|");return a.language===i&&a.label===s};class Fe{available$=new r.Subject;current$=new r.ValueSubject(void 0);error$=new r.Subject;video;cueSettings;subscription=new r.Subscription;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ve(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:s})),this.subscription.add(Ve(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:u},d)=>u===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ve(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:s})),this.subscription.add(Ve(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,s)=>i.length===s.length&&i.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const s=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",s))};i.track?.addEventListener("cuechange",s)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const s=i;r.isNonNullable(t.align)&&(s.align=t.align),r.isNonNullable(t.position)&&(s.position=t.position),r.isNonNullable(t.size)&&(s.size=t.size),r.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Fe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,s=e.id?e.id:ta(e),n=this.externalTracks.has(s),o=s.includes("auto");return n?{id:s,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(s)?.url}:{id:s,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(s)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:s,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===s&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(s=>s.id===i)).forEach(([,i])=>this.detach(i))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!ia(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){r.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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Di=a=>{a.removeAttribute("src"),a.load()},sa=a=>{try{a.pause(),a.playbackRate=0,Di(a),a.remove()}catch(e){console.error(e)}};class aa{attribute="data-pool-reused";get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const vi=window.WeakMap?new WeakMap:new aa,Je=a=>{let e=a.querySelector("video");const t=!!e;return e?Di(e):(e=document.createElement("video"),a.appendChild(e)),vi.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Xe=a=>{const e=vi.get(a);vi.delete(a),e?Di(a):sa(a)};class Wt{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const cs=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Bi=a=>{const e=cs(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ra=a=>{const e=cs(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},Ei=3;class na{_buffer=[];_source;constructor(e){this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Ei&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Ei))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,u=n>=e&&n<t;o&&u||(o?i(t,n):u?i(s,e):s<e&&n>t?(i(t,n),i(s,e)):i(s,n))})}destroy(){this._buffer=[]}}var ds=(a,e,t=Ei)=>{let i=0,s=0;for(let n=0;n<a.length;n++){const o=a.start(n),u=a.end(n);if(o<=e&&e<=u){if(i=o,s=u,!t)return{from:i,to:s};for(let d=n-1;d>=0;d--)a.end(d)+t>=i&&(i=a.start(d));for(let d=n+1;d<a.length;d++)a.start(d)-t<=s&&(s=a.end(d))}}return{from:i,to:s}};const Ke=a=>{const e=m=>r.fromEvent(a,m).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(m=>r.fromEvent(a,m))).pipe(r.map(m=>m.type==="ended"?a.readyState<2:a.readyState<3),r.filterChanged()),s=r.merge(r.fromEvent(a,"progress"),r.fromEvent(a,"timeupdate")).pipe(r.map(()=>ds(a.buffered,a.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),u=r.fromEvent(a,"volumechange").pipe(r.map(()=>({muted:a.muted,volume:a.volume}))),d=r.fromEvent(a,"ratechange").pipe(r.map(()=>a.playbackRate)),c=r.fromEvent(a,"error").pipe(r.filter(()=>!!(a.error||a.played.length)),r.map(()=>{const m=a.error;return{id:m?`MediaError#${m.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:m?m.message:"Error event from HTML video element",thrown:a.error??void 0}})),h=r.fromEvent(a,"timeupdate").pipe(r.map(()=>a.currentTime)),l=new r.Subject,f=.3;let p;h.subscribe(m=>{a.loop&&r.isNonNullable(p)&&r.isNonNullable(m)&&p>=a.duration-f&&m<=f&&l.next(p),p=m});const g=r.fromEvent(a,"enterpictureinpicture"),y=r.fromEvent(a,"leavepictureinpicture"),b=new r.ValueSubject(ra(a));g.subscribe(()=>b.next(!0)),y.subscribe(()=>b.next(!1));const k=new r.ValueSubject(Bi(a));return r.fromEvent(a,"fullscreenchange").pipe(r.map(()=>Bi(a))).subscribe(k),{playing$:o,pause$:e("pause").pipe(r.filter(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:r.fromEvent(a,"durationchange").pipe(r.map(()=>a.duration)),isBuffering$:i,currentBuffer$:s,volumeState$:u,playbackRateState$:d,inPiP$:b,inFullscreen$:k}},mi=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};let Ci=!1,st={};const oa=a=>{Ci=a},ua=()=>{st={}},ca=a=>{a(st)},Kt=(a,e)=>{Ci&&(st.meta=st.meta??{},st.meta[a]=e)};class Ge{name;constructor(e){this.name=e}next(e){if(!Ci)return;st.series=st.series??{};const t=st.series[this.name]??[];t.push([Date.now(),e]),st.series[this.name]=t}}var gt;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(gt||(gt={}));const da=new Ge("best_bitrate"),la=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class ls{last;history={};recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ha='Assertion "ABR Tracks is empty array" failed',Tt=(a,{container:e,throughput:t,tuning:i,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:d,history:c,droppedVideoMaxQualityLimit:h,abrLogger:l})=>{r.assertNotEmptyArray(a,ha);const f=i.usePixelRatio?window.devicePixelRatio??1:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*i.containerSizeFactor,height:e.height*f*i.containerSizeFactor},g=p&&r.videoSizeToQuality(p),y=i.considerPlaybackRate&&r.isNonNullable(u)?u:1,b=a.filter(S=>!r.isInvariantQuality(S.quality)).sort((S,L)=>r.isHigher(S.quality,L.quality)?-1:1),k=b.at(-1)?.quality,A=b.at(0)?.quality,m=r.isNullable(s)||r.isNonNullable(s.min)&&r.isNonNullable(s.max)&&r.isLower(s.max,s.min)||r.isNonNullable(s.min)&&A&&r.isHigher(s.min,A)||r.isNonNullable(s.max)&&k&&r.isLower(s.max,k),T=y*la(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},_=b.filter(S=>(g?r.isLower(S.quality,g):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(S.bitrate)?t-n>=S.bitrate*T:!0)?i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!r.isInvariantQuality(d.quality)&&(o??0)<i.minBufferToSwitchUp&&r.isHigher(S.quality,d.quality)?($[S.quality]=gt.Buffer,!1):!!h&&r.isHigherOrEqual(S.quality,h)?($[S.quality]=gt.DroppedFramesLimit,!1):m||(r.isNullable(s.max)||r.isLowerOrEqual(S.quality,s.max))&&(r.isNullable(s.min)||r.isHigherOrEqual(S.quality,s.min))?!0:($[S.quality]=gt.FitsQualityLimits,!1):($[S.quality]=gt.FitsThroughput,!1):($[S.quality]=gt.FitsContainer,!1))[0];_&&_.bitrate&&da.next(_.bitrate);const C=_??b[Math.ceil((b.length-1)/2)]??a[0];C.quality!==c?.last?.quality&&l({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${a.map(S=>`{ id: ${S.id}, quality: ${S.quality}, bitrate: ${S.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -42,5 +42,5 @@ precision highp float;
|
|
|
42
42
|
#define GLSLIFY 1
|
|
43
43
|
#endif
|
|
44
44
|
#define PI 3.14159265358979323846264
|
|
45
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class ks{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new wr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ar(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(s,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Pr,this.gl.VERTEX_SHADER),i=this.createShader(Dr,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:i=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,n=e-i,o=t-s,u=e+i,d=t-s,c=e+i,h=t+s,l=e-i,f=t+s;return[n,o,u,d,c,h,l,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let $s=class{scene3D;subscription=new r.Subscription;videoState=new q(Z.STOPPED);video;player;params;elementSize$=new r.ValueSubject(void 0);textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ls;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new $r({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Ke(this.video),s=this.constructor.name,n=u=>{e.error$.next({id:s,category:r.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:u})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(u,d)=>this.subscription.add(u.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(r.map(c=>c.map(({track:h})=>h)))}),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.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(rt(this.video,t.playbackRate,i.playbackRateState$,s)),n(zt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===Ce.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();r.assertNonNullable(l,"Manifest not loaded or empty");const f=Array.from(l.audio).sort((b,k)=>k.bitrate-b.bitrate),p=Array.from(l.video).sort((b,k)=>k.bitrate-b.bitrate),g=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const k=yr(b);k&&this.audioTracks.push({track:k,representation:b})}for(const b of p){const k=Sr(b);if(k){h.push({track:k,representation:b});const A=!this.params.tuning.isAudioDisabled&&Tr(f,p,b);A&&this.audioRepresentations.set(b.id,A)}}this.videoTracks$.next(h);for(const b of g){const k=vr(b);k&&this.textTracks.push({track:k,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const y=this.selectVideoRepresentation();r.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else c===Ce.REPRESENTATIOS_READY&&(this.videoState.setState(Z.READY),this.player.initBuffer())},s));const o=c=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!==Ce.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l){this.player.switchRepresentation(fe.VIDEO,l.id).catch(o);const p=this.audioRepresentations.get(l.id);p&&this.player.switchRepresentation(fe.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(c=>c&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(r.map(({to:c})=>c===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(r.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),n=ke(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=Tt(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?c??i:i??c;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Z.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-o,s.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case Z.STOPPED:this.videoState.startTransitionTo(Z.READY),this.prepare();return;case Z.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Z.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ks(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){nt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Z.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}},Cr=class extends $s{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var pe;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(pe||(pe={}));var Ye;(function(a){a[a.ActiveLowLatency=0]="ActiveLowLatency",a[a.LiveWithTargetOffset=1]="LiveWithTargetOffset",a[a.LiveForwardBuffering=2]="LiveForwardBuffering",a[a.None=3]="None"})(Ye||(Ye={}));var di;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(di||(di={}));var Re;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Re||(Re={}));var M;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(M||(M={}));var xt;(function(a){a.MP4="mp4",a.WEBM="webm"})(xt||(xt={}));var li;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(li||(li={}));var ee;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(ee||(ee={}));let ws=!1;try{ws=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Lr{bufferFull$=new r.Subject;error$=new r.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(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;ws&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:r.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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:r.assertNever(t)}}}class Ne{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class As extends Ne{}class xr extends Ne{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Rr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Ir extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Nr extends Ne{data;constructor(e){super(e),this.data=this.content}}class ot extends Ne{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class _r extends ot{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const u=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}}class Br extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Mr extends Ne{parseChildrenBoxes(){return lt(this.content)}}var St;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(St||(St={}));class Vr extends ot{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=St.MONOSCOPIC;break;case 1:this.stereoMode=St.TOP_BOTTOM;break;case 2:this.stereoMode=St.LEFT_RIGHT;break;case 3:this.stereoMode=St.STEREO_CUSTOM;break;case 4:this.stereoMode=St.RIGHT_LEFT;break}this.cursor+=1}}class Fr extends ot{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Or extends ot{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ur extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Hr extends ot{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class jr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Yr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Gr extends ot{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class zr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class qr extends ot{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Wr extends ot{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Qr extends ot{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e){super(e),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Jr={ftyp:xr,moov:Rr,moof:Ir,mdat:Nr,sidx:_r,trak:Br,mdia:Ur,mfhd:Gr,tkhd:Hr,traf:zr,tfhd:qr,tfdt:Wr,trun:Qr,minf:jr,sv3d:Mr,st3d:Vr,prhd:Fr,proj:Yr,equi:Or,unknown:As};class Xr{createBox(e,t){const i=Jr[e];return i?new i(t):new As(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Si.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Si=new Xr;function jt(a,e){const t=new Uint8Array(a.buffer),i=e.split("").map(o=>o.charCodeAt(0));let s=a.byteOffset,n=[];for(;s<t.byteLength;){if(t[s]===i[n.length]?n.push(t[s]):n=[],n.length===4){const u=new DataView(a.buffer,s-7,4).getUint32(0);return s-7+u>a.buffer.byteLength?null:Si.createBox(e,new DataView(a.buffer,s-7))}s++}return null}function $i(a,e){const t=[];let i=a.byteOffset;for(;i<a.buffer.byteLength;){const s=jt(new DataView(a.buffer,i,a.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function lt(a){const e=[];let t=0;for(;t<a.byteLength;){const i=Si.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Kr=new TextDecoder("ascii"),Zr=a=>Kr.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",en=a=>{const e=Si.createFromView(a);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,u={status:M.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,u})},tn=a=>{const e=$i(a,"mdat"),t=$i(a,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],n=i.source.byteOffset,u=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(a.buffer,n,u)},sn=(a,e)=>{const t=$i(a,"traf"),i=t[t.length-1].children.find(d=>d.type==="tfhd"),s=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,c)=>d+c,0):o=i.defaultSampleDuration*n.sampleCount,(Number(s.baseMediaDecodeTime)+o)/e*1e3},an=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(jt(a,"sv3d")){e.is3dVideo=!0;const i=jt(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=jt(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=jt(a,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},rn={validateData:Zr,parseInit:an,getIndexRange:()=>{},parseSegments:en,parseFeedableSegmentChunk:tn,getSegmentEndTime:sn};var E;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(E||(E={}));var D;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(D||(D={}));const Gi={[E.EBML]:{type:D.Master},[E.EBMLVersion]:{type:D.UnsignedInteger},[E.EBMLReadVersion]:{type:D.UnsignedInteger},[E.EBMLMaxIDLength]:{type:D.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[E.DocType]:{type:D.String},[E.DocTypeVersion]:{type:D.UnsignedInteger},[E.DocTypeReadVersion]:{type:D.UnsignedInteger},[E.Void]:{type:D.Binary},[E.Segment]:{type:D.Master},[E.SeekHead]:{type:D.Master},[E.Seek]:{type:D.Master},[E.SeekID]:{type:D.Binary},[E.SeekPosition]:{type:D.UnsignedInteger},[E.Info]:{type:D.Master},[E.TimestampScale]:{type:D.UnsignedInteger},[E.Duration]:{type:D.Float},[E.Tracks]:{type:D.Master},[E.TrackEntry]:{type:D.Master},[E.Video]:{type:D.Master},[E.Projection]:{type:D.Master},[E.ProjectionType]:{type:D.UnsignedInteger},[E.ProjectionPrivate]:{type:D.Master},[E.Chapters]:{type:D.Master},[E.Cluster]:{type:D.Master},[E.Timestamp]:{type:D.UnsignedInteger},[E.SilentTracks]:{type:D.Master},[E.SilentTrackNumber]:{type:D.UnsignedInteger},[E.Position]:{type:D.UnsignedInteger},[E.PrevSize]:{type:D.UnsignedInteger},[E.SimpleBlock]:{type:D.Binary},[E.BlockGroup]:{type:D.Master},[E.EncryptedBlock]:{type:D.Binary},[E.Attachments]:{type:D.Master},[E.Tags]:{type:D.Master},[E.Cues]:{type:D.Master},[E.CuePoint]:{type:D.Master},[E.CueTime]:{type:D.UnsignedInteger},[E.CueTrackPositions]:{type:D.Master},[E.CueTrack]:{type:D.UnsignedInteger},[E.CueClusterPosition]:{type:D.UnsignedInteger},[E.CueRelativePosition]:{type:D.UnsignedInteger},[E.CueDuration]:{type:D.UnsignedInteger},[E.CueBlockNumber]:{type:D.UnsignedInteger},[E.CueCodecState]:{type:D.UnsignedInteger},[E.CueReference]:{type:D.Master},[E.CueRefTime]:{type:D.UnsignedInteger}},Ps=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=hi(a,t),s=i in Gi,n=s?Gi[i].type:D.Binary,o=a.getUint8(t);let u=0;o&128?u=1:o&64?u=2:o&32?u=3:o&16?u=4:o&8?u=5:o&4?u=6:o&2?u=7:o&1&&(u=8);const d=new DataView(a.buffer,a.byteOffset+t+1,u-1),c=o&255>>u,h=hi(d),l=c*2**((u-1)*8)+h,f=t+u;let p;return f+l>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,l),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+l,value:p,valueSize:l}},hi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},qe=(a,e)=>{switch(e){case D.SignedInteger:return a.getInt8(0);case D.UnsignedInteger:return hi(a);case D.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(a);case D.UTF8:return new TextDecoder("utf-8").decode(a);case D.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case D.Master:return a;case D.Binary:return a;default:r.assertNever(e)}},Rt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=Ps(i);if(!e(s))return;s.type===D.Master&&Rt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},nn=a=>{if(a.getUint32(0)!==E.EBML)return!1;let e,t,i;const s=Ps(a);return Rt(s.value,({tag:n,type:o,value:u})=>(n===E.EBMLReadVersion?e=qe(u,o):n===E.DocType?t=qe(u,o):n===E.DocTypeReadVersion&&(i=qe(u,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ds=[E.Info,E.SeekHead,E.Tracks,E.TrackEntry,E.Video,E.Projection,E.ProjectionType,E.ProjectionPrivate,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],on=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],un=a=>{let e,t,i,s,n=!1,o=!1,u=!1,d,c,h=!1;const l=0;return Rt(a,({tag:f,type:p,value:g,valueSize:y})=>{if(f===E.SeekID){const b=qe(g,p);c=hi(b)}else f!==E.SeekPosition&&(c=void 0);return f===E.Segment?(e=g.byteOffset,t=g.byteOffset+y):f===E.Info?n=!0:f===E.SeekHead?o=!0:f===E.TimestampScale?i=qe(g,p):f===E.Duration?s=qe(g,p):f===E.SeekPosition&&c===E.Cues?d=qe(g,p):f===E.Tracks?Rt(g,({tag:b,type:k,value:A})=>b===E.ProjectionType?(h=qe(A,k)===1,!1):!0):n&&o&&Ds.includes(f)&&(u=!0),!u}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:l,projectionType:li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},cn=a=>{if(r.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},dn=(a,e)=>{let t=!1,i=!1;const s=u=>r.isNonNullable(u.time)&&r.isNonNullable(u.position),n=[];let o;return Rt(a,({tag:u,type:d,value:c})=>{switch(u){case E.Cues:t=!0;break;case E.CuePoint:o&&s(o)&&n.push(o),o={};break;case E.CueTime:o&&(o.time=qe(c,d));break;case E.CueTrackPositions:break;case E.CueClusterPosition:o&&(o.position=qe(c,d));break;default:t&&Ds.includes(u)&&(i=!0)}return!(t&&i)}),o&&s(o)&&n.push(o),n.map((u,d)=>{const{time:c,position:h}=u,l=n[d+1];return{status:M.NONE,time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},ln=a=>{let e=0,t=!1;try{Rt(a,i=>i.tag===E.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):on.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},hn={validateData:nn,parseInit:un,getIndexRange:cn,parseSegments:dn,parseFeedableSegmentChunk:ln},zi=a=>{if(!a.startsWith("P"))return;const e=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),s=i?.[1]==="-"?-1:1,n={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},wt=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(i)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(u,d)=>r.isNullable(n)?u:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},fn=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],u=o.children,d=n.getAttribute("type")==="dynamic",c=n.getAttribute("availabilityStartTime"),h=c?new Date(c).getTime():void 0;let l;const f=n.getAttribute("mediaPresentationDuration"),p=o.getAttribute("duration"),y=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)l=zi(f);else if(p){const m=zi(p);r.isNonNullable(m)&&(l=m)}else y&&(l=parseInt(y,10));let b=0;const k=n.getAttribute("profiles")?.split(",")??[],A=k.includes(di.WEBM_AS_IN_FFMPEG)||k.includes(di.WEBM_AS_IN_SPEC)?xt.WEBM:xt.MP4;for(const m of u){const T=m.getAttribute("mimeType"),$=m.getAttribute("codecs"),R=m.getAttribute("contentType")??T?.split("/")[0],_=m.getAttribute("profiles")?.split(",")??[],C=m.querySelectorAll("Representation"),I=m.querySelector("SegmentTemplate");if(R===pe.TEXT){for(const S of C){const L=S.getAttribute("id")||"",N=m.getAttribute("lang"),j=S.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(j,e).toString(),ne=L.includes("_auto");s[pe.TEXT].push({id:L,lang:N,isAuto:ne,kind:pe.TEXT,url:ie})}continue}for(const S of C){const L=S.getAttribute("mimeType")??T,N=S.getAttribute("codecs")??$??"",j=S.getAttribute("contentType")??L?.split("/")[0]??R,ie=m.getAttribute("profiles")?.split(",")??[],ne=parseInt(S.getAttribute("width")??"",10),x=parseInt(S.getAttribute("height")??"",10),G=parseInt(S.getAttribute("bandwidth")??"",10)/1e3,K=S.getAttribute("frameRate")??"",oe=S.getAttribute("quality")??void 0,me=K?mi(K):void 0,Oe=S.getAttribute("id")??(b++).toString(10),_t=j==="video"?`${x}p`:j==="audio"?`${G}Kbps`:N,vt=`${Oe}@${_t}`,z=S.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(z,e).toString(),Te=[...k,..._,...ie];let de;const et=S.querySelector("SegmentBase"),se=S.querySelector("SegmentTemplate")??I;if(et){const ue=S.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[le,Ue]=ue.split("-").map(we=>parseInt(we,10)),ve={from:le,to:Ue},_e=S.querySelector("SegmentBase")?.getAttribute("indexRange"),[ht,tt]=_e?_e.split("-").map(we=>parseInt(we,10)):[],Be=_e?{from:ht,to:tt}:void 0;de={type:Re.BYTE_RANGE,url:ce,initRange:ve,indexRange:Be}}else if(se){const ue={representationId:S.getAttribute("id")??void 0,bandwidth:S.getAttribute("bandwidth")??void 0},le=parseInt(se.getAttribute("timescale")??"",10),Ue=se.getAttribute("initialization")??"",ve=se.getAttribute("media"),_e=parseInt(se.getAttribute("startNumber")??"",10)??1,ht=wt(Ue,ue);if(!ve)throw new ReferenceError("No media attribute in SegmentTemplate");const tt=se.querySelectorAll("SegmentTimeline S")??[],Be=[];let we=0,ft="",Ae=0;if(tt.length){let Pe=_e,ae=0;for(const Me of tt){const Ee=parseInt(Me.getAttribute("d")??"",10),He=parseInt(Me.getAttribute("r")??"",10)||0,it=parseInt(Me.getAttribute("t")??"",10);ae=Number.isFinite(it)?it:ae;const Bt=Ee/le*1e3,Xt=ae/le*1e3;for(let Et=0;Et<He+1;Et++){const _s=wt(ve,{...ue,segmentNumber:Pe.toString(10),segmentTime:(ae+Et*Ee).toString(10)}),Ri=(Xt??0)+Et*Bt,Bs=Ri+Bt;Pe++,Be.push({time:{from:Ri,to:Bs},url:_s})}ae+=(He+1)*Ee,we+=(He+1)*Bt}Ae=ae/le*1e3,ft=wt(ve,{...ue,segmentNumber:Pe.toString(10),segmentTime:ae.toString(10)})}else if(r.isNonNullable(l)){const ae=parseInt(se.getAttribute("duration")??"",10)/le*1e3,Me=Math.ceil(l/ae);let Ee=0;for(let He=1;He<Me;He++){const it=wt(ve,{...ue,segmentNumber:He.toString(10),segmentTime:Ee.toString(10)});Be.push({time:{from:Ee,to:Ee+ae},url:it}),Ee+=ae}Ae=Ee,ft=wt(ve,{...ue,segmentNumber:Me.toString(10),segmentTime:Ee.toString(10)})}const pt={time:{from:Ae,to:1/0},url:ft};de={type:Re.TEMPLATE,baseUrl:ce,segmentTemplateUrl:ve,initUrl:ht,totalSegmentsDurationMs:we,segments:Be,nextSegmentBeyondManifest:pt,timescale:le}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!L)continue;const $e={video:pe.VIDEO,audio:pe.AUDIO,text:pe.TEXT}[j];$e&&s[$e].push({id:vt,kind:$e,segmentReference:de,profiles:Te,duration:l,bitrate:G,mime:L,codecs:N,width:ne,height:x,fps:me,quality:oe})}}return{dynamic:d,liveAvailabilityStartTime:h,duration:l,container:A,representations:s}},pn=({id:a,width:e,height:t,bitrate:i,fps:s,quality:n})=>{const o=(n?It(n):void 0)??r.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:s}},mn=({id:a,bitrate:e})=>({id:a,bitrate:e}),gn=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},bn=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),qi=a=>"size"in a,kt=a=>a.type===Re.TEMPLATE,wi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);class Wi{onLastSegment$=new r.ValueSubject(!1);fullyBuffered$=new r.ValueSubject(!1);playingRepresentation$=new r.ValueSubject(void 0);playingRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;gaps=[];subscription=new r.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Ie;destroyAbortController=new Ie;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;constructor(e,t,i,s,{fetcher:n,tuning:o,getCurrentPosition:u,isActiveLowLatency:d,compatibilityMode:c=!1,manifest:h}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=c,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=u,this.isActiveLowLatency=d,this.isLive=!!h?.dynamic,this.container=i,i){case xt.MP4:this.containerParser=rn;break;case xt.WEBM:this.containerParser=hn;break;default:r.assertNever(i)}this.initData=new Map(s.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=r.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);r.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 Lr(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const u=Math.min(this.bufferLimit,ui(this.sourceBuffer.buffered)*.8);this.bufferLimit=u,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),n=this.parsedInitData.get(t.id);r.assertNonNullable(i,"No init buffer for starting representation"),r.assertNonNullable(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=r.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);r.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(r.isNullable(s)||r.isNullable(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),r.assertNonNullable(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const n=this.getCurrentPosition();r.isNonNullable(n)&&(this.isLive||(i.forEach(o=>o.status=M.NONE),this.pruneBuffer(n,1/0,!0)),this.maintain(n))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ie,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(c=>e>=c.time.from&&e<c.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=ke(this.sourceBuffer.buffered,e),l=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=s.time.to-e+100&&(n=l)}if(isFinite(this.bufferLimit)&&ui(this.sourceBuffer.buffered)>=this.bufferLimit){const c=ke(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,n),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(u.includes(s))c="high";else{const h=u.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===M.FED&&!u.length&&ke(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=i.at(-1);d&&d.status===M.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:n.time.from+s}),i=n.time.to;r.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let n=0,o=t.length-1;do s.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<i&&o>=0);return this.liveInitialAdditionalOffset=n-i,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=r.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const u of this.representations.keys()){const d=e.find(l=>l.id===u);d&&this.representations.set(u,d);const c=this.representations.get(u);if(!c||!kt(c.segmentReference))return;const h=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);r.assertNonNullable(i);const s=this.segments.get(t);r.assertNonNullable(s,"No segments for starting representation");const n=this.initData.get(t);if(r.assertNonNullable(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;const o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!kt(t.segmentReference))return;const i=t.segmentReference.segments.map(u=>({...u,status:M.NONE,size:void 0})),s=this.segments.get(t.id)??[],n=s.at(-1)?.time.to??0,o=i?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const u=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,u)}else{const u=i.slice(o+1);this.segments.set(t.id,[...s,...u])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!kt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=wt(i.segmentTemplateUrl,{segmentTime:s}),o=this.segments.get(t.id)??[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:M.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(n=>n.time.from<=e&&n.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:l,time:{from:f,to:p}},g)=>{const y=f<=i&&p>=i,b=f>i||y||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&f<=i+k||p<=i+k;return(l===M.NONE||l===M.PARTIALLY_EJECTED&&b&&A&&this.sourceBuffer&&!Ct(this.sourceBuffer.buffered,i))&&b&&A});if(s===-1)return[];if(t!==Re.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,u=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<n.length&&(o<=c||u<=h);l++){const f=n[l];if(o+=f.byte.to+1-f.byte.from,u+=f.time.to+1-f.time.from,f.status===M.NONE||f.status===M.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){t.segmentReference.type===Re.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=M.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:n,url:o,signal:u,onProgress:d,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await r.abortable(u,async function*(){const h=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,h))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(o,{range:n,signal:u,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!h)return;const l=new DataView(h);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(l,f)}d&&s.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,u),s.segment.status=M.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){if(!wi(h))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(h)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const d of e)d.status=M.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:n,signal:o,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await r.abortable(o,async function*(){const d=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:s,onProgress:u,signal:o,priority:i}),this.failedDownloads=0}catch(d){if(!wi(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}}prepareByteRangeFetchSegmentParams(e,t){if(kt(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,s={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:s,signal:n,onProgress:(d,c)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:c,signal:n,onSegmentAppendFailed:o,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!kt(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const s=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},u=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(h,l)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:h,loaded:l,signal:n,onSegmentAppendFailed:o,representationId:t.id});u.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:s,signal:n,onProgress:c,onProgressTasks:u}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(i)&&(t=ke(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const u of this.activeSegments){const{segment:d}=u;if(u.representationId===t){if(n.aborted){s();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){const c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(c);h?.byteLength&&(d.status=M.PARTIALLY_FED,u.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),u.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:l}=h,f=d===Re.BYTE_RANGE,p=f?l.byte.to-l.byte.from+1:c;if(h.representationId!==t||!(!f||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const y=f?l.byte.from-i:0,b=f?l.byte.to-i:e.byteLength,k=y<s,A=b<=s;if(l.status===M.DOWNLOADING&&k&&A){l.status=M.DOWNLOADED;const m=new DataView(e.buffer,e.byteOffset+y,p);this.sourceBufferTaskQueue.append(m,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(h,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&k&&(h.loadedBytes=Math.min(p,s-y),h.loadedBytes>h.feedingBytes)){const m=new DataView(e.buffer,e.byteOffset+y+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===p?m:this.containerParser.parseFeedableSegmentChunk(m);T?.byteLength&&(l.status=M.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then($=>{if(n.aborted)o();else if($)h.fedBytes+=T.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=M.FED,qi(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const s of this.segments.get(i.id)??[])s.status===M.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=M.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===M.PARTIALLY_FED||e.status===M.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=M.NONE),e.status=M.PARTIALLY_EJECTED):e.status=M.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=oi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async u=>{if(!u)return;const{init:d,dataView:c,segments:h}=u,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l);let f=h;this.isLive&&kt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,u=!1;const d=c=>{n=Math.min(n,c.time.from),o=Math.max(o,c.time.to);const h=qi(c)?c.size??0:c.byte.to-c.byte.from;s+=h};for(const c of this.segments.values())for(const h of c){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===M.FED&&d(h)}if(u=isFinite(n)&&isFinite(o),!u){s=0,n=1/0,o=-1/0;for(const c of this.segments.values())for(const h of c){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===M.FED&&d(h)}}if(u=isFinite(n)&&isFinite(o),!u)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const h=this.sourceBuffer.buffered.start(c)*1e3,l=this.sourceBuffer.buffered.end(c)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===M.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(l)){n=h,o=l;break}}if(u=isFinite(n)&&isFinite(o),!u&&i){s=0,n=1/0,o=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const l of h)l.time.from>e+c&&l.status===M.FED&&d(l)}return u=isFinite(n)&&isFinite(o),u?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)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,u=this.sourceBuffer.buffered.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){s=void 0;break}u>i.time.from&&u<i.time.to&&(s.from=u),o<i.time.to&&o>i.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=oi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:n})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:n}=s;if(n!==M.FED&&n!==M.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),u=Math.ceil(s.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=u),c=e.filter(h=>o>=h.from-t&&o<=h.to+t||u>=h.from-t&&u<=h.to+t);d||(c.length===1?s.status=M.PARTIALLY_EJECTED:s.status=M.NONE)}}}var Pt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(Pt||(Pt={}));class Sn{throughputEstimator;requestQuic;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);abortAllController=new Ie;subscription=new r.Subscription;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Li(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=r.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ct(t));const i=yield yt(t,{signal:this.abortAllController.signal}).catch(Ft);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=r.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:i,onProgress:s,priority:n="auto",signal:o,measureThroughput:u=!0,isLowLatency:d=!1}={}){let c=e;const h=new Headers;if(i)switch(t){case Pt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case Pt.PARAM:{const C=new URL(c,location.href);C.searchParams.append("bytes",`${i.from}-${i.to}`),c=C.toString();break}default:r.assertNever(t)}this.requestQuic&&(c=ct(c));let l=this.abortAllController.signal,f;if(o){const C=new Ie;if(f=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(o,"abort")).subscribe(()=>{try{C.abort()}catch(I){Ft(I)}}),this.abortAllController.signal.aborted||o.aborted)try{C.abort()}catch(I){Ft(I)}l=C.signal}const p=r.now(),g=yield yt(c,{priority:n,headers:h,signal:l}).catch(Ft),y=r.now();if(!g)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-p),!g.ok||!g.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!s&&!u)return f?.unsubscribe(),g.arrayBuffer();const[b,k]=g.body.tee(),A=b.getReader();u&&this.throughputEstimator?.trackStream(k,d);let m=0,T=new Uint8Array(0),$=!1;const R=C=>{f?.unsubscribe(),$=!0,Ft(C)},_=r.abortable(l,async function*({done:C,value:I}){if(m===0&&this.lastRequestFirstBytes$.next(r.now()-p),l.aborted){f?.unsubscribe();return}if(!C&&I){const S=new Uint8Array(T.length+I.length);S.set(T),S.set(I,T.length),T=S,m+=I.byteLength,s?.(new DataView(T.buffer),m),yield A?.read().then(_,R)}}.bind(this));return yield A?.read().then(_,R),f?.unsubscribe(),$?null:T.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Re.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Re.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:r.assertNever(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Re.BYTE_RANGE)return null;const{from:s,to:n}=e.initRange;let o=s,u=n,d=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,d=n+1===c,d&&(o=Math.min(c,s),u=Math.max(h,n))),o=Math.min(o,0);const l=yield this.fetch(e.url,{range:{from:o,to:u},priority:i,measureThroughput:!1});if(!l)return null;const f=new DataView(l,s-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const p=t.parseInit(f),g=e.indexRange??t.getIndexRange(p);if(!g)throw new ReferenceError("No way to load representation index");let y;if(d)y=new DataView(l,g.from-o,g.to-g.from+1);else{const k=yield this.fetch(e.url,{range:g,priority:i,measureThroughput:!1});if(!k)return null;y=new DataView(k)}const b=t.parseSegments(y,p,g);return{init:p,dataView:new DataView(l),segments:b}}.bind(this));fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==Re.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(o=>({...o,status:M.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const Ft=a=>{if(!wi(a))throw a},Ai=1e3,fi=(a,e,t)=>t*e+(1-t)*a,Cs=(a,e)=>a.reduce((t,i)=>t+i,0)/e,yn=(a,e,t,i)=>{let s=0,n=t;const o=Cs(a,e),u=e<i?e:i;for(let d=0;d<u;d++)a[n]>o?s++:s--,n=(a.length+n-1)%a.length;return Math.abs(s)===u};class xi{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ge(`raw_${t}`),this.smoothedSeries$=new Ge(`smoothed_${t}`),this.reportedSeries$=new Ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.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))}}class Tn extends xi{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=fi(this.slow,e,this.params.emaAlphaSlow),this.fast=fi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class vn extends xi{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Cs(this.pastMeasures,this.takenMeasures);this.emaSmoothed=fi(this.emaSmoothed,e,this.params.emaAlpha);const i=yn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class En extends xi{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?fi(this.smoothed,e,this.params.emaAlpha):e}}class Pi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Tn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new vn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new En({initial:e,label:"liveEdgeDelay",...t})}}const kn=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},Qi=["timeupdate","progress","play","seeked","stalled","waiting"];var Le;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(Le||(Le={}));let $n=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new r.Subscription;representationSubscription=new r.Subscription;fetcher;state$=new q(Le.NONE);currentVideoRepresentation$=new r.ValueSubject(void 0);currentVideoRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);isLive$=new r.ValueSubject(!1);liveDuration$=new r.ValueSubject(0);liveAvailabilityStartTime$=new r.ValueSubject(void 0);bufferLength$=new r.ValueSubject(0);liveLoadBufferLength$=new r.ValueSubject(0);livePositionFromPlayer$=new r.ValueSubject(0);liveEstimatedDelay;waitingEventInterval;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new r.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Ie;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Sn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Pi.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=r.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Se(t,i,X.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Le.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Le.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=r.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=fn(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`)||s===pe.TEXT);return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,n])=>[s,n.filter(i)]))}}.bind(this));async seekLive(e){r.assertNonNullable(this.element);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Se(this.manifestUrlString,t,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initRepresentations=r.abortable(this.destroyController.signal,async function*(e,t){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Le.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new Wi(pe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(t)&&(this.audioBufferManager=new Wi(pe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(r.interval(Ai).subscribe(o=>{if(this.element?.paused){const u=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=Se(this.manifestUrlString,u+Ai,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Qi.map(o=>r.fromEvent(this.element,o))).pipe(r.map(o=>this.element?ke(this.element.buffered,this.element.currentTime*1e3):0),r.filterChanged(),r.filter(o=>!!o),r.tap(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(r.filter(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,c=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,l=u-d;let f=1+Math.sign(l)*h;Math.abs(l)<c?f=1:Math.abs(l)>c*2&&(f=1+Math.sign(l)*h*2),kn(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{let d=0;if(u){const c=(this.element?.currentTime??0)*1e3;d=Math.min(...this.bufferManagers.map(l=>l.getLiveSegmentsToLoadState(this.manifest)?.to??0))-c}d&&this.liveLoadBufferLength$.getValue()!==d&&this.liveLoadBufferLength$.next(d)}));let o=0;this.representationSubscription.add(r.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:u,bufferLength:d})=>{if(r.assertNonNullable(this.element),this.isUpdatingLive)return;const c=this.element.playbackRate,h=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P),l=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(l,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*c),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*c,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,y=this.isActiveLowLatency?d:u;let b=Ye.None;if(this.isActiveLowLatency?b=Ye.ActiveLowLatency:y<f+g&&y>=f?b=Ye.LiveWithTargetOffset:h!==0&&y<f&&(b=Ye.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),b===Ye.LiveForwardBuffering||b===Ye.LiveWithTargetOffset){const k=o-(f+p),A=this.normolizeLiveOffset(Math.trunc(h+k/c)),m=Math.abs(A-h);let T;!u||m<=this.tuning.dashCmafLive.offsetCalculationError?T=h:A>0&&m>this.tuning.dashCmafLive.offsetCalculationError?T=A:T=0,this.manifestUrlString=Se(this.manifestUrlString,T,X.DASH_CMAF_OFFSET_P)}b!==Ye.None&&b!==Ye.ActiveLowLatency&&(o=0,this.updateLive())}))}const s=r.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=r.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:s,someBufferEnded:n}).pipe(r.filter(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).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:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.representationSubscription.add(r.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>this.source?.addEventListener("sourceopen",o))),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Le.REPRESENTATIOS_READY)}.bind(this));initBuffer(){r.assertNonNullable(this.element),this.state$.setState(Le.RUNNING),this.subscription.add(r.merge(...Qi.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ct(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){return{[pe.VIDEO]:this.videoBufferManager,[pe.AUDIO]:this.audioBufferManager,[pe.TEXT]:null}[e]?.switchTo(t)}seek(e,t){r.assertNonNullable(this.element),r.assertNonNullable(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Ct(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Le.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:r.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}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=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class Ls{scene3D;subscription=new r.Subscription;videoState=new q(ee.STOPPED);video;player;params;elementSize$=new r.ValueSubject(void 0);textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ls;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new $n({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Ke(this.video),s=this.constructor.name,n=u=>{e.error$.next({id:s,category:r.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:u})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(u,d)=>this.subscription.add(u.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(r.map(c=>c.map(({track:h})=>h)))}),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.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(rt(this.video,t.playbackRate,i.playbackRateState$,s)),n(zt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===Le.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();r.assertNonNullable(l,"Manifest not loaded or empty");const f=Array.from(l.audio).sort((b,k)=>k.bitrate-b.bitrate),p=Array.from(l.video).sort((b,k)=>k.bitrate-b.bitrate),g=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const k=mn(b);k&&this.audioTracks.push({track:k,representation:b})}for(const b of p){const k=pn(b);if(k){h.push({track:k,representation:b});const A=!this.params.tuning.isAudioDisabled&&gn(f,p,b);A&&this.audioRepresentations.set(b.id,A)}}this.videoTracks$.next(h);for(const b of g){const k=bn(b);k&&this.textTracks.push({track:k,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const y=this.selectVideoRepresentation();r.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else c===Le.REPRESENTATIOS_READY&&(this.videoState.setState(ee.READY),this.player.initBuffer())},s));const o=c=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!==Le.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l){this.player.switchRepresentation(pe.VIDEO,l.id).catch(o);const p=this.audioRepresentations.get(l.id);p&&this.player.switchRepresentation(pe.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(c=>c&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(r.map(({to:c})=>c===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(r.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),n=ke(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=Tt(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?c??i:i??c;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==ee.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-o,s.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ee.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();return;case ee.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ee.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ks(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){nt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}destroy(){console.log("destroy DASH provider"),this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}}class wn extends Ls{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let An=class extends $s{constructor(e){super(e),this.liveOffset=new Wt}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(r.combine({interval:r.interval(ki),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===Z.PLAYING){const n=e.position$.getValue()+(s-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&i===Z.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(o,s)})}};class Pn extends Ls{constructor(e){super(e),this.liveOffset=new Wt}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.combine({interval:r.interval(Ai),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===ee.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(s-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&i===ee.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(o,s)})}}const je={};var Y;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));const Ot=(a,e)=>new r.Observable(t=>{const i=(s,n)=>t.next(n);return a.on(e,i),()=>a.off(e,i)});class Dn{subscription=new r.Subscription;videoState=new q(Y.INITIALIZING);video;params;hls;textTracksManager=new Fe;trackLevels=new Map;constructor(e){this.video=Je(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(s=>{e||(je.Hls=s.default,je.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){r.assertNonNullable(je.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=c=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:c})},s=Ke(this.video),n=(c,h)=>this.subscription.add(c.subscribe(h,i));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(dt(this.video,e.isLooped,i)),this.subscription.add(Qe(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(rt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(Ot(this.hls,je.Events.ERROR).subscribe(c=>{c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${c.err?.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),w(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),n(Ot(this.hls,je.Events.MANIFEST_PARSED).pipe(r.map(({levels:c})=>c.reduce((h,l)=>{const f=l.name||l.height.toString(10),{width:p,height:g}=l,y=It(l.attrs.QUALITY??"")??r.videoSizeToQuality({width:p,height:g});if(!y)return h;const b=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,k={id:f.toString(),quality:y,bitrate:l.bitrate/1e3,size:{width:p,height:g},fps:b};return this.trackLevels.set(f,{track:k,level:l}),h.push(k),h},[]))),t.availableVideoTracks$),n(Ot(this.hls,je.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){const h=[];for(const l of c.subtitleTracks){const f=l.name,p=l.attrs.URI||"",g=l.lang,y="internal";h.push({id:f,url:p,language:g,type:y})}e.internalTextTracks.startTransitionTo(h)}}),n(Ot(this.hls,je.Events.LEVEL_LOADING).pipe(r.map(({url:c})=>ye(c))),t.hostname$),this.subscription.add(Ve(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:i}));const o=c=>Array.from(this.trackLevels.values()).find(({level:h})=>h===c)?.track,u=Ot(this.hls,je.Events.LEVEL_SWITCHED).pipe(r.map(({level:c})=>o(this.hls.levels[c])));u.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ve(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),c=>{if(r.isNullable(c))return;const h=this.trackLevels.get(c.id)?.level;if(!h)return;const l=this.hls.levels.indexOf(h),f=this.hls.currentLevel,p=this.hls.levels[f];!p||h.bitrate>p.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:u,onError:i})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(e!==Y.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&s.state===V.Requested&&this.seek(s.position),t){case exports.PlaybackState.STOPPED:switch(e){case Y.STOPPED:break;case Y.READY:case Y.PLAYING:case Y.PAUSED:this.stop();break;default:r.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PLAYING:case Y.PAUSED:break;default:r.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Y.PLAYING:break;case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PAUSED:this.playIfAllowed();break;default:r.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Y.PAUSED:break;case Y.STOPPED:this.prepare();break;case Y.READY:this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Y.PLAYING:this.pause();break;default:r.assertNever(e)}break;default:r.assertNever(t)}};prepare(){this.videoState.startTransitionTo(Y.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Y.PLAYING),await nt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(Y.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Ji="X-Playback-Duration";var Xi=async a=>{const e=await yt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Ji)?parseInt(e.headers.get(Ji),10):void 0};const Cn=a=>{let e=null;if(a.QUALITY&&(e=It(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(s=>parseInt(s,10));e=r.videoSizeToQuality({width:t,height:i})}return e??null},xs=async(a,e=a)=>{const s=(await(await yt(a)).text()).split(`
|
|
46
|
-
`),n=[],o=[];for(let u=0;u<s.length;u++){const d=s[u],c=d.match(/^#EXT-X-STREAM-INF:(.+)/),h=d.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const l=Object.fromEntries(c[1].split(",").map(A=>A.split("="))),f=l.QUALITY??`stream-${l.BANDWIDTH}`,p=Cn(l);let g;l.BANDWIDTH&&(g=parseInt(l.BANDWIDTH,10)/1e3||void 0),!g&&l["AVERAGE-BANDWIDTH"]&&(g=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const y=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let b;if(l.RESOLUTION){const[A,m]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));A&&m&&(b={width:A,height:m})}const k=new URL(s[++u],e).toString();p&&n.push({id:f,quality:p,url:k,bandwidth:g,size:b,fps:y})}if(h){const l=Object.fromEntries(h[1].split(",").map(y=>y.split("=")).map(([y,b])=>[y,b.replace(/^"|"$/g,"")])),f=l.URI?.replace(/playlist$/,"subtitles.vtt"),p=l.LANGUAGE,g=l.NAME;f&&p&&o.push({type:"internal",id:p,label:g,language:p,url:f,isAuto:!1})}}}return{qualityManifests:n,textTracks:o}};var W;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(W||(W={}));class Ln{subscription=new r.Subscription;videoState=new q(W.STOPPED);video;params;textTracksManager=new Fe;masterManifest;manifests$=new r.ValueSubject([]);maxSeekBackTime$;liveOffset=new Wt;manifestStartTime$=new r.ValueSubject(void 0);constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},xs(Se(this.params.source.url),this.params.source.url).then(({qualityManifests:t})=>{if(t.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:r.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),n=s?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const u=i?"master":n;return i&&!s&&t.startTransitionTo(this.masterManifest),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,i));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&r.isNonNullable(c.to)){const l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(p=>p.id===l);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ye(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),u&&u.state===V.Requested&&this.seek(u.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:u,currentTime:d})=>this.params.output.liveTime$.next(u+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.map(u=>u.map(({id:d,quality:c,size:h,bandwidth:l,fps:f})=>({id:d,quality:c,size:h,fps:f,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:u,min:d}=t?.to??i??{};for(const[c,h]of[[u,"mq"],[d,"lq"]]){const l=String(parseFloat(c||""));h&&c&&s.searchParams.set(h,l)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?X.DASH_CMAF_OFFSET_P:X.OFFSET_P,o=Se(s.toString(),this.liveOffset.getTotalOffset(),n);this.video.setAttribute("src",o),this.video.load(),Xi(o).then(u=>{if(!r.isNullable(u))this.maxSeekBackTime$.next(u);else{const d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(r.isNullable(d)||!isFinite(d))try{yt(o).then(c=>c.text()).then(c=>{const h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(h){const l=new URL(h,o).toString();Xi(l).then(f=>{r.isNullable(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(n||o||u){const h=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested){this.videoState.startTransitionTo(W.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case W.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(W.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);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else s?.to===exports.PlaybackState.PAUSED&&(w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case W.CHANGING_MANIFEST:break;default:return r.assertNever(t)}}}var J;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(J||(J={}));class xn{subscription=new r.Subscription;videoState=new q(J.STOPPED);video;params;textTracksManager=new Fe;masterManifest;manifests$=new r.ValueSubject([]);constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),n=s?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const u=i?"master":n;return i&&!s&&t.startTransitionTo(this.masterManifest),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d));if(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.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&r.isNonNullable(c.to)){const l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(p=>p.id===l);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ye(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===J.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===V.Requested&&this.seek(u.position)},i))),this.subscription.add(this.manifests$.pipe(r.map(u=>u.map(({id:d,quality:c,size:h,bandwidth:l,fps:f})=>({id:d,quality:c,size:h,fps:f,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!r.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:u}=this.video;this.subscription.add(r.merge(r.fromEvent(u,"addtrack"),r.fromEvent(u,"removetrack"),r.fromEvent(u,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<u.length;d++)u[d].mode="hidden"},i))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:n,min:o}=t?.to??i??{};for(const[u,d]of[[n,"mq"],[o,"lq"]]){const c=String(parseFloat(u||""));d&&u&&s.searchParams.set(d,c)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(n||o||u){const h=this.videoState.getState();this.videoState.setState(J.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:l}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:l*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested&&this.seek(c.position),t){case J.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case J.CHANGING_MANIFEST:break;default:return r.assertNever(t)}}}var te;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(te||(te={}));class Rn{subscription=new r.Subscription;videoState=new q(te.STOPPED);video;trackUrls={};params;textTracksManager=new Fe;constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,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.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&r.isNonNullable(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===te.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;r.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];r.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ct(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ye(t))}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==te.STOPPED&&(this.videoState.startTransitionTo(te.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(te.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.autoVideoTrackLimits.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(n&&e!==te.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),u.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:d*1e3,forcePrecise:!0}),o.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[o.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==exports.PlaybackState.PAUSED&&u.state===V.Requested&&this.seek(u.position),e){case te.READY:t===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case te.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(u=>!r.isInvariantQuality(u.track.quality)&&r.isLowerOrEqual(u.track.quality,e))?.track,n=this.params.desiredState.videoTrack.getState()?.id,o=this.trackUrls[n??"0"]?.track;if(s&&o&&r.isHigherOrEqual(o.quality,s.quality)&&(t=s),!t){const u=Object.values(this.trackUrls).filter(c=>!r.isInvariantQuality(c.track.quality)&&r.isHigher(c.track.quality,e)),d=u.length;d&&(t=u[d-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(n=>n.track);t=Tt(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}}const Ki=["stun:videostun.mycdn.me:80"],In=1e3,Nn=3,Ti=()=>null;class _n{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Ti;externalStopCallback=Ti;externalErrorCallback=Ti;constructor(e,t){this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Ki}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),In)}normalizeOptions(e={}){const t={stunServerList:Ki,maxRetryNumber:Nn,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Q;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Q||(Q={}));class Bn{subscription;params;log;video;videoState=new q(Q.STOPPED);liveStreamClient;maxSeekBackTime$=new r.ValueSubject(0);constructor(e){this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Je(e.container),this.liveStreamClient=new _n(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Xe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(o)}`})});const s=Ke(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(s.timeUpdate$,e.liveTime$),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$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Q.READY&&this.videoState.setState(Q.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Qe(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Q.READY:break;case Q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:r.VideoQuality.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.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(Q.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case Q.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),w(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()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}}class Zi{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}const Rs=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,pi=document.createElement("video"),Mn='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Vn='video/mp4; codecs="hev1.1.6.L93.B0"',Is='video/webm; codecs="vp09.00.10.08"',Ns='video/webm; codecs="av01.0.00M.08"',Fn='audio/mp4; codecs="mp4a.40.2"',On='audio/webm; codecs="opus"',he={mms:!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(pi.canPlayType?.("application/x-mpegurl")||pi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},De={mp4:!!pi.canPlayType?.("video/mp4"),webm:!!pi.canPlayType?.("video/webm"),cmaf:!0},We={h264:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Mn),h265:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Vn),vp9:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Is),av1:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Ns),aac:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Fn),opus:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(On)},$t=(We.h264||We.h265)&&We.aac;var ut;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(ut||(ut={}));var at;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg"})(at||(at={}));let mt;const Un=async()=>{if(!window.navigator.mediaCapabilities)return;const a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Ns}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Is}})]);mt={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{Un()}catch(a){console.error(a)}const qt=he.hls&&De.mp4,Hn=()=>Object.keys(We).filter(a=>We[a]),jn=(a,e=!1,t=!1)=>a.filter(i=>{switch(i){case exports.VideoFormat.DASH:return he.mse&&De.mp4&&$t;case exports.VideoFormat.DASH_SEP:return(he.mse||he.mms&&t)&&De.mp4&&$t;case exports.VideoFormat.DASH_WEBM:return(he.mse||he.mms&&t)&&De.webm&&We.vp9&&We.opus;case exports.VideoFormat.DASH_WEBM_AV1:return(he.mse||he.mms&&t)&&De.webm&&We.av1&&We.opus;case exports.VideoFormat.DASH_LIVE:return he.mse&&De.mp4&&$t;case exports.VideoFormat.DASH_LIVE_CMAF:return(he.mse||he.mms&&t)&&De.mp4&&$t&&De.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return(he.mse||he.mms&&t)&&De.mp4&&$t;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return qt||e&&he.mse&&De.mp4&&$t;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return qt;case exports.VideoFormat.MPEG:return De.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return he.webrtc&&he.ws&&We.h264&&(De.mp4||De.webm);default:return r.assertNever(i)}}),Ut=a=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(a){case ut.VP9:return[e,t];case ut.AV1:return[t,e];case ut.NONE:return[];case ut.SMOOTH:return mt?mt[t].smooth?[t,e]:mt[e].smooth?[e,t]:[t,e]:[e,t];case ut.POWER_EFFICIENT:return mt?mt[t].powerEfficient?[t,e]:mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(a)}return[e,t]},Yn=({webmCodec:a,androidPreferredFormat:e})=>{if(Rs)switch(e){case at.MPEG:return[exports.VideoFormat.MPEG,...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case at.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case at.DASH:return[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return qt?[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Gn=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],s=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...s],o=[...s,...i];let u;if(Rs)switch(a){case at.DASH:{u=n;break}case at.HLS:case at.MPEG:{u=o;break}}else qt?u=o:u=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...u]:[...u,exports.VideoFormat.WEB_RTC_LIVE]},es=a=>a?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var zn=a=>new r.Observable(e=>{const t=new r.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:c,to:h})=>`${c}-${h}`)),s=a.desiredPlaybackState$.stateChangeEnded$,n=a.providerChanged$.pipe(r.map(({type:c})=>c!==void 0)),o=new r.Subject;let u=0,d="unknown";return t.add(i.subscribe(c=>{u&&window.clearTimeout(u),d=c,u=window.setTimeout(()=>o.next(c),a.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(u),d="unknown",u=0})),t.add(n.subscribe(c=>{u&&(window.clearTimeout(u),u=0,c&&(u=window.setTimeout(()=>o.next(d),a.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});const qn={cacheDuration:12e4},Wn={chunkDuration:5e3,maxParallelRequests:5};class Qn{current$=new r.ValueSubject({type:void 0});providerError$=new r.Subject;noAvailableProvidersError$=new r.Subject;providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)};subscription=new r.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=jn([...Gn(this.params.tuning),...Yn(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>r.isNonNullable(e.sources[u])),{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let n=[];i?n=[i]:s.length?n=[...t.filter(u=>!s.includes(u)),...t.filter(u=>s.includes(u))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Zi(n),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(n);const o=[...es(!0),...es(!1)];this.chromecastFormatsIterator=new Zi(o.filter(u=>r.isNonNullable(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(console.log("Choose provider "+t),r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),s=i.state!==V.None;if(this.params.desiredState.seekState.setState({state:V.Requested,position:s?i.position:t,forcePrecise:s?i.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ge.SCREEN:return this.createScreenProvider(t);case ge.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case exports.VideoFormat.DASH:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Na({...o,source:u,config:qn})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),this.params.tuning.useDashJs?new Mi({...o,source:u,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new wn({...o,source:u})):new Cr({...o,source:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),this.params.tuning.useDashJsCMAF?new Mi({...o,source:u,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new Pn({...o,source:u}):new An({...o,source:u})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),qt||!this.params.tuning.useHlsJs?new xn({...o,source:u}):new Dn({...o,source:u})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Ln({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Rn({...o,source:u})}case exports.VideoFormat.DASH_LIVE:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Ca({...o,source:u,config:{...Wn,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Bn({container:i,source:u,desiredState:s,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 r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:n}=this.params,o=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(u),new Js({connection:u,meta:n,container:i,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ge.CHROMECAST:ge.SCREEN}chooseFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ge.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.next();case ge.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case ge.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ge.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=s=>{const n=new URL(s);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:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([s,n])=>[s,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;const s=r.now();return e.add(r.merge(this.providerOutput.error$,zn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(n=>({id:`ProviderHangup:${n}`,category:r.ErrorCategory.WTF,message:`A ${n} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const n=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(n)})),e.add(this.providerError$.subscribe(n=>{console.log(n);const o=this.current$.getValue().destination;if(o===ge.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ge.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const u=n.category===r.ErrorCategory.NETWORK,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit,h=d&&(u&&t||!c),l=n.id.includes("partial_metadata"),f=r.now()-s;h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l&&f<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():c?(i++,this.reinitProvider()):this.switchToNextProvider(o??ge.SCREEN)}})),e}}const Jn=5e3,ts="one_video_throughput",is="one_video_rtt",Yt=window.navigator.connection,ss=()=>{const a=Yt?.downlink;if(r.isNonNullable(a)&&a!==10)return a*1e3},as=()=>{const a=Yt?.rtt;if(r.isNonNullable(a)&&a!==3e3)return a},rs=(a,e,t)=>{const i=t*8,s=i/a;return i/(s+e)};class Gt{throughput;rtt;subscription=new r.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Gt.load(ts)||(e.useBrowserEstimation?ss():void 0)||Jn,i=Gt.load(is)??(e.useBrowserEstimation?as():void 0)??0;if(this.throughput$=new r.ValueSubject(t),this.rtt$=new r.ValueSubject(i),this.rttAdjustedThroughput$=new r.ValueSubject(rs(t,i,e.rttPenaltyRequestSize)),this.throughput=Pi.getSmoothedValue(t,-1,e),this.rtt=Pi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const o=ss();o&&this.throughput.next(o);const u=as();r.isNonNullable(u)&&this.rtt.next(u)};Yt&&"onchange"in Yt&&this.subscription.add(r.fromEvent(Yt,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{r.safeStorage.set(ts,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{r.safeStorage.set(is,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:s,rtt:n})=>rs(s,n,e.rttPenaltyRequestSize)),r.filter(s=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=r.now();const s=new r.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:s.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}s.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,u=r.now(),d=o-t,c=u-i;this.addRawSpeed(d,c,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let s=0,n=r.now(),o=0,u=r.now();const d=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},c=async({done:h,value:l})=>{if(h)!t&&this.addRawSpeed(s,r.now()-n,1),this.concurrentDownloads.delete(e);else if(l){if(t){if(r.now()-u<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=l.byteLength;else{const p=u-n;p&&this.addRawSpeed(o,p,1,t),o=l.byteLength,n=r.now()}u=r.now()}else s+=l.byteLength,o+=l.byteLength,o>=this.tuningConfig.streamMinSampleSize&&r.now()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,r.now()-u,this.concurrentDownloads.size),o=0,u=r.now());await i?.read().then(c,d)}};this.concurrentDownloads.add(e),i?.read().then(c,d)}addRawSpeed(e,t,i=1,s=!1){if(Gt.sanityCheck(e,t,s)){const n=e*8/t;this.throughput.next(n*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=r.safeStorage.get(e);if(r.isNonNullable(t))return parseInt(t,10)??void 0}}const ns={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ut.VP9,androidPreferredFormat:at.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Xn=a=>({...r.fillWithDefault(a,ns),configName:[...a.configName??[],...ns.configName]});var os=({seekState:a,position$:e})=>r.merge(a.stateChangeEnded$.pipe(r.map(({to:t})=>t.state===V.None?void 0:(t.position??NaN)/1e3),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>a.getState().state===V.None))),Kn=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return r.assertNonNullable(e,`Wrong container or containerId {${a.container}}`),e};const Zn=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(r.filter(s=>s.length>0),r.once()).subscribe(s=>{s.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class eo{subscription=new r.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new r.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new q(exports.PlaybackState.STOPPED),seekState:new q({state:V.None}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)};events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject};experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:ca};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Xn(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ys({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Gt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const n=Reflect.get(t,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(u){const d=o.map(l=>JSON.stringify(l,(f,p)=>{const g=typeof p;return["number","string","boolean"].includes(g)?p:p===null?null:`<${g}>`})),c=`Player.${String(i)}`,h=`Exception calling ${c} (${d.join(", ")})`;throw this.events.fatalError$.next({id:c,category:r.ErrorCategory.WTF,message:h,thrown:u}),u}}}})}initVideo(e){return this.config=e,this.domContainer=Kn(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Qn({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?r.fromEvent(document,"visibilitychange").pipe(r.once()).subscribe(e):e(),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){const i=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=i&&!s&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:V.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){r.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 Zn(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const s=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+n.x,y:s.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===V.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){const e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:s})=>i||s||0,0),height:e.reduce((i,{height:s})=>i||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.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.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===V.Requested?this.desiredState.seekState.setState({...o,state:V.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===V.Applying&&(this.desiredState.seekState.setState({state:V.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:u})=>u).sort((u,d)=>r.isInvariantQuality(u)?1:r.isInvariantQuality(d)?-1:r.isHigher(d,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const u={};for(const d of o)d.fps&&(u[d.quality]=d.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o?.quality),this.info.videoBitrate$.next(o?.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.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.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o??{})})).add(e.providerOutput.currentBuffer$.pipe(r.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:u,isLowLatency:d})=>{const c=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(u)<c/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:u,duration:d})=>o&&(Math.abs(d)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.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(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o??r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let s=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return o&&!u}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.size?.width,height:o?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),c=this.chromecastInitializer.castState$.getValue();let h;c===exports.ChromecastState.CONNECTED?h=exports.Surface.SECOND_SCREEN:d?o?h=exports.Surface.PIP:u?h=exports.Surface.FULLSCREEN:h=exports.Surface.INLINE:h=exports.Surface.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Tt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.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;r.assertNonNullable(this.providerContainer),r.assertNonNullable(e),ua(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>oa(t)),this.providerContainer.current$.subscribe(({type:t})=>Kt("provider",t)),e.duration$.subscribe(t=>Kt("duration",t)),e.availableVideoTracks$.pipe(r.filter(t=>!!t.length),r.once()).subscribe(t=>Kt("tracks",t)),this.events.fatalError$.subscribe(new Ge("fatalError")),this.events.managedError$.subscribe(new Ge("managedError")),e.position$.subscribe(new Ge("position")),e.currentVideoTrack$.pipe(r.map(t=>t?.quality)).subscribe(new Ge("quality")),this.info.currentBuffer$.subscribe(new Ge("buffer")),e.isBuffering$.subscribe(new Ge("isBuffering"))].forEach(t=>this.subscription.add(t)),Kt("codecs",Hn())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(s)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;s&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(s=>s.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const to=`@vkontakte/videoplayer-core@${us}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=eo;exports.SDK_VERSION=to;exports.VERSION=us;
|
|
45
|
+
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class ks{container;sourceVideoElement;canvas;gl;params;frameWidth;frameHeight;viewportWidth;viewportHeight;videoInitialized=!1;program;videoTexture;vertexBuffer;textureMappingBuffer;camera;cameraRotationManager;videoElementDataLoadedFn;renderFn;active=!1;constructor(e,t,i){this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new wr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ar(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(s,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(Pr,this.gl.VERTEX_SHADER),i=this.createShader(Dr,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:i=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,n=e-i,o=t-s,u=e+i,d=t-s,c=e+i,h=t+s,l=e-i,f=t+s;return[n,o,u,d,c,h,l,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let $s=class{scene3D;subscription=new r.Subscription;videoState=new q(Z.STOPPED);video;player;params;elementSize$=new r.ValueSubject(void 0);textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ls;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new $r({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Ke(this.video),s=this.constructor.name,n=u=>{e.error$.next({id:s,category:r.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:u})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(u,d)=>this.subscription.add(u.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(r.map(c=>c.map(({track:h})=>h)))}),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.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(rt(this.video,t.playbackRate,i.playbackRateState$,s)),n(zt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===Ce.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();r.assertNonNullable(l,"Manifest not loaded or empty");const f=Array.from(l.audio).sort((b,k)=>k.bitrate-b.bitrate),p=Array.from(l.video).sort((b,k)=>k.bitrate-b.bitrate),g=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const k=yr(b);k&&this.audioTracks.push({track:k,representation:b})}for(const b of p){const k=Sr(b);if(k){h.push({track:k,representation:b});const A=!this.params.tuning.isAudioDisabled&&Tr(f,p,b);A&&this.audioRepresentations.set(b.id,A)}}this.videoTracks$.next(h);for(const b of g){const k=vr(b);k&&this.textTracks.push({track:k,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const y=this.selectVideoRepresentation();r.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else c===Ce.REPRESENTATIOS_READY&&(this.videoState.setState(Z.READY),this.player.initBuffer())},s));const o=c=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!==Ce.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l){this.player.switchRepresentation(fe.VIDEO,l.id).catch(o);const p=this.audioRepresentations.get(l.id);p&&this.player.switchRepresentation(fe.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(c=>c&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(r.map(({to:c})=>c===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(r.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),n=ke(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=Tt(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?c??i:i??c;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==Z.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-o,s.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case Z.STOPPED:this.videoState.startTransitionTo(Z.READY),this.prepare();return;case Z.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Z.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ks(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){nt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(Z.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}},Cr=class extends $s{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var pe;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(pe||(pe={}));var Ye;(function(a){a[a.ActiveLowLatency=0]="ActiveLowLatency",a[a.LiveWithTargetOffset=1]="LiveWithTargetOffset",a[a.LiveForwardBuffering=2]="LiveForwardBuffering",a[a.None=3]="None"})(Ye||(Ye={}));var di;(function(a){a.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",a.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(di||(di={}));var Re;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(Re||(Re={}));var M;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(M||(M={}));var xt;(function(a){a.MP4="mp4",a.WEBM="webm"})(xt||(xt={}));var li;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(li||(li={}));var ee;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(ee||(ee={}));let ws=!1;try{ws=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<16}catch(a){console.error(a)}class Lr{bufferFull$=new r.Subject;error$=new r.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(i=>{const s={operation:"append",data:e,signal:t,callback:i};this.queue.push(s),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:i,callback:s};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;ws&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}completeTask=()=>{try{if(this.currentTask){const e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:r.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(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:r.assertNever(t)}}}class Ne{source;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e){this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class As extends Ne{}class xr extends Ne{majorBrand;minorVersion;compatibleBrands;constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Rr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Ir extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Nr extends Ne{data;constructor(e){super(e),this.data=this.content}}class ot extends Ne{version;flags;constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class _r extends ot{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const u=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}}class Br extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Mr extends Ne{parseChildrenBoxes(){return lt(this.content)}}var St;(function(a){a[a.MONOSCOPIC=0]="MONOSCOPIC",a[a.TOP_BOTTOM=1]="TOP_BOTTOM",a[a.LEFT_RIGHT=2]="LEFT_RIGHT",a[a.STEREO_CUSTOM=3]="STEREO_CUSTOM",a[a.RIGHT_LEFT=4]="RIGHT_LEFT"})(St||(St={}));class Vr extends ot{stereoMode;constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=St.MONOSCOPIC;break;case 1:this.stereoMode=St.TOP_BOTTOM;break;case 2:this.stereoMode=St.LEFT_RIGHT;break;case 3:this.stereoMode=St.STEREO_CUSTOM;break;case 4:this.stereoMode=St.RIGHT_LEFT;break}this.cursor+=1}}class Fr extends ot{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Or extends ot{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ur extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Hr extends ot{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class jr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Yr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class Gr extends ot{sequenceNumber;constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class zr extends Ne{parseChildrenBoxes(){return lt(this.content)}}class qr extends ot{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Wr extends ot{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Qr extends ot{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e){super(e),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Jr={ftyp:xr,moov:Rr,moof:Ir,mdat:Nr,sidx:_r,trak:Br,mdia:Ur,mfhd:Gr,tkhd:Hr,traf:zr,tfhd:qr,tfdt:Wr,trun:Qr,minf:jr,sv3d:Mr,st3d:Vr,prhd:Fr,proj:Yr,equi:Or,unknown:As};class Xr{createBox(e,t){const i=Jr[e];return i?new i(t):new As(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Si.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Si=new Xr;function jt(a,e){const t=new Uint8Array(a.buffer),i=e.split("").map(o=>o.charCodeAt(0));let s=a.byteOffset,n=[];for(;s<t.byteLength;){if(t[s]===i[n.length]?n.push(t[s]):n=[],n.length===4){const u=new DataView(a.buffer,s-7,4).getUint32(0);return s-7+u>a.buffer.byteLength?null:Si.createBox(e,new DataView(a.buffer,s-7))}s++}return null}function $i(a,e){const t=[];let i=a.byteOffset;for(;i<a.buffer.byteLength;){const s=jt(new DataView(a.buffer,i,a.buffer.byteLength-i),e);if(s)t.push(s),i=s.source.byteOffset+s.size;else break}return t}function lt(a){const e=[];let t=0;for(;t<a.byteLength;){const i=Si.createFromView(new DataView(a.buffer,a.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Kr=new TextDecoder("ascii"),Zr=a=>Kr.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",en=a=>{const e=Si.createFromView(a);let t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,u={status:M.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,u})},tn=a=>{const e=$i(a,"mdat"),t=$i(a,"moof");if(!(e.length&&t.length))return null;const i=t[0],s=e[e.length-1],n=i.source.byteOffset,u=s.source.byteOffset-i.source.byteOffset+s.size;return new DataView(a.buffer,n,u)},sn=(a,e)=>{const t=$i(a,"traf"),i=t[t.length-1].children.find(d=>d.type==="tfhd"),s=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,c)=>d+c,0):o=i.defaultSampleDuration*n.sampleCount,(Number(s.baseMediaDecodeTime)+o)/e*1e3},an=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(jt(a,"sv3d")){e.is3dVideo=!0;const i=jt(a,"st3d");i&&(e.stereoMode=i.stereoMode);const s=jt(a,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=jt(a,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},rn={validateData:Zr,parseInit:an,getIndexRange:()=>{},parseSegments:en,parseFeedableSegmentChunk:tn,getSegmentEndTime:sn};var E;(function(a){a[a.EBML=440786851]="EBML",a[a.EBMLVersion=17030]="EBMLVersion",a[a.EBMLReadVersion=17143]="EBMLReadVersion",a[a.EBMLMaxIDLength=17138]="EBMLMaxIDLength",a[a.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",a[a.DocType=17026]="DocType",a[a.DocTypeVersion=17031]="DocTypeVersion",a[a.DocTypeReadVersion=17029]="DocTypeReadVersion",a[a.Void=236]="Void",a[a.Segment=408125543]="Segment",a[a.SeekHead=290298740]="SeekHead",a[a.Seek=19899]="Seek",a[a.SeekID=21419]="SeekID",a[a.SeekPosition=21420]="SeekPosition",a[a.Info=357149030]="Info",a[a.TimestampScale=2807729]="TimestampScale",a[a.Duration=17545]="Duration",a[a.Tracks=374648427]="Tracks",a[a.TrackEntry=174]="TrackEntry",a[a.Video=224]="Video",a[a.Projection=30320]="Projection",a[a.ProjectionType=30321]="ProjectionType",a[a.ProjectionPrivate=30322]="ProjectionPrivate",a[a.Chapters=272869232]="Chapters",a[a.Cluster=524531317]="Cluster",a[a.Timestamp=231]="Timestamp",a[a.SilentTracks=22612]="SilentTracks",a[a.SilentTrackNumber=22743]="SilentTrackNumber",a[a.Position=167]="Position",a[a.PrevSize=171]="PrevSize",a[a.SimpleBlock=163]="SimpleBlock",a[a.BlockGroup=160]="BlockGroup",a[a.EncryptedBlock=175]="EncryptedBlock",a[a.Attachments=423732329]="Attachments",a[a.Tags=307544935]="Tags",a[a.Cues=475249515]="Cues",a[a.CuePoint=187]="CuePoint",a[a.CueTime=179]="CueTime",a[a.CueTrackPositions=183]="CueTrackPositions",a[a.CueTrack=247]="CueTrack",a[a.CueClusterPosition=241]="CueClusterPosition",a[a.CueRelativePosition=240]="CueRelativePosition",a[a.CueDuration=178]="CueDuration",a[a.CueBlockNumber=21368]="CueBlockNumber",a[a.CueCodecState=234]="CueCodecState",a[a.CueReference=219]="CueReference",a[a.CueRefTime=150]="CueRefTime"})(E||(E={}));var D;(function(a){a.SignedInteger="int",a.UnsignedInteger="uint",a.Float="float",a.String="string",a.UTF8="utf8",a.Date="date",a.Master="master",a.Binary="binary"})(D||(D={}));const Gi={[E.EBML]:{type:D.Master},[E.EBMLVersion]:{type:D.UnsignedInteger},[E.EBMLReadVersion]:{type:D.UnsignedInteger},[E.EBMLMaxIDLength]:{type:D.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[E.DocType]:{type:D.String},[E.DocTypeVersion]:{type:D.UnsignedInteger},[E.DocTypeReadVersion]:{type:D.UnsignedInteger},[E.Void]:{type:D.Binary},[E.Segment]:{type:D.Master},[E.SeekHead]:{type:D.Master},[E.Seek]:{type:D.Master},[E.SeekID]:{type:D.Binary},[E.SeekPosition]:{type:D.UnsignedInteger},[E.Info]:{type:D.Master},[E.TimestampScale]:{type:D.UnsignedInteger},[E.Duration]:{type:D.Float},[E.Tracks]:{type:D.Master},[E.TrackEntry]:{type:D.Master},[E.Video]:{type:D.Master},[E.Projection]:{type:D.Master},[E.ProjectionType]:{type:D.UnsignedInteger},[E.ProjectionPrivate]:{type:D.Master},[E.Chapters]:{type:D.Master},[E.Cluster]:{type:D.Master},[E.Timestamp]:{type:D.UnsignedInteger},[E.SilentTracks]:{type:D.Master},[E.SilentTrackNumber]:{type:D.UnsignedInteger},[E.Position]:{type:D.UnsignedInteger},[E.PrevSize]:{type:D.UnsignedInteger},[E.SimpleBlock]:{type:D.Binary},[E.BlockGroup]:{type:D.Master},[E.EncryptedBlock]:{type:D.Binary},[E.Attachments]:{type:D.Master},[E.Tags]:{type:D.Master},[E.Cues]:{type:D.Master},[E.CuePoint]:{type:D.Master},[E.CueTime]:{type:D.UnsignedInteger},[E.CueTrackPositions]:{type:D.Master},[E.CueTrack]:{type:D.UnsignedInteger},[E.CueClusterPosition]:{type:D.UnsignedInteger},[E.CueRelativePosition]:{type:D.UnsignedInteger},[E.CueDuration]:{type:D.UnsignedInteger},[E.CueBlockNumber]:{type:D.UnsignedInteger},[E.CueCodecState]:{type:D.UnsignedInteger},[E.CueReference]:{type:D.Master},[E.CueRefTime]:{type:D.UnsignedInteger}},Ps=a=>{const e=a.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=hi(a,t),s=i in Gi,n=s?Gi[i].type:D.Binary,o=a.getUint8(t);let u=0;o&128?u=1:o&64?u=2:o&32?u=3:o&16?u=4:o&8?u=5:o&4?u=6:o&2?u=7:o&1&&(u=8);const d=new DataView(a.buffer,a.byteOffset+t+1,u-1),c=o&255>>u,h=hi(d),l=c*2**((u-1)*8)+h,f=t+u;let p;return f+l>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,l),{tag:s?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+l,value:p,valueSize:l}},hi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{const t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},qe=(a,e)=>{switch(e){case D.SignedInteger:return a.getInt8(0);case D.UnsignedInteger:return hi(a);case D.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(a);case D.UTF8:return new TextDecoder("utf-8").decode(a);case D.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case D.Master:return a;case D.Binary:return a;default:r.assertNever(e)}},Rt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),s=Ps(i);if(!e(s))return;s.type===D.Master&&Rt(s.value,e),t=s.value.byteOffset-a.byteOffset+s.valueSize}},nn=a=>{if(a.getUint32(0)!==E.EBML)return!1;let e,t,i;const s=Ps(a);return Rt(s.value,({tag:n,type:o,value:u})=>(n===E.EBMLReadVersion?e=qe(u,o):n===E.DocType?t=qe(u,o):n===E.DocTypeReadVersion&&(i=qe(u,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Ds=[E.Info,E.SeekHead,E.Tracks,E.TrackEntry,E.Video,E.Projection,E.ProjectionType,E.ProjectionPrivate,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],on=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],un=a=>{let e,t,i,s,n=!1,o=!1,u=!1,d,c,h=!1;const l=0;return Rt(a,({tag:f,type:p,value:g,valueSize:y})=>{if(f===E.SeekID){const b=qe(g,p);c=hi(b)}else f!==E.SeekPosition&&(c=void 0);return f===E.Segment?(e=g.byteOffset,t=g.byteOffset+y):f===E.Info?n=!0:f===E.SeekHead?o=!0:f===E.TimestampScale?i=qe(g,p):f===E.Duration?s=qe(g,p):f===E.SeekPosition&&c===E.Cues?d=qe(g,p):f===E.Tracks?Rt(g,({tag:b,type:k,value:A})=>b===E.ProjectionType?(h=qe(A,k)===1,!1):!0):n&&o&&Ds.includes(f)&&(u=!0),!u}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(s,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(s/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:h,stereoMode:l,projectionType:li.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},cn=a=>{if(r.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},dn=(a,e)=>{let t=!1,i=!1;const s=u=>r.isNonNullable(u.time)&&r.isNonNullable(u.position),n=[];let o;return Rt(a,({tag:u,type:d,value:c})=>{switch(u){case E.Cues:t=!0;break;case E.CuePoint:o&&s(o)&&n.push(o),o={};break;case E.CueTime:o&&(o.time=qe(c,d));break;case E.CueTrackPositions:break;case E.CueClusterPosition:o&&(o.position=qe(c,d));break;default:t&&Ds.includes(u)&&(i=!0)}return!(t&&i)}),o&&s(o)&&n.push(o),n.map((u,d)=>{const{time:c,position:h}=u,l=n[d+1];return{status:M.NONE,time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},ln=a=>{let e=0,t=!1;try{Rt(a,i=>i.tag===E.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):on.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},hn={validateData:nn,parseInit:un,getIndexRange:cn,parseSegments:dn,parseFeedableSegmentChunk:ln},zi=a=>{if(!a.startsWith("P"))return;const e=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),s=i?.[1]==="-"?-1:1,n={days:e(i?.[5],s),hours:e(i?.[6],s),minutes:e(i?.[7],s),seconds:e(i?.[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},wt=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(i)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(u,d)=>r.isNullable(n)?u:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},fn=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),s={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],u=o.children,d=n.getAttribute("type")==="dynamic",c=n.getAttribute("availabilityStartTime"),h=c?new Date(c).getTime():void 0;let l;const f=n.getAttribute("mediaPresentationDuration"),p=o.getAttribute("duration"),y=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)l=zi(f);else if(p){const m=zi(p);r.isNonNullable(m)&&(l=m)}else y&&(l=parseInt(y,10));let b=0;const k=n.getAttribute("profiles")?.split(",")??[],A=k.includes(di.WEBM_AS_IN_FFMPEG)||k.includes(di.WEBM_AS_IN_SPEC)?xt.WEBM:xt.MP4;for(const m of u){const T=m.getAttribute("mimeType"),$=m.getAttribute("codecs"),R=m.getAttribute("contentType")??T?.split("/")[0],_=m.getAttribute("profiles")?.split(",")??[],C=m.querySelectorAll("Representation"),I=m.querySelector("SegmentTemplate");if(R===pe.TEXT){for(const S of C){const L=S.getAttribute("id")||"",N=m.getAttribute("lang"),j=S.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(j,e).toString(),ne=L.includes("_auto");s[pe.TEXT].push({id:L,lang:N,isAuto:ne,kind:pe.TEXT,url:ie})}continue}for(const S of C){const L=S.getAttribute("mimeType")??T,N=S.getAttribute("codecs")??$??"",j=S.getAttribute("contentType")??L?.split("/")[0]??R,ie=m.getAttribute("profiles")?.split(",")??[],ne=parseInt(S.getAttribute("width")??"",10),x=parseInt(S.getAttribute("height")??"",10),G=parseInt(S.getAttribute("bandwidth")??"",10)/1e3,K=S.getAttribute("frameRate")??"",oe=S.getAttribute("quality")??void 0,me=K?mi(K):void 0,Oe=S.getAttribute("id")??(b++).toString(10),_t=j==="video"?`${x}p`:j==="audio"?`${G}Kbps`:N,vt=`${Oe}@${_t}`,z=S.querySelector("BaseURL")?.textContent?.trim()??"",ce=new URL(z,e).toString(),Te=[...k,..._,...ie];let de;const et=S.querySelector("SegmentBase"),se=S.querySelector("SegmentTemplate")??I;if(et){const ue=S.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[le,Ue]=ue.split("-").map(we=>parseInt(we,10)),ve={from:le,to:Ue},_e=S.querySelector("SegmentBase")?.getAttribute("indexRange"),[ht,tt]=_e?_e.split("-").map(we=>parseInt(we,10)):[],Be=_e?{from:ht,to:tt}:void 0;de={type:Re.BYTE_RANGE,url:ce,initRange:ve,indexRange:Be}}else if(se){const ue={representationId:S.getAttribute("id")??void 0,bandwidth:S.getAttribute("bandwidth")??void 0},le=parseInt(se.getAttribute("timescale")??"",10),Ue=se.getAttribute("initialization")??"",ve=se.getAttribute("media"),_e=parseInt(se.getAttribute("startNumber")??"",10)??1,ht=wt(Ue,ue);if(!ve)throw new ReferenceError("No media attribute in SegmentTemplate");const tt=se.querySelectorAll("SegmentTimeline S")??[],Be=[];let we=0,ft="",Ae=0;if(tt.length){let Pe=_e,ae=0;for(const Me of tt){const Ee=parseInt(Me.getAttribute("d")??"",10),He=parseInt(Me.getAttribute("r")??"",10)||0,it=parseInt(Me.getAttribute("t")??"",10);ae=Number.isFinite(it)?it:ae;const Bt=Ee/le*1e3,Xt=ae/le*1e3;for(let Et=0;Et<He+1;Et++){const _s=wt(ve,{...ue,segmentNumber:Pe.toString(10),segmentTime:(ae+Et*Ee).toString(10)}),Ri=(Xt??0)+Et*Bt,Bs=Ri+Bt;Pe++,Be.push({time:{from:Ri,to:Bs},url:_s})}ae+=(He+1)*Ee,we+=(He+1)*Bt}Ae=ae/le*1e3,ft=wt(ve,{...ue,segmentNumber:Pe.toString(10),segmentTime:ae.toString(10)})}else if(r.isNonNullable(l)){const ae=parseInt(se.getAttribute("duration")??"",10)/le*1e3,Me=Math.ceil(l/ae);let Ee=0;for(let He=1;He<Me;He++){const it=wt(ve,{...ue,segmentNumber:He.toString(10),segmentTime:Ee.toString(10)});Be.push({time:{from:Ee,to:Ee+ae},url:it}),Ee+=ae}Ae=Ee,ft=wt(ve,{...ue,segmentNumber:Me.toString(10),segmentTime:Ee.toString(10)})}const pt={time:{from:Ae,to:1/0},url:ft};de={type:Re.TEMPLATE,baseUrl:ce,segmentTemplateUrl:ve,initUrl:ht,totalSegmentsDurationMs:we,segments:Be,nextSegmentBeyondManifest:pt,timescale:le}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!L)continue;const $e={video:pe.VIDEO,audio:pe.AUDIO,text:pe.TEXT}[j];$e&&s[$e].push({id:vt,kind:$e,segmentReference:de,profiles:Te,duration:l,bitrate:G,mime:L,codecs:N,width:ne,height:x,fps:me,quality:oe})}}return{dynamic:d,liveAvailabilityStartTime:h,duration:l,container:A,representations:s}},pn=({id:a,width:e,height:t,bitrate:i,fps:s,quality:n})=>{const o=(n?It(n):void 0)??r.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:s}},mn=({id:a,bitrate:e})=>({id:a,bitrate:e}),gn=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},bn=({id:a,lang:e,url:t,isAuto:i})=>({id:a,url:t,isAuto:i,type:"internal",language:e}),qi=a=>"size"in a,kt=a=>a.type===Re.TEMPLATE,wi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);class Wi{onLastSegment$=new r.ValueSubject(!1);fullyBuffered$=new r.ValueSubject(!1);playingRepresentation$=new r.ValueSubject(void 0);playingRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;gaps=[];subscription=new r.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Ie;destroyAbortController=new Ie;getCurrentPosition;isActiveLowLatency;tuning;forwardBufferTarget;fetcher;bufferLimit=1/0;sourceBufferTaskQueue;gapDetectionIdleCallback;initLoadIdleCallback;failedDownloads=0;compatibilityMode;preloadOnly;isLive=!1;liveUpdateSegmentIndex=0;liveInitialAdditionalOffset=0;isSeekingLive=!1;index=0;constructor(e,t,i,s,{fetcher:n,tuning:o,getCurrentPosition:u,isActiveLowLatency:d,compatibilityMode:c=!1,manifest:h}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=c,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=u,this.isActiveLowLatency=d,this.isLive=!!h?.dynamic,this.container=i,i){case xt.MP4:this.containerParser=rn;break;case xt.WEBM:this.containerParser=hn;break;default:r.assertNever(i)}this.initData=new Map(s.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=r.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);r.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 Lr(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const u=Math.min(this.bufferLimit,ui(this.sourceBuffer.buffered)*.8);this.bufferLimit=u,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),s=this.segments.get(t.id),n=this.parsedInitData.get(t.id);r.assertNonNullable(i,"No init buffer for starting representation"),r.assertNonNullable(s,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(s,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=r.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);r.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(r.isNullable(s)||r.isNullable(i)?yield this.loadInit(t,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),r.assertNonNullable(i,"No segments for starting representation"),s=this.initData.get(e),!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal);const n=this.getCurrentPosition();r.isNonNullable(n)&&(this.isLive||(i.forEach(o=>o.status=M.NONE),this.pruneBuffer(n,1/0,!0)),this.maintain(n))}.bind(this));abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ie,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find(c=>e>=c.time.from&&e<c.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const h=ke(this.sourceBuffer.buffered,e),l=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=s.time.to-e+100&&(n=l)}if(isFinite(this.bufferLimit)&&ui(this.sourceBuffer.buffered)>=this.bufferLimit){const c=ke(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,n),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(u.includes(s))c="high";else{const h=u.at(0);h&&h.time.from-s.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===M.FED&&!u.length&&ke(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=i.at(-1);d&&d.status===M.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let i=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:n.time.from+s}),i=n.time.to;r.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let n=0,o=t.length-1;do s.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<i&&o>=0);return this.liveInitialAdditionalOffset=n-i,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}seekLive=r.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const u of this.representations.keys()){const d=e.find(l=>l.id===u);d&&this.representations.set(u,d);const c=this.representations.get(u);if(!c||!kt(c.segmentReference))return;const h=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,h)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);r.assertNonNullable(i);const s=this.segments.get(t);r.assertNonNullable(s,"No segments for starting representation");const n=this.initData.get(t);if(r.assertNonNullable(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;const o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));updateLive(e){for(const t of e?.representations[this.kind].values()??[]){if(!t||!kt(t.segmentReference))return;const i=t.segmentReference.segments.map(u=>({...u,status:M.NONE,size:void 0})),s=this.segments.get(t.id)??[],n=s.at(-1)?.time.to??0,o=i?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const u=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,u)}else{const u=i.slice(o+1);this.segments.set(t.id,[...s,...u])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!kt(i))return;const s=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=wt(i.segmentTemplateUrl,{segmentTime:s}),o=this.segments.get(t.id)??[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:M.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){const t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;const i=this.segments.get(t);return i?i.find(n=>n.time.from<=e&&n.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const s=e.findIndex(({status:l,time:{from:f,to:p}},g)=>{const y=f<=i&&p>=i,b=f>i||y||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&f<=i+k||p<=i+k;return(l===M.NONE||l===M.PARTIALLY_EJECTED&&b&&A&&this.sourceBuffer&&!Ct(this.sourceBuffer.buffered,i))&&b&&A});if(s===-1)return[];if(t!==Re.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,u=0;const d=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,h=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<n.length&&(o<=c||u<=h);l++){const f=n[l];if(o+=f.byte.to+1-f.byte.from,u+=f.time.to+1-f.time.from,f.status===M.NONE||f.status===M.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){t.segmentReference.type===Re.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=M.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:n,url:o,signal:u,onProgress:d,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await r.abortable(u,async function*(){const h=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,h))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{const h=await this.fetcher.fetch(o,{range:n,signal:u,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!h)return;const l=new DataView(h);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(l,f)}d&&s.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,u),s.segment.status=M.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(h){if(!wi(h))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(h)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const d of e)d.status=M.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:n,signal:o,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await r.abortable(o,async function*(){const d=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:s,onProgress:u,signal:o,priority:i}),this.failedDownloads=0}catch(d){if(!wi(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}}prepareByteRangeFetchSegmentParams(e,t){if(kt(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,s={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:s,signal:n,onProgress:(d,c)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:c,signal:n,onSegmentAppendFailed:o,globalFrom:s?s.from:0,representationId:t.id})}catch(h){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}}}prepareTemplateFetchSegmentParams(e,t){if(!kt(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const s=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},u=[],c=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(h,l)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:h,loaded:l,signal:n,onSegmentAppendFailed:o,representationId:t.id});u.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:s,signal:n,onProgress:c,onProgressTasks:u}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){let t=!1;const i=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(i)&&(t=ke(this.sourceBuffer?.buffered,i)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,t||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:s,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const u of this.activeSegments){const{segment:d}=u;if(u.representationId===t){if(n.aborted){s();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){const c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=this.containerParser.parseFeedableSegmentChunk(c);h?.byteLength&&(d.status=M.PARTIALLY_FED,u.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),u.fedBytes+=h.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:s,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:l}=h,f=d===Re.BYTE_RANGE,p=f?l.byte.to-l.byte.from+1:c;if(h.representationId!==t||!(!f||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const y=f?l.byte.from-i:0,b=f?l.byte.to-i:e.byteLength,k=y<s,A=b<=s;if(l.status===M.DOWNLOADING&&k&&A){l.status=M.DOWNLOADED;const m=new DataView(e.buffer,e.byteOffset+y,p);this.sourceBufferTaskQueue.append(m,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(h,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&k&&(h.loadedBytes=Math.min(p,s-y),h.loadedBytes>h.feedingBytes)){const m=new DataView(e.buffer,e.byteOffset+y+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===p?m:this.containerParser.parseFeedableSegmentChunk(m);T?.byteLength&&(l.status=M.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then($=>{if(n.aborted)o();else if($)h.fedBytes+=T.byteLength,h.fedBytes===p&&this.onSegmentFullyAppended(h,t);else{if(h.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=M.FED,qi(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const s of this.segments.get(i.id)??[])s.status===M.FED&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status=M.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===M.PARTIALLY_FED||e.status===M.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=M.NONE),e.status=M.PARTIALLY_EJECTED):e.status=M.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=oi(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(async u=>{if(!u)return;const{init:d,dataView:c,segments:h}=u,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l);let f=h;this.isLive&&kt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,u=!1;const d=c=>{n=Math.min(n,c.time.from),o=Math.max(o,c.time.to);const h=qi(c)?c.size??0:c.byte.to-c.byte.from;s+=h};for(const c of this.segments.values())for(const h of c){if(h.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;h.status===M.FED&&d(h)}if(u=isFinite(n)&&isFinite(o),!u){s=0,n=1/0,o=-1/0;for(const c of this.segments.values())for(const h of c){if(h.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;h.status===M.FED&&d(h)}}if(u=isFinite(n)&&isFinite(o),!u)for(let c=0;c<this.sourceBuffer.buffered.length;c++){const h=this.sourceBuffer.buffered.start(c)*1e3,l=this.sourceBuffer.buffered.end(c)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===M.NONE&&Math.round(p.time.from)<=Math.round(h)&&Math.round(p.time.to)>=Math.round(l)){n=h,o=l;break}}if(u=isFinite(n)&&isFinite(o),!u&&i){s=0,n=1/0,o=-1/0;const c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const h of this.segments.values())for(const l of h)l.time.from>e+c&&l.status===M.FED&&d(l)}return u=isFinite(n)&&isFinite(o),u?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)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let s={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,u=this.sourceBuffer.buffered.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){s=void 0;break}u>i.time.from&&u<i.time.to&&(s.from=u),o<i.time.to&&o>i.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=oi(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const s=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:s,to:n})}const t=1;for(const i of this.segments.values())for(const s of i){const{status:n}=s;if(n!==M.FED&&n!==M.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),u=Math.ceil(s.time.to),d=e.some(h=>h.from-t<=o&&h.to+t>=u),c=e.filter(h=>o>=h.from-t&&o<=h.to+t||u>=h.from-t&&u<=h.to+t);d||(c.length===1?s.status=M.PARTIALLY_EJECTED:s.status=M.NONE)}}}var Pt;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(Pt||(Pt={}));class Sn{throughputEstimator;requestQuic;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);abortAllController=new Ie;subscription=new r.Subscription;compatibilityMode;constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Li(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=r.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ct(t));const i=yield yt(t,{signal:this.abortAllController.signal}).catch(Ft);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=r.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:i,onProgress:s,priority:n="auto",signal:o,measureThroughput:u=!0,isLowLatency:d=!1}={}){let c=e;const h=new Headers;if(i)switch(t){case Pt.HEADER:{h.append("Range",`bytes=${i.from}-${i.to}`);break}case Pt.PARAM:{const C=new URL(c,location.href);C.searchParams.append("bytes",`${i.from}-${i.to}`),c=C.toString();break}default:r.assertNever(t)}this.requestQuic&&(c=ct(c));let l=this.abortAllController.signal,f;if(o){const C=new Ie;if(f=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(o,"abort")).subscribe(()=>{try{C.abort()}catch(I){Ft(I)}}),this.abortAllController.signal.aborted||o.aborted)try{C.abort()}catch(I){Ft(I)}l=C.signal}const p=r.now(),g=yield yt(c,{priority:n,headers:h,signal:l}).catch(Ft),y=r.now();if(!g)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-p),!g.ok||!g.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!s&&!u)return f?.unsubscribe(),g.arrayBuffer();const[b,k]=g.body.tee(),A=b.getReader();u&&this.throughputEstimator?.trackStream(k,d);let m=0,T=new Uint8Array(0),$=!1;const R=C=>{f?.unsubscribe(),$=!0,Ft(C)},_=r.abortable(l,async function*({done:C,value:I}){if(m===0&&this.lastRequestFirstBytes$.next(r.now()-p),l.aborted){f?.unsubscribe();return}if(!C&&I){const S=new Uint8Array(T.length+I.length);S.set(T),S.set(I,T.length),T=S,m+=I.byteLength,s?.(new DataView(T.buffer),m),yield A?.read().then(_,R)}}.bind(this));return yield A?.read().then(_,R),f?.unsubscribe(),$?null:T.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:s}=e;switch(s){case Re.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case Re.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:r.assertNever(s)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==Re.BYTE_RANGE)return null;const{from:s,to:n}=e.initRange;let o=s,u=n,d=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,d=n+1===c,d&&(o=Math.min(c,s),u=Math.max(h,n))),o=Math.min(o,0);const l=yield this.fetch(e.url,{range:{from:o,to:u},priority:i,measureThroughput:!1});if(!l)return null;const f=new DataView(l,s-o,n-o+1);if(!t.validateData(f))throw new Error("Invalid media file");const p=t.parseInit(f),g=e.indexRange??t.getIndexRange(p);if(!g)throw new ReferenceError("No way to load representation index");let y;if(d)y=new DataView(l,g.from-o,g.to-g.from+1);else{const k=yield this.fetch(e.url,{range:g,priority:i,measureThroughput:!1});if(!k)return null;y=new DataView(k)}const b=t.parseSegments(y,p,g);return{init:p,dataView:new DataView(l),segments:b}}.bind(this));fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==Re.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),s=yield this.fetch(i,{priority:t,measureThroughput:!1});return s?{init:null,segments:e.segments.map(o=>({...o,status:M.NONE,size:void 0})),dataView:new DataView(s)}:null}.bind(this))}const Ft=a=>{if(!wi(a))throw a},Ai=1e3,fi=(a,e,t)=>t*e+(1-t)*a,Cs=(a,e)=>a.reduce((t,i)=>t+i,0)/e,yn=(a,e,t,i)=>{let s=0,n=t;const o=Cs(a,e),u=e<i?e:i;for(let d=0;d<u;d++)a[n]>o?s++:s--,n=(a.length+n-1)%a.length;return Math.abs(s)===u};class xi{prevReported=void 0;rawSeries$;smoothedSeries$;reportedSeries$;smoothed;pastMeasures=[];takenMeasures=0;measuresCursor=0;params;smoothed$;debounced$;constructor(e){this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ge(`raw_${t}`),this.smoothedSeries$=new Ge(`smoothed_${t}`),this.reportedSeries$=new Ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.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))}}class Tn extends xi{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=fi(this.slow,e,this.params.emaAlphaSlow),this.fast=fi(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class vn extends xi{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Cs(this.pastMeasures,this.takenMeasures);this.emaSmoothed=fi(this.emaSmoothed,e,this.params.emaAlpha);const i=yn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class En extends xi{extremumInterval;furtherValues=[];currentTopExtremumValue=0;constructor(e){super(e),this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?fi(this.smoothed,e,this.params.emaAlpha):e}}class Pi{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Tn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new vn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new En({initial:e,label:"liveEdgeDelay",...t})}}const kn=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},Qi=["timeupdate","progress","play","seeked","stalled","waiting"];var Le;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(Le||(Le={}));let $n=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new r.Subscription;representationSubscription=new r.Subscription;fetcher;state$=new q(Le.NONE);currentVideoRepresentation$=new r.ValueSubject(void 0);currentVideoRepresentationInit$=new r.ValueSubject(void 0);error$=new r.Subject;lastConnectionType$=new r.ValueSubject(void 0);lastConnectionReused$=new r.ValueSubject(void 0);lastRequestFirstBytes$=new r.ValueSubject(void 0);isLive$=new r.ValueSubject(!1);liveDuration$=new r.ValueSubject(0);liveAvailabilityStartTime$=new r.ValueSubject(void 0);bufferLength$=new r.ValueSubject(0);liveLoadBufferLength$=new r.ValueSubject(0);livePositionFromPlayer$=new r.ValueSubject(0);liveEstimatedDelay;waitingEventInterval;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new r.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;destroyController=new Ie;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Sn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Pi.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=r.abortable(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=Se(t,i,X.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Le.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(Le.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=r.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=fn(e??"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;const i=({kind:s,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&window.MediaSource?.isTypeSupported?.(`${n}; codecs="${o}"`)||s===pe.TEXT);return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([s,n])=>[s,n.filter(i)]))}}.bind(this));async seekLive(e){r.assertNonNullable(this.element);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Se(this.manifestUrlString,t,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initRepresentations=r.abortable(this.destroyController.signal,async function*(e,t){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Le.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new Wi(pe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(t)&&(this.audioBufferManager=new Wi(pe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(r.interval(Ai).subscribe(o=>{if(this.element?.paused){const u=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=Se(this.manifestUrlString,u+Ai,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Qi.map(o=>r.fromEvent(this.element,o))).pipe(r.map(o=>this.element?ke(this.element.buffered,this.element.currentTime*1e3):0),r.filterChanged(),r.filter(o=>!!o),r.tap(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(r.filter(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,c=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,l=u-d;let f=1+Math.sign(l)*h;Math.abs(l)<c?f=1:Math.abs(l)>c*2&&(f=1+Math.sign(l)*h*2),kn(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{let d=0;if(u){const c=(this.element?.currentTime??0)*1e3;d=Math.min(...this.bufferManagers.map(l=>l.getLiveSegmentsToLoadState(this.manifest)?.to??0))-c}d&&this.liveLoadBufferLength$.getValue()!==d&&this.liveLoadBufferLength$.next(d)}));let o=0;this.representationSubscription.add(r.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:u,bufferLength:d})=>{if(r.assertNonNullable(this.element),this.isUpdatingLive)return;const c=this.element.playbackRate,h=si(this.manifestUrlString,X.DASH_CMAF_OFFSET_P),l=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(l,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*c),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*c,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,y=this.isActiveLowLatency?d:u;let b=Ye.None;if(this.isActiveLowLatency?b=Ye.ActiveLowLatency:y<f+g&&y>=f?b=Ye.LiveWithTargetOffset:h!==0&&y<f&&(b=Ye.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),b===Ye.LiveForwardBuffering||b===Ye.LiveWithTargetOffset){const k=o-(f+p),A=this.normolizeLiveOffset(Math.trunc(h+k/c)),m=Math.abs(A-h);let T;!u||m<=this.tuning.dashCmafLive.offsetCalculationError?T=h:A>0&&m>this.tuning.dashCmafLive.offsetCalculationError?T=A:T=0,this.manifestUrlString=Se(this.manifestUrlString,T,X.DASH_CMAF_OFFSET_P)}b!==Ye.None&&b!==Ye.ActiveLowLatency&&(o=0,this.updateLive())}))}const s=r.merge(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=r.merge(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:s,someBufferEnded:n}).pipe(r.filter(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).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:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:o})}})),this.representationSubscription.add(r.merge(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>this.source?.addEventListener("sourceopen",o))),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(Le.REPRESENTATIOS_READY)}.bind(this));initBuffer(){r.assertNonNullable(this.element),this.state$.setState(Le.RUNNING),this.subscription.add(r.merge(...Qi.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ct(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){return{[pe.VIDEO]:this.videoBufferManager,[pe.AUDIO]:this.audioBufferManager,[pe.TEXT]:null}[e]?.switchTo(t)}seek(e,t){r.assertNonNullable(this.element),r.assertNonNullable(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Ct(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Le.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:r.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}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=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const s=Math.max(...i);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class Ls{scene3D;subscription=new r.Subscription;videoState=new q(ee.STOPPED);video;player;params;elementSize$=new r.ValueSubject(void 0);textTracksManager=new Fe;droppedFramesManager=new Qt;videoTracks$=new r.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new ls;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new $n({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Ke(this.video),s=this.constructor.name,n=u=>{e.error$.next({id:s,category:r.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:u})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(u,d)=>this.subscription.add(u.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(r.map(c=>c.map(({track:h})=>h)))}),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.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(dt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,i.volumeState$,s)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(rt(this.video,t.playbackRate,i.playbackRateState$,s)),n(zt(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(i.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c===Le.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const l=this.player.getRepresentations();r.assertNonNullable(l,"Manifest not loaded or empty");const f=Array.from(l.audio).sort((b,k)=>k.bitrate-b.bitrate),p=Array.from(l.video).sort((b,k)=>k.bitrate-b.bitrate),g=Array.from(l.text);if(!this.params.tuning.isAudioDisabled)for(const b of f){const k=mn(b);k&&this.audioTracks.push({track:k,representation:b})}for(const b of p){const k=pn(b);if(k){h.push({track:k,representation:b});const A=!this.params.tuning.isAudioDisabled&&gn(f,p,b);A&&this.audioRepresentations.set(b.id,A)}}this.videoTracks$.next(h);for(const b of g){const k=bn(b);k&&this.textTracks.push({track:k,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const y=this.selectVideoRepresentation();r.assertNonNullable(y),this.player.initRepresentations(y.id,this.audioRepresentations.get(y.id)?.id)}else c===Le.REPRESENTATIOS_READY&&(this.videoState.setState(ee.READY),this.player.initBuffer())},s));const o=c=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!==Le.RUNNING||h||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const l=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l){this.player.switchRepresentation(pe.VIDEO,l.id).catch(o);const p=this.audioRepresentations.get(l.id);p&&this.player.switchRepresentation(pe.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(c=>c&&this.videoTracks$.getValue().find(({representation:{id:h}})=>h===c)?.track)).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const u=t.playbackState.stateChangeStarted$.pipe(r.map(({to:c})=>c===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const c=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(r.merge(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:l}})=>l===t)?.track,s=this.params.output.currentVideoTrack$.getValue(),n=ke(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,u=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),d=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,s?this.audioRepresentations.get(s.id)?.bitrate??0:0),c=Tt(this.videoTracks$.getValue().map(({track:l})=>l),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:d,forwardBufferHealth:u,current:s,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=e?c??i:i??c;return h&&this.videoTracks$.getValue().find(({track:l})=>l===h)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(s.state===V.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==ee.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(s.position-o,s.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ee.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();return;case ee.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ee.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new ks(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};playIfAllowed(){nt(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}}class wn extends Ls{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let An=class extends $s{constructor(e){super(e),this.liveOffset=new Wt}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(r.combine({interval:r.interval(ki),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===Z.PLAYING){const n=e.position$.getValue()+(s-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&i===Z.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(o,s)})}};class Pn extends Ls{constructor(e){super(e),this.liveOffset=new Wt}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.combine({interval:r.interval(Ai),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()===ee.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(s-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&i===ee.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(o,s)})}}const je={};var Y;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Y||(Y={}));const Ot=(a,e)=>new r.Observable(t=>{const i=(s,n)=>t.next(n);return a.on(e,i),()=>a.off(e,i)});class Dn{subscription=new r.Subscription;videoState=new q(Y.INITIALIZING);video;params;hls;textTracksManager=new Fe;trackLevels=new Map;constructor(e){this.video=Je(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(s=>{e||(je.Hls=s.default,je.Events=s.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){r.assertNonNullable(je.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=c=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:c})},s=Ke(this.video),n=(c,h)=>this.subscription.add(c.subscribe(h,i));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(dt(this.video,e.isLooped,i)),this.subscription.add(Qe(this.video,e.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(rt(this.video,e.playbackRate,s.playbackRateState$,i)),this.subscription.add(Ot(this.hls,je.Events.ERROR).subscribe(c=>{c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${c.err?.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),w(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),n(Ot(this.hls,je.Events.MANIFEST_PARSED).pipe(r.map(({levels:c})=>c.reduce((h,l)=>{const f=l.name||l.height.toString(10),{width:p,height:g}=l,y=It(l.attrs.QUALITY??"")??r.videoSizeToQuality({width:p,height:g});if(!y)return h;const b=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,k={id:f.toString(),quality:y,bitrate:l.bitrate/1e3,size:{width:p,height:g},fps:b};return this.trackLevels.set(f,{track:k,level:l}),h.push(k),h},[]))),t.availableVideoTracks$),n(Ot(this.hls,je.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){const h=[];for(const l of c.subtitleTracks){const f=l.name,p=l.attrs.URI||"",g=l.lang,y="internal";h.push({id:f,url:p,language:g,type:y})}e.internalTextTracks.startTransitionTo(h)}}),n(Ot(this.hls,je.Events.LEVEL_LOADING).pipe(r.map(({url:c})=>ye(c))),t.hostname$),this.subscription.add(Ve(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:i}));const o=c=>Array.from(this.trackLevels.values()).find(({level:h})=>h===c)?.track,u=Ot(this.hls,je.Events.LEVEL_SWITCHED).pipe(r.map(({level:c})=>o(this.hls.levels[c])));u.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ve(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),c=>{if(r.isNullable(c))return;const h=this.trackLevels.get(c.id)?.level;if(!h)return;const l=this.hls.levels.indexOf(h),f=this.hls.currentLevel,p=this.hls.levels[f];!p||h.bitrate>p.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:u,onError:i})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(e!==Y.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&s.state===V.Requested&&this.seek(s.position),t){case exports.PlaybackState.STOPPED:switch(e){case Y.STOPPED:break;case Y.READY:case Y.PLAYING:case Y.PAUSED:this.stop();break;default:r.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PLAYING:case Y.PAUSED:break;default:r.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Y.PLAYING:break;case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PAUSED:this.playIfAllowed();break;default:r.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Y.PAUSED:break;case Y.STOPPED:this.prepare();break;case Y.READY:this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Y.PLAYING:this.pause();break;default:r.assertNever(e)}break;default:r.assertNever(t)}};prepare(){this.videoState.startTransitionTo(Y.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Y.PLAYING),await nt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(Y.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(Y.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Ji="X-Playback-Duration";var Xi=async a=>{const e=await yt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Ji)?parseInt(e.headers.get(Ji),10):void 0};const Cn=a=>{let e=null;if(a.QUALITY&&(e=It(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(s=>parseInt(s,10));e=r.videoSizeToQuality({width:t,height:i})}return e??null},xs=async(a,e=a)=>{const s=(await(await yt(a)).text()).split(`
|
|
46
|
+
`),n=[],o=[];for(let u=0;u<s.length;u++){const d=s[u],c=d.match(/^#EXT-X-STREAM-INF:(.+)/),h=d.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const l=Object.fromEntries(c[1].split(",").map(A=>A.split("="))),f=l.QUALITY??`stream-${l.BANDWIDTH}`,p=Cn(l);let g;l.BANDWIDTH&&(g=parseInt(l.BANDWIDTH,10)/1e3||void 0),!g&&l["AVERAGE-BANDWIDTH"]&&(g=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const y=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let b;if(l.RESOLUTION){const[A,m]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));A&&m&&(b={width:A,height:m})}const k=new URL(s[++u],e).toString();p&&n.push({id:f,quality:p,url:k,bandwidth:g,size:b,fps:y})}if(h){const l=Object.fromEntries(h[1].split(",").map(y=>y.split("=")).map(([y,b])=>[y,b.replace(/^"|"$/g,"")])),f=l.URI?.replace(/playlist$/,"subtitles.vtt"),p=l.LANGUAGE,g=l.NAME;f&&p&&o.push({type:"internal",id:p,label:g,language:p,url:f,isAuto:!1})}}}return{qualityManifests:n,textTracks:o}};var W;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(W||(W={}));class Ln{subscription=new r.Subscription;videoState=new q(W.STOPPED);video;params;textTracksManager=new Fe;masterManifest;manifests$=new r.ValueSubject([]);maxSeekBackTime$;liveOffset=new Wt;manifestStartTime$=new r.ValueSubject(void 0);constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},xs(Se(this.params.source.url),this.params.source.url).then(({qualityManifests:t})=>{if(t.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:r.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),n=s?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const u=i?"master":n;return i&&!s&&t.startTransitionTo(this.masterManifest),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,i));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&r.isNonNullable(c.to)){const l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(p=>p.id===l);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ye(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),u&&u.state===V.Requested&&this.seek(u.position)},i)),this.subscription.add(s.loadedData$.subscribe(()=>{const u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:u,currentTime:d})=>this.params.output.liveTime$.next(u+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.map(u=>u.map(({id:d,quality:c,size:h,bandwidth:l,fps:f})=>({id:d,quality:c,size:h,fps:f,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:u,min:d}=t?.to??i??{};for(const[c,h]of[[u,"mq"],[d,"lq"]]){const l=String(parseFloat(c||""));h&&c&&s.searchParams.set(h,l)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?X.DASH_CMAF_OFFSET_P:X.OFFSET_P,o=Se(s.toString(),this.liveOffset.getTotalOffset(),n);this.video.setAttribute("src",o),this.video.load(),Xi(o).then(u=>{if(!r.isNullable(u))this.maxSeekBackTime$.next(u);else{const d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(r.isNullable(d)||!isFinite(d))try{yt(o).then(c=>c.text()).then(c=>{const h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(h){const l=new URL(h,o).toString();Xi(l).then(f=>{r.isNullable(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(n||o||u){const h=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(s?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested){this.videoState.startTransitionTo(W.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case W.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(W.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);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else s?.to===exports.PlaybackState.PAUSED&&(w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case W.CHANGING_MANIFEST:break;default:return r.assertNever(t)}}}var J;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(J||(J={}));class xn{subscription=new r.Subscription;videoState=new q(J.STOPPED);video;params;textTracksManager=new Fe;masterManifest;manifests$=new r.ValueSubject([]);constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),s=t.getTransition(),n=s?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const u=i?"master":n;return i&&!s&&t.startTransitionTo(this.masterManifest),o.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d));if(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.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},i).add(s.loadedMetadata$.subscribe(()=>{const u=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&r.isNonNullable(c.to)){const l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);const f=this.manifests$.getValue().find(p=>p.id===l);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ye(f.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),d&&d.from===J.CHANGING_MANIFEST&&this.videoState.setState(d.to),u.state===V.Requested&&this.seek(u.position)},i))),this.subscription.add(this.manifests$.pipe(r.map(u=>u.map(({id:d,quality:c,size:h,bandwidth:l,fps:f})=>({id:d,quality:c,size:h,fps:f,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!r.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:u}=this.video;this.subscription.add(r.merge(r.fromEvent(u,"addtrack"),r.fromEvent(u,"removetrack"),r.fromEvent(u,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<u.length;d++)u[d].mode="hidden"},i))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),s=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:n,min:o}=t?.to??i??{};for(const[u,d]of[[n,"mq"],[o,"lq"]]){const c=String(parseFloat(u||""));d&&u&&s.searchParams.set(d,c)}}this.video.setAttribute("src",s.toString()),this.video.load()}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(t===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(n||o||u){const h=this.videoState.getState();this.videoState.setState(J.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:l}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:l*1e3,forcePrecise:!0});return}switch(s?.to!==exports.PlaybackState.PAUSED&&c.state===V.Requested&&this.seek(c.position),t){case J.READY:i===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):s?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):s?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case J.CHANGING_MANIFEST:break;default:return r.assertNever(t)}}}var te;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(te||(te={}));class Rn{subscription=new r.Subscription;videoState=new q(te.STOPPED);video;trackUrls={};params;textTracksManager=new Fe;constructor(e){this.params=e,this.video=Je(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},s=Ke(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,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.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Qe(this.video,t.volume,s.volumeState$,i)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(rt(this.video,t.playbackRate,s.playbackRateState$,i)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===te.READY&&this.videoState.setState(te.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&r.isNonNullable(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===te.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Xe(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;r.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];r.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ct(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ye(t))}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==te.STOPPED&&(this.videoState.startTransitionTo(te.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(te.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.autoVideoTrackLimits.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(n&&e!==te.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),u.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:d*1e3,forcePrecise:!0}),o.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[o.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!==exports.PlaybackState.PAUSED&&u.state===V.Requested&&this.seek(u.position),e){case te.READY:t===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case te.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const s=Object.values(this.trackUrls).find(u=>!r.isInvariantQuality(u.track.quality)&&r.isLowerOrEqual(u.track.quality,e))?.track,n=this.params.desiredState.videoTrack.getState()?.id,o=this.trackUrls[n??"0"]?.track;if(s&&o&&r.isHigherOrEqual(o.quality,s.quality)&&(t=s),!t){const u=Object.values(this.trackUrls).filter(c=>!r.isInvariantQuality(c.track.quality)&&r.isHigher(c.track.quality,e)),d=u.length;d&&(t=u[d-1].track)}t&&(i=t.quality)}else if(!e){const s=Object.values(this.trackUrls).map(n=>n.track);t=Tt(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}}const Ki=["stun:videostun.mycdn.me:80"],In=1e3,Nn=3,Ti=()=>null;class _n{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Ti;externalStopCallback=Ti;externalErrorCallback=Ti;constructor(e,t){this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Ki}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),In)}normalizeOptions(e={}){const t={stunServerList:Ki,maxRetryNumber:Nn,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Q;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(Q||(Q={}));class Bn{subscription;params;log;video;videoState=new q(Q.STOPPED);liveStreamClient;maxSeekBackTime$=new r.ValueSubject(0);constructor(e){this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Je(e.container),this.liveStreamClient=new _n(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Xe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(o)}`})});const s=Ke(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(s.timeUpdate$,e.liveTime$),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$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===Q.READY&&this.videoState.setState(Q.READY)},i)).add(s.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED)},i)).add(s.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING)},i)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Qe(this.video,t.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Q.READY:break;case Q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:r.VideoQuality.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t===exports.PlaybackState.STOPPED){e!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.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(Q.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case Q.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),w(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()):i?.to===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(e)}}}class Zi{iterator;current;constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}const Rs=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,pi=document.createElement("video"),Mn='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Vn='video/mp4; codecs="hev1.1.6.L93.B0"',Is='video/webm; codecs="vp09.00.10.08"',Ns='video/webm; codecs="av01.0.00M.08"',Fn='audio/mp4; codecs="mp4a.40.2"',On='audio/webm; codecs="opus"',he={mms:!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),mse:!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),hls:!!(pi.canPlayType?.("application/x-mpegurl")||pi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},De={mp4:!!pi.canPlayType?.("video/mp4"),webm:!!pi.canPlayType?.("video/webm"),cmaf:!0},We={h264:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Mn),h265:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Vn),vp9:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Is),av1:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Ns),aac:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(Fn),opus:!!(window.MediaSource||window.ManagedMediaSource)?.isTypeSupported?.(On)},$t=(We.h264||We.h265)&&We.aac;var ut;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(ut||(ut={}));var at;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg"})(at||(at={}));let mt;const Un=async()=>{if(!window.navigator.mediaCapabilities)return;const a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Ns}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Is}})]);mt={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{Un()}catch(a){console.error(a)}const qt=he.hls&&De.mp4,Hn=()=>Object.keys(We).filter(a=>We[a]),jn=(a,e=!1,t=!1)=>a.filter(i=>{switch(i){case exports.VideoFormat.DASH:return he.mse&&De.mp4&&$t;case exports.VideoFormat.DASH_SEP:return(he.mse||he.mms&&t)&&De.mp4&&$t;case exports.VideoFormat.DASH_WEBM:return(he.mse||he.mms&&t)&&De.webm&&We.vp9&&We.opus;case exports.VideoFormat.DASH_WEBM_AV1:return(he.mse||he.mms&&t)&&De.webm&&We.av1&&We.opus;case exports.VideoFormat.DASH_LIVE:return he.mse&&De.mp4&&$t;case exports.VideoFormat.DASH_LIVE_CMAF:return(he.mse||he.mms&&t)&&De.mp4&&$t&&De.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return(he.mse||he.mms&&t)&&De.mp4&&$t;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return qt||e&&he.mse&&De.mp4&&$t;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return qt;case exports.VideoFormat.MPEG:return De.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return he.webrtc&&he.ws&&We.h264&&(De.mp4||De.webm);default:return r.assertNever(i)}}),Ut=a=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(a){case ut.VP9:return[e,t];case ut.AV1:return[t,e];case ut.NONE:return[];case ut.SMOOTH:return mt?mt[t].smooth?[t,e]:mt[e].smooth?[e,t]:[t,e]:[e,t];case ut.POWER_EFFICIENT:return mt?mt[t].powerEfficient?[t,e]:mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(a)}return[e,t]},Yn=({webmCodec:a,androidPreferredFormat:e})=>{if(Rs)switch(e){case at.MPEG:return[exports.VideoFormat.MPEG,...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case at.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case at.DASH:return[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return qt?[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Ut(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Gn=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],s=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...s],o=[...s,...i];let u;if(Rs)switch(a){case at.DASH:{u=n;break}case at.HLS:case at.MPEG:{u=o;break}}else qt?u=o:u=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...u]:[...u,exports.VideoFormat.WEB_RTC_LIVE]},es=a=>a?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var zn=a=>new r.Observable(e=>{const t=new r.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:c,to:h})=>`${c}-${h}`)),s=a.desiredPlaybackState$.stateChangeEnded$,n=a.providerChanged$.pipe(r.map(({type:c})=>c!==void 0)),o=new r.Subject;let u=0,d="unknown";return t.add(i.subscribe(c=>{u&&window.clearTimeout(u),d=c,u=window.setTimeout(()=>o.next(c),a.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(u),d="unknown",u=0})),t.add(n.subscribe(c=>{u&&(window.clearTimeout(u),u=0,c&&(u=window.setTimeout(()=>o.next(d),a.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});const qn={cacheDuration:12e4},Wn={chunkDuration:5e3,maxParallelRequests:5};class Qn{current$=new r.ValueSubject({type:void 0});providerError$=new r.Subject;noAvailableProvidersError$=new r.Subject;providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)};subscription=new r.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=jn([...Gn(this.params.tuning),...Yn(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>r.isNonNullable(e.sources[u]));console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(t);const{forceFormat:i,formatsToAvoid:s}=this.params.tuning;let n=[];i?n=[i]:s.length?n=[...t.filter(u=>!s.includes(u)),...t.filter(u=>s.includes(u))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Zi(n);const o=[...es(!0),...es(!1)];this.chromecastFormatsIterator=new Zi(o.filter(u=>r.isNonNullable(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),s=i.state!==V.None;if(this.params.desiredState.seekState.setState({state:V.Requested,position:s?i.position:t,forcePrecise:s?i.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ge.SCREEN:return this.createScreenProvider(t);case ge.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Na({...o,source:u,config:qn})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),this.params.tuning.useDashJs?new Mi({...o,source:u,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new wn({...o,source:u}):new Cr({...o,source:u})}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),this.params.tuning.useDashJsCMAF?new Mi({...o,source:u,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new Pn({...o,source:u}):new An({...o,source:u})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),qt||!this.params.tuning.useHlsJs?new xn({...o,source:u}):new Dn({...o,source:u})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Ln({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Rn({...o,source:u})}case exports.VideoFormat.DASH_LIVE:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Ca({...o,source:u,config:{...Wn,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const u=this.applyFailoverHost(t[e]);return r.assertNonNullable(u),new Bn({container:i,source:u,desiredState:s,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 r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:s,meta:n}=this.params,o=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(u),new Js({connection:u,meta:n,container:i,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ge.CHROMECAST:ge.SCREEN}chooseFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ge.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case ge.SCREEN:return this.screenFormatsIterator.next();case ge.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case ge.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ge.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=s=>{const n=new URL(s);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:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([s,n])=>[s,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;const s=r.now();return e.add(r.merge(this.providerOutput.error$,zn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(n=>({id:`ProviderHangup:${n}`,category:r.ErrorCategory.WTF,message:`A ${n} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const n=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(n)})),e.add(this.providerError$.subscribe(n=>{const o=this.current$.getValue().destination;if(o===ge.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ge.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const u=n.category===r.ErrorCategory.NETWORK,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit,h=d&&(u&&t||!c),l=n.id.includes("partial_metadata"),f=r.now()-s;h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l&&f<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():c?(i++,this.reinitProvider()):this.switchToNextProvider(o??ge.SCREEN)}})),e}}const Jn=5e3,ts="one_video_throughput",is="one_video_rtt",Yt=window.navigator.connection,ss=()=>{const a=Yt?.downlink;if(r.isNonNullable(a)&&a!==10)return a*1e3},as=()=>{const a=Yt?.rtt;if(r.isNonNullable(a)&&a!==3e3)return a},rs=(a,e,t)=>{const i=t*8,s=i/a;return i/(s+e)};class Gt{throughput;rtt;subscription=new r.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=Gt.load(ts)||(e.useBrowserEstimation?ss():void 0)||Jn,i=Gt.load(is)??(e.useBrowserEstimation?as():void 0)??0;if(this.throughput$=new r.ValueSubject(t),this.rtt$=new r.ValueSubject(i),this.rttAdjustedThroughput$=new r.ValueSubject(rs(t,i,e.rttPenaltyRequestSize)),this.throughput=Pi.getSmoothedValue(t,-1,e),this.rtt=Pi.getSmoothedValue(i,1,e),e.useBrowserEstimation){const s=()=>{const o=ss();o&&this.throughput.next(o);const u=as();r.isNonNullable(u)&&this.rtt.next(u)};Yt&&"onchange"in Yt&&this.subscription.add(r.fromEvent(Yt,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{r.safeStorage.set(ts,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{r.safeStorage.set(is,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:s,rtt:n})=>rs(s,n,e.rttPenaltyRequestSize)),r.filter(s=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=r.now();const s=new r.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:s.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}s.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,u=r.now(),d=o-t,c=u-i;this.addRawSpeed(d,c,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let s=0,n=r.now(),o=0,u=r.now();const d=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},c=async({done:h,value:l})=>{if(h)!t&&this.addRawSpeed(s,r.now()-n,1),this.concurrentDownloads.delete(e);else if(l){if(t){if(r.now()-u<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=l.byteLength;else{const p=u-n;p&&this.addRawSpeed(o,p,1,t),o=l.byteLength,n=r.now()}u=r.now()}else s+=l.byteLength,o+=l.byteLength,o>=this.tuningConfig.streamMinSampleSize&&r.now()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,r.now()-u,this.concurrentDownloads.size),o=0,u=r.now());await i?.read().then(c,d)}};this.concurrentDownloads.add(e),i?.read().then(c,d)}addRawSpeed(e,t,i=1,s=!1){if(Gt.sanityCheck(e,t,s)){const n=e*8/t;this.throughput.next(n*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=r.safeStorage.get(e);if(r.isNonNullable(t))return parseInt(t,10)??void 0}}const ns={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ut.VP9,androidPreferredFormat:at.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Xn=a=>({...r.fillWithDefault(a,ns),configName:[...a.configName??[],...ns.configName]});var os=({seekState:a,position$:e})=>r.merge(a.stateChangeEnded$.pipe(r.map(({to:t})=>t.state===V.None?void 0:(t.position??NaN)/1e3),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>a.getState().state===V.None))),Kn=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return r.assertNonNullable(e,`Wrong container or containerId {${a.container}}`),e};const Zn=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(r.filter(s=>s.length>0),r.once()).subscribe(s=>{s.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class eo{subscription=new r.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new r.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;desiredState={playbackState:new q(exports.PlaybackState.STOPPED),seekState:new q({state:V.None}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)};events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject};experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:ca};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=Xn(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ys({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Gt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,s)=>{const n=Reflect.get(t,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(u){const d=o.map(l=>JSON.stringify(l,(f,p)=>{const g=typeof p;return["number","string","boolean"].includes(g)?p:p===null?null:`<${g}>`})),c=`Player.${String(i)}`,h=`Exception calling ${c} (${d.join(", ")})`;throw this.events.fatalError$.next({id:c,category:r.ErrorCategory.WTF,message:h,thrown:u}),u}}}})}initVideo(e){return this.config=e,this.domContainer=Kn(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Qn({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?r.fromEvent(document,"visibilitychange").pipe(r.once()).subscribe(e):e(),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){const i=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=i&&!s&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:V.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){r.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 Zn(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const s=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+n.x,y:s.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===V.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){const e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:s})=>i||s||0,0),height:e.reduce((i,{height:s})=>i||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.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.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===V.Requested?this.desiredState.seekState.setState({...o,state:V.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===V.Applying&&(this.desiredState.seekState.setState({state:V.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:u})=>u).sort((u,d)=>r.isInvariantQuality(u)?1:r.isInvariantQuality(d)?-1:r.isHigher(d,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const u={};for(const d of o)d.fps&&(u[d.quality]=d.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o?.quality),this.info.videoBitrate$.next(o?.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.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.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o??{})})).add(e.providerOutput.currentBuffer$.pipe(r.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:u,isLowLatency:d})=>{const c=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(u)<c/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:u,duration:d})=>o&&(Math.abs(d)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(os({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.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(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o??r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let s=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return o&&!u}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.size?.width,height:o?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),c=this.chromecastInitializer.castState$.getValue();let h;c===exports.ChromecastState.CONNECTED?h=exports.Surface.SECOND_SCREEN:d?o?h=exports.Surface.PIP:u?h=exports.Surface.FULLSCREEN:h=exports.Surface.INLINE:h=exports.Surface.NONE,this.info.surface$.getValue()!==h&&this.info.surface$.next(h)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,s)=>i.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Tt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.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;r.assertNonNullable(this.providerContainer),r.assertNonNullable(e),ua(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>oa(t)),this.providerContainer.current$.subscribe(({type:t})=>Kt("provider",t)),e.duration$.subscribe(t=>Kt("duration",t)),e.availableVideoTracks$.pipe(r.filter(t=>!!t.length),r.once()).subscribe(t=>Kt("tracks",t)),this.events.fatalError$.subscribe(new Ge("fatalError")),this.events.managedError$.subscribe(new Ge("managedError")),e.position$.subscribe(new Ge("position")),e.currentVideoTrack$.pipe(r.map(t=>t?.quality)).subscribe(new Ge("quality")),this.info.currentBuffer$.subscribe(new Ge("buffer")),e.isBuffering$.subscribe(new Ge("isBuffering"))].forEach(t=>this.subscription.add(t)),Kt("codecs",Hn())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(s)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;s&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(s=>s.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const to=`@vkontakte/videoplayer-core@${us}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=eo;exports.SDK_VERSION=to;exports.VERSION=us;
|