@vkontakte/videoplayer-core 2.0.103 → 2.0.104
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 +73 -27
- package/es2015.esm.js +72 -26
- package/es2018.cjs.js +73 -27
- package/es2018.esm.js +72 -26
- package/esnext.cjs.js +75 -29
- package/esnext.esm.js +73 -27
- package/evergreen.esm.js +73 -27
- package/package.json +7 -7
- package/types/enums/AndroidPreferredFormat.d.ts +8 -0
- package/types/enums/WebmCodecStrategy.d.ts +7 -0
- package/types/env.d.ts +1 -0
- package/types/index.d.ts +12 -0
- package/types/player/Player.d.ts +173 -0
- package/{index.d.ts → types/player/types.d.ts} +64 -391
- package/types/player/utils/optimisticPosition.d.ts +12 -0
- package/types/player/utils/selectContainer.d.ts +3 -0
- package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +31 -0
- package/types/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +23 -0
- package/types/providers/ChromecastProvider/index.d.ts +33 -0
- package/types/providers/DashLiveProvider/DashLiveProvider.d.ts +37 -0
- package/types/providers/DashLiveProvider/index.d.ts +2 -0
- package/types/providers/DashLiveProvider/types.d.ts +21 -0
- package/types/providers/DashLiveProvider/utils/FilesFetcher.d.ts +25 -0
- package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +143 -0
- package/types/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +33 -0
- package/types/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +42 -0
- package/types/providers/DashProvider/baseDashProvider.d.ts +52 -0
- package/types/providers/DashProvider/consts.d.ts +1 -0
- package/types/providers/DashProvider/dashCmafLiveProvider.d.ts +8 -0
- package/types/providers/DashProvider/dashProvider.d.ts +6 -0
- package/types/providers/DashProvider/index.d.ts +2 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +103 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +51 -0
- package/types/providers/DashProvider/lib/parsers/mpd.d.ts +3 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxModel.d.ts +20 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxParser.d.ts +21 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/BoxTypeEnum.d.ts +26 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/box.d.ts +79 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/equi.d.ts +21 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/ftyp.d.ts +17 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/index.d.ts +22 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdat.d.ts +15 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mdia.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/mfhd.d.ts +11 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/minf.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moof.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/moov.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/prhd.d.ts +16 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/proj.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sidx.d.ts +48 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/st3d.d.ts +23 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/sv3d.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tfdt.d.ts +17 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tfhd.d.ts +22 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/tkhd.d.ts +42 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/traf.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trak.d.ts +7 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/trun.d.ts +31 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/unknown.d.ts +6 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +6 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/fullBox.d.ts +15 -0
- package/types/providers/DashProvider/lib/parsers/mpeg/isobmff.d.ts +12 -0
- package/types/providers/DashProvider/lib/parsers/webm/ebml.d.ts +76 -0
- package/types/providers/DashProvider/lib/parsers/webm/webm.d.ts +3 -0
- package/types/providers/DashProvider/lib/player.d.ts +75 -0
- package/types/providers/DashProvider/lib/sourceBufferTaskQueue.d.ts +18 -0
- package/types/providers/DashProvider/lib/types.d.ts +156 -0
- package/types/providers/DashProvider/lib/utils.d.ts +14 -0
- package/types/providers/HlsJsProvider/index.d.ts +24 -0
- package/types/providers/HlsLiveProvider/index.d.ts +30 -0
- package/types/providers/HlsLiveProvider/seekBackTimeExtractor.d.ts +3 -0
- package/types/providers/HlsProvider/index.d.ts +21 -0
- package/types/providers/HlsProvider/manifestDataExtractor.d.ts +21 -0
- package/types/providers/MpegProvider/index.d.ts +20 -0
- package/types/providers/ProviderContainer/index.d.ts +42 -0
- package/types/providers/ProviderContainer/types.d.ts +20 -0
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +20 -0
- package/types/providers/ProviderContainer/utils/playbackHangup.d.ts +12 -0
- package/types/providers/WebRTCLiveProvider/WebRTCLiveClient.d.ts +188 -0
- package/types/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +60 -0
- package/types/providers/WebRTCLiveProvider/interface/WebRTCLiveClientOptions.d.ts +9 -0
- package/types/providers/types.d.ts +83 -0
- package/types/providers/utils/HTMLVideoElement/DroppedFramesManager.d.ts +44 -0
- package/types/providers/utils/HTMLVideoElement/TextTrackManager.d.ts +30 -0
- package/types/providers/utils/HTMLVideoElement/clear.d.ts +1 -0
- package/types/providers/utils/HTMLVideoElement/destroy.d.ts +1 -0
- package/types/providers/utils/HTMLVideoElement/forcePlay.d.ts +7 -0
- package/types/providers/utils/HTMLVideoElement/observable.d.ts +25 -0
- package/types/providers/utils/HTMLVideoElement/pool.d.ts +2 -0
- package/types/providers/utils/HTMLVideoElement/surface.d.ts +2 -0
- package/types/providers/utils/LiveOffset/index.d.ts +14 -0
- package/types/providers/utils/LiveOffset/types.d.ts +10 -0
- package/types/providers/utils/addQuicParam.d.ts +2 -0
- package/types/providers/utils/extractConnectionHeaders.d.ts +6 -0
- package/types/providers/utils/generateLiveUrl.d.ts +9 -0
- package/types/providers/utils/okQualityStringToVideoQuality.d.ts +3 -0
- package/types/providers/utils/parseFps.d.ts +1 -0
- package/types/providers/utils/syncDesiredState.d.ts +12 -0
- package/types/providers/utils/syncPlaybackState.d.ts +4 -0
- package/types/utils/3d/Camera3D.d.ts +14 -0
- package/types/utils/3d/CameraRotationManager.d.ts +62 -0
- package/types/utils/3d/Scene3D.d.ts +132 -0
- package/types/utils/3d/types.d.ts +25 -0
- package/types/utils/StateMachine/StateMachine.d.ts +19 -0
- package/types/utils/StateMachine/types.d.ts +60 -0
- package/types/utils/StatefulIterator/index.d.ts +13 -0
- package/types/utils/ThroughputEstimator.d.ts +25 -0
- package/types/utils/addScript.d.ts +2 -0
- package/types/utils/autoSelectVideoTrack.d.ts +26 -0
- package/types/utils/buffer/getBufferedRangeForPosition.d.ts +3 -0
- package/types/utils/buffer/getForwardBufferDuration.d.ts +3 -0
- package/types/utils/buffer/getTotalBufferDuration.d.ts +3 -0
- package/types/utils/buffer/isPositionBuffered.d.ts +3 -0
- package/types/utils/changePlaybackRate.d.ts +2 -0
- package/types/utils/hostnameFromUrl.d.ts +2 -0
- package/types/utils/isInPiP.d.ts +1 -0
- package/types/utils/link.d.ts +2 -0
- package/types/utils/mediaSource.d.ts +8 -0
- package/types/utils/observeElementVisibility.d.ts +3 -0
- package/types/utils/playbackTelemetry.d.ts +12 -0
- package/types/utils/setStateWithSubscribe.d.ts +3 -0
- package/types/utils/smoothedValue/baseSmoothedValue.d.ts +18 -0
- package/types/utils/smoothedValue/emaAndMaSmoothedValue.d.ts +7 -0
- package/types/utils/smoothedValue/emaTopExtremumValue.d.ts +10 -0
- package/types/utils/smoothedValue/smoothedValueFactory.d.ts +6 -0
- package/types/utils/smoothedValue/twoEmaSmoothedValue.d.ts +8 -0
- package/types/utils/smoothedValue/types.d.ts +26 -0
- package/types/utils/smoothedValue/utils.d.ts +3 -0
- package/types/utils/tuningConfig.d.ts +164 -0
- package/types/utils/videoFormat.d.ts +2 -0
package/esnext.cjs.js
CHANGED
|
@@ -1,46 +1,92 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.104
|
|
3
|
+
* Mon, 24 Jun 2024 13:01:09 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-104/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Wi=Object.create;var Zt=Object.defineProperty;var Qi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Xi=Object.getPrototypeOf,Ki=Object.prototype.hasOwnProperty;var Zi=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ji(e))!Ki.call(a,r)&&r!==t&&Zt(a,r,{get:()=>e[r],enumerable:!(i=Qi(e,r))||i.enumerable});return a};var es=(a,e,t)=>(t=a!=null?Wi(Xi(a)):{},Zi(e||!a||!a.__esModule?Zt(t,"default",{value:a,enumerable:!0}):t,a));var s=require("@vkontakte/videoplayer-shared/esnext.cjs.js");const wi="2.0.103";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_SEP",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 ee;(function(a){a.SCREEN="SCREEN",a.CHROMECAST="CHROMECAST"})(ee||(ee={}));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 I;(function(a){a.None="none",a.Requested="requested",a.Applying="applying"})(I||(I={}));exports.Surface=void 0;(function(a){a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible"})(exports.Surface||(exports.Surface={}));var ts=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 is{connection$=new s.ValueSubject(void 0);castState$=new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);errorEvent$=new s.Subject;contentId;realCastState$=new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE);subscription=new s.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=s.isNonNullable(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||ts("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:s.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(){s.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();s.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();s.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(s.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.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 s.assertNever(r.sessionState)}})).add(s.merge(s.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(s.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),s.map(r=>r.castState)),s.observableFrom([i.getCastState()])).pipe(s.filterChanged(),s.map(ss),s.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{const n=r===exports.ChromecastState.CONNECTED,o=s.isNonNullable(this.connection$.getValue());if(n&&!o){const c=i.getCurrentSession();s.assertNonNullable(c);const l=c.getCastDevice(),u=c.getMediaSession()?.media.contentId;(s.isNullable(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?s.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}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(r){this.errorEvent$.next({id:"ChromecastInitializer",category:s.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}}const ss=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 s.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:s.assertNever(t)}return a};const ei=(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:s.assertNever(e)}};var A=(a,e,t=!1)=>{const i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};class z{state;prevState;transition;transitionStarted$=new s.Subject;transitionEnded$=new s.Subject;transitionUpdated$=new s.Subject;forceChanged$=new s.Subject;stateChangeStarted$=s.merge(this.transitionStarted$,this.transitionUpdated$);stateChangeEnded$=s.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||s.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 as=a=>{switch(a){case exports.VideoFormat.MPEG: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 s.assertNever(a)}};var D;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(D||(D={}));const rs=5,ns=5,os=500,ti=7e3;class cs{subscription=new s.Subscription;loadMediaTimeoutSubscription=new s.Subscription;videoState=new z(D.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(as(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 s.Subscription;this.subscription.add(e),this.subscription.add(s.merge(this.videoState.stateChangeStarted$.pipe(s.map(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(s.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new s.Subject;e.add(r.pipe(s.debounce(os)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const c=o.value;this.params.output.position$.next(c),(this.params.desiredState.seekState.getState().state===I.Applying||Math.abs(c-n)>rs)&&r.next(c),n=c})),e.add(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.value,c=this.params.output.isBuffering$.getValue(),l=o===chrome.cast.media.PlayerState.BUFFERING;switch(c!==l&&this.params.output.isBuffering$.next(l),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<ns&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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:s.assertNever(o)}}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(s.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=s.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.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(D.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(D.PLAYING),A(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:I.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===D.PAUSED||e===D.PLAYING)&&(this.videoState.setState(D.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState();(this.videoState.getTransition()?.to===D.PLAYING||e===D.PAUSED)&&(this.videoState.setState(D.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){this.videoState.getTransition()?.to===D.READY&&this.videoState.setState(D.READY),this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==D.STOPPED&&this.videoState.setState(D.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,r,n;switch(e){case exports.VideoFormat.MPEG:{const u=t[e];s.assertNonNullable(u);const d=s.getHighestQuality(Object.keys(u));s.assertNonNullable(d);const h=u[d];s.assertNonNullable(h),i=h,r="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const u=t[e];s.assertNonNullable(u),i=u.url,r="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 u=t[e];s.assertNonNullable(u),i=u.url,r="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const u=t[e];s.assertNonNullable(u),i=u.url,r="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const u=t[e];s.assertNonNullable(u),i=Se(u.url),r="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const u="Unsupported format for Chromecast",d=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:s.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:d}),d}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return s.assertNever(e)}const o=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);o.contentUrl=i,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:l}=this.params.meta;return s.isNonNullable(c)&&(o.metadata.title=c),s.isNonNullable(l)&&(o.metadata.subtitle=l),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===I.Applying||i.state===I.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((r,n)=>{this.loadMediaTimeoutSubscription.add(s.timeout(ti).subscribe(()=>n(`timeout(${ti})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===I.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:s.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}).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(),r=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!==D.STOPPED&&(this.videoState.startTransitionTo(D.STOPPED),this.stop());return}if(!t){if(r?.to!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&e!==D.STOPPED){this.seek(n.position/1e3);return}switch(i){case exports.PlaybackState.READY:{switch(e){case D.PLAYING:case D.PAUSED:case D.READY:break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PLAYING:{switch(e){case D.PLAYING:break;case D.PAUSED:this.videoState.startTransitionTo(D.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case D.READY:this.videoState.startTransitionTo(D.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}case exports.PlaybackState.PAUSED:{switch(e){case D.PLAYING:this.videoState.startTransitionTo(D.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case D.PAUSED:break;case D.READY:this.videoState.startTransitionTo(D.PAUSED),this.videoState.setState(D.PAUSED);break;case D.STOPPED:this.videoState.startTransitionTo(D.READY),this.prepare();break;default:s.assertNever(e)}break}default:s.assertNever(i)}}}}const qt=a=>{a.removeAttribute("src"),a.load()},us=a=>{try{a.pause(),a.playbackRate=0,qt(a),a.remove()}catch(e){console.error(e)}};class ls{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 Ot=window.WeakMap?new WeakMap:new ls,Ue=a=>{let e=a.querySelector("video");const t=!!e;return e?qt(e):(e=document.createElement("video"),a.appendChild(e)),Ot.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},He=a=>{const e=Ot.get(a);Ot.delete(a),e?qt(a):us(a)},we=(a,e,t,{equal:i=(o,c)=>o===c,changed$:r,onError:n}={})=>{const o=a.getState(),c=e(),l=s.isNullable(r),u=new s.Subscription;return r&&u.add(r.subscribe(d=>{const h=a.getState();i(d,h)&&a.setState(d)},n)),i(c,o)||(t(o),l&&a.setState(o)),u.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),l&&a.setState(d.to)},n)),u},pt=(a,e,t)=>we(e,()=>a.loop,i=>{s.isNonNullable(i)&&(a.loop=i)},{onError:t}),je=(a,e,t,i)=>we(e,()=>({muted:a.muted,volume:a.volume}),r=>{s.isNonNullable(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,n)=>r===n||r?.muted===n?.muted&&r?.volume===n?.volume,changed$:t,onError:i}),it=(a,e,t,i)=>we(e,()=>a.playbackRate,r=>{s.isNonNullable(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ds=a=>["__",a.language,a.label].join("|"),hs=(a,e)=>{if(a.id===e)return!0;const[t,i,r]=e.split("|");return a.language===i&&a.label===r};class Ne{available$=new s.Subject;current$=new s.ValueSubject(void 0);error$=new s.Subject;video;cueSettings;subscription=new s.Subscription;externalTracks=new Map;internalTracks=new Map;connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:s.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(we(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{s.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>s.isNonNullable(n)&&s.isNonNullable(o)&&n.length===o.length&&n.every(({id:c},l)=>c===o[l].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="internal"))),onError:r})),this.subscription.add(we(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{s.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>s.isNonNullable(n)&&s.isNonNullable(o)&&n.length===o.length&&n.every(({id:c},l)=>c===o[l].id),changed$:this.available$.pipe(s.map(n=>n.filter(({type:o})=>o==="external"))),onError:r})),this.subscription.add(we(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:r})),this.subscription.add(we(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){s.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(s.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(s.merge(s.fromEvent(e,"addtrack"),s.fromEvent(e,"removetrack"),s.observableFrom(["init"])).pipe(s.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),s.filterChanged((i,r)=>i.length===r.length&&i.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(s.merge(s.fromEvent(e,"change"),s.observableFrom(["init"])).pipe(s.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),s.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),s.filterChanged()).subscribe(this.current$));const t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(s.fromEvent(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);const r=n=>{const o=n.target?.cues??null;o&&o.length&&(this.applyCueSettings(n.target?.cues??null),n.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(s.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 r=i;s.isNonNullable(t.align)&&(r.align=t.align),s.isNonNullable(t.position)&&(r.position=t.position),s.isNonNullable(t.size)&&(r.size=t.size),s.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){s.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ne.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id?e.id:ds(e),n=this.externalTracks.has(r),o=r.includes("auto");return n?{id:r,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(r)?.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:r,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){s.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(s.isNullable(e)||!hs(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){s.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){s.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)}}class zt{pausedTime=0;streamOffset=0;pauseTimestamp=0;getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const $i=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ii=a=>{const e=$i(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},fs=a=>{const e=$i(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)},ps=3;var ms=(a,e,t=ps)=>{let i=0,r=0;for(let n=0;n<a.length;n++){const o=a.start(n),c=a.end(n);if(o<=e&&e<=c){if(i=o,r=c,!t)return{from:i,to:r};for(let l=n-1;l>=0;l--)a.end(l)+t>=i&&(i=a.start(l));for(let l=n+1;l<a.length;l++)a.start(l)-t<=r&&(r=a.end(l))}}return{from:i,to:r}};const Ye=a=>{const e=P=>s.fromEvent(a,P).pipe(s.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=s.merge(...t.map(P=>s.fromEvent(a,P))).pipe(s.map(P=>P.type==="ended"?a.readyState<2:a.readyState<3),s.filterChanged()),r=s.merge(s.fromEvent(a,"progress"),s.fromEvent(a,"timeupdate")).pipe(s.map(()=>ms(a.buffered,a.currentTime))),o=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari?s.combine({play:e("play").pipe(s.once()),playing:e("playing")}).pipe(s.mapTo(void 0)):e("playing"),c=s.fromEvent(a,"volumechange").pipe(s.map(()=>({muted:a.muted,volume:a.volume}))),l=s.fromEvent(a,"ratechange").pipe(s.map(()=>a.playbackRate)),u=s.fromEvent(a,"error").pipe(s.filter(()=>!!(a.error||a.played.length)),s.map(()=>{const P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:s.ErrorCategory.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:a.error??void 0}})),d=s.fromEvent(a,"timeupdate").pipe(s.map(()=>a.currentTime)),h=new s.Subject,p=.3;let f;d.subscribe(P=>{a.loop&&s.isNonNullable(f)&&s.isNonNullable(P)&&f>=a.duration-p&&P<=p&&h.next(f),f=P});const m=s.fromEvent(a,"enterpictureinpicture"),T=s.fromEvent(a,"leavepictureinpicture"),b=new s.ValueSubject(fs(a));m.subscribe(()=>b.next(!0)),T.subscribe(()=>b.next(!1));const y=new s.ValueSubject(ii(a));return s.fromEvent(a,"fullscreenchange").pipe(s.map(()=>ii(a))).subscribe(y),{playing$:o,pause$:e("pause").pipe(s.filter(()=>!a.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:s.fromEvent(a,"durationchange").pipe(s.map(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:c,playbackRateState$:l,inPiP$:b,inFullscreen$:y}};var Ct=a=>{switch(a){case"mobile":return s.VideoQuality.Q_144P;case"lowest":return s.VideoQuality.Q_240P;case"low":return s.VideoQuality.Q_360P;case"sd":case"medium":return s.VideoQuality.Q_480P;case"hd":case"high":return s.VideoQuality.Q_720P;case"fullhd":case"full":return s.VideoQuality.Q_1080P;case"quadhd":case"quad":return s.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return s.VideoQuality.Q_2160P}};let Wt=!1,$e={};const Ss=a=>{Wt=a},bs=()=>{$e={}},gs=a=>{a($e)},vt=(a,e)=>{Wt&&($e.meta=$e.meta??{},$e.meta[a]=e)};class ve{name;constructor(e){this.name=e}next(e){if(!Wt)return;$e.series=$e.series??{};const t=$e.series[this.name]??[];t.push([Date.now(),e]),$e.series[this.name]=t}}var _e;(function(a){a.FitsContainer="FitsContainer",a.FitsThroughput="FitsThroughput",a.Buffer="Buffer",a.DroppedFramesLimit="DroppedFramesLimit",a.FitsQualityLimits="FitsQualityLimits"})(_e||(_e={}));const ys=new ve("best_bitrate"),vs=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;class Ts{last;history={};recordSelection(e){this.history[e.id]=s.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Es='Assertion "ABR Tracks is empty array" failed',Lt=(a,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:c,current:l,history:u,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{s.assertNotEmptyArray(a,Es);const p=i.usePixelRatio?window.devicePixelRatio??1:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},m=f&&s.videoSizeToQuality(f),T=i.considerPlaybackRate&&s.isNonNullable(c)?c:1,b=a.filter(k=>!s.isInvariantQuality(k.quality)).sort((k,w)=>s.isHigher(k.quality,w.quality)?-1:1),y=b.at(-1)?.quality,C=b.at(0)?.quality,P=s.isNullable(r)||s.isNonNullable(r.min)&&s.isNonNullable(r.max)&&s.isLower(r.max,r.min)||s.isNonNullable(r.min)&&C&&s.isHigher(r.min,C)||s.isNonNullable(r.max)&&y&&s.isLower(r.max,y),g=T*vs(o??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},B=b.filter(k=>(m?s.isLower(k.quality,m):!0)?(s.isNonNullable(t)&&isFinite(t)&&s.isNonNullable(k.bitrate)?t-n>=k.bitrate*g:!0)?i.lazyQualitySwitch&&s.isNonNullable(i.minBufferToSwitchUp)&&l&&!s.isInvariantQuality(l.quality)&&(o??0)<i.minBufferToSwitchUp&&s.isHigher(k.quality,l.quality)?(E[k.quality]=_e.Buffer,!1):!!d&&s.isHigherOrEqual(k.quality,d)?(E[k.quality]=_e.DroppedFramesLimit,!1):P||(s.isNullable(r.max)||s.isLowerOrEqual(k.quality,r.max))&&(s.isNullable(r.min)||s.isHigherOrEqual(k.quality,r.min))?!0:(E[k.quality]=_e.FitsQualityLimits,!1):(E[k.quality]=_e.FitsThroughput,!1):(E[k.quality]=_e.FitsContainer,!1))[0];B&&B.bitrate&&ys.next(B.bitrate);const x=B??b[Math.ceil((b.length-1)/2)]??a[0];x.quality!==u?.last?.quality&&h({message:`
|
|
6
|
+
"use strict";var rm=Object.create;var ji=Object.defineProperty;var im=Object.getOwnPropertyDescriptor;var am=Object.getOwnPropertyNames;var sm=Object.getPrototypeOf,nm=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),om=(i,e)=>{for(var t in e)ji(i,t,{get:e[t],enumerable:!0})},Lo=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of am(e))!nm.call(i,a)&&a!==t&&ji(i,a,{get:()=>e[a],enumerable:!(r=im(e,a))||r.enumerable});return i};var _e=(i,e,t)=>(t=i!=null?rm(sm(i)):{},Lo(e||!i||!i.__esModule?ji(t,"default",{value:i,enumerable:!0}):t,i)),um=i=>Lo(ji({},"__esModule",{value:!0}),i);var Pe=m((Px,Co)=>{"use strict";Co.exports=function(i){try{return!!i()}catch{return!0}}});var Pr=m((kx,Do)=>{"use strict";var cm=Pe();Do.exports=!cm(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var fe=m((wx,Bo)=>{"use strict";var Mo=Pr(),Oo=Function.prototype,cs=Oo.call,dm=Mo&&Oo.bind.bind(cs,cs);Bo.exports=Mo?dm:function(i){return function(){return cs.apply(i,arguments)}}});var Jt=m((Ax,_o)=>{"use strict";var Vo=fe(),pm=Vo({}.toString),hm=Vo("".slice);_o.exports=function(i){return hm(pm(i),8,-1)}});var Fo=m((Rx,No)=>{"use strict";var fm=fe(),mm=Pe(),bm=Jt(),ds=Object,gm=fm("".split);No.exports=mm(function(){return!ds("z").propertyIsEnumerable(0)})?function(i){return bm(i)=="String"?gm(i,""):ds(i)}:ds});var Xt=m((Lx,qo)=>{"use strict";qo.exports=function(i){return i==null}});var Qi=m(($x,Uo)=>{"use strict";var vm=Xt(),Sm=TypeError;Uo.exports=function(i){if(vm(i))throw Sm("Can't call method on "+i);return i}});var Zt=m((Cx,Ho)=>{"use strict";var ym=Fo(),Tm=Qi();Ho.exports=function(i){return ym(Tm(i))}});var ps=m((Dx,jo)=>{"use strict";jo.exports=function(){}});var Rt=m((Mx,Go)=>{"use strict";Go.exports={}});var ne=m((Yo,Wo)=>{"use strict";var zi=function(i){return i&&i.Math==Math&&i};Wo.exports=zi(typeof globalThis=="object"&&globalThis)||zi(typeof window=="object"&&window)||zi(typeof self=="object"&&self)||zi(typeof global=="object"&&global)||function(){return this}()||Yo||Function("return this")()});var fs=m((Ox,Qo)=>{"use strict";var hs=typeof document=="object"&&document.all,Im=typeof hs>"u"&&hs!==void 0;Qo.exports={all:hs,IS_HTMLDDA:Im}});var ee=m((Bx,Ko)=>{"use strict";var zo=fs(),Em=zo.all;Ko.exports=zo.IS_HTMLDDA?function(i){return typeof i=="function"||i===Em}:function(i){return typeof i=="function"}});var Zo=m((Vx,Xo)=>{"use strict";var xm=ne(),Pm=ee(),Jo=xm.WeakMap;Xo.exports=Pm(Jo)&&/native code/.test(String(Jo))});var Qe=m((_x,ru)=>{"use strict";var eu=ee(),tu=fs(),km=tu.all;ru.exports=tu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:eu(i)||i===km}:function(i){return typeof i=="object"?i!==null:eu(i)}});var ze=m((Nx,iu)=>{"use strict";var wm=Pe();iu.exports=!wm(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var Ki=m((Fx,su)=>{"use strict";var Am=ne(),au=Qe(),ms=Am.document,Rm=au(ms)&&au(ms.createElement);su.exports=function(i){return Rm?ms.createElement(i):{}}});var bs=m((qx,nu)=>{"use strict";var Lm=ze(),$m=Pe(),Cm=Ki();nu.exports=!Lm&&!$m(function(){return Object.defineProperty(Cm("div"),"a",{get:function(){return 7}}).a!=7})});var gs=m((Ux,ou)=>{"use strict";var Dm=ze(),Mm=Pe();ou.exports=Dm&&Mm(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Ne=m((Hx,uu)=>{"use strict";var Om=Qe(),Bm=String,Vm=TypeError;uu.exports=function(i){if(Om(i))return i;throw Vm(Bm(i)+" is not an object")}});var me=m((jx,lu)=>{"use strict";var _m=Pr(),Ji=Function.prototype.call;lu.exports=_m?Ji.bind(Ji):function(){return Ji.apply(Ji,arguments)}});var Xi=m((Gx,cu)=>{"use strict";cu.exports={}});var rt=m((Yx,pu)=>{"use strict";var vs=Xi(),Ss=ne(),Nm=ee(),du=function(i){return Nm(i)?i:void 0};pu.exports=function(i,e){return arguments.length<2?du(vs[i])||du(Ss[i]):vs[i]&&vs[i][e]||Ss[i]&&Ss[i][e]}});var kr=m((Wx,hu)=>{"use strict";var Fm=fe();hu.exports=Fm({}.isPrototypeOf)});var wr=m((Qx,fu)=>{"use strict";fu.exports=typeof navigator<"u"&&String(navigator.userAgent)||""});var Ts=m((zx,yu)=>{"use strict";var Su=ne(),ys=wr(),mu=Su.process,bu=Su.Deno,gu=mu&&mu.versions||bu&&bu.version,vu=gu&&gu.v8,Fe,Zi;vu&&(Fe=vu.split("."),Zi=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!Zi&&ys&&(Fe=ys.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=ys.match(/Chrome\/(\d+)/),Fe&&(Zi=+Fe[1])));yu.exports=Zi});var Is=m((Kx,Iu)=>{"use strict";var Tu=Ts(),qm=Pe(),Um=ne(),Hm=Um.String;Iu.exports=!!Object.getOwnPropertySymbols&&!qm(function(){var i=Symbol();return!Hm(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Tu&&Tu<41})});var Es=m((Jx,Eu)=>{"use strict";var jm=Is();Eu.exports=jm&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var xs=m((Xx,xu)=>{"use strict";var Gm=rt(),Ym=ee(),Wm=kr(),Qm=Es(),zm=Object;xu.exports=Qm?function(i){return typeof i=="symbol"}:function(i){var e=Gm("Symbol");return Ym(e)&&Wm(e.prototype,zm(i))}});var Ar=m((Zx,Pu)=>{"use strict";var Km=String;Pu.exports=function(i){try{return Km(i)}catch{return"Object"}}});var it=m((eP,ku)=>{"use strict";var Jm=ee(),Xm=Ar(),Zm=TypeError;ku.exports=function(i){if(Jm(i))return i;throw Zm(Xm(i)+" is not a function")}});var Rr=m((tP,wu)=>{"use strict";var eb=it(),tb=Xt();wu.exports=function(i,e){var t=i[e];return tb(t)?void 0:eb(t)}});var Ru=m((rP,Au)=>{"use strict";var Ps=me(),ks=ee(),ws=Qe(),rb=TypeError;Au.exports=function(i,e){var t,r;if(e==="string"&&ks(t=i.toString)&&!ws(r=Ps(t,i))||ks(t=i.valueOf)&&!ws(r=Ps(t,i))||e!=="string"&&ks(t=i.toString)&&!ws(r=Ps(t,i)))return r;throw rb("Can't convert object to primitive value")}});var qe=m((iP,Lu)=>{"use strict";Lu.exports=!0});var Du=m((aP,Cu)=>{"use strict";var $u=ne(),ib=Object.defineProperty;Cu.exports=function(i,e){try{ib($u,i,{value:e,configurable:!0,writable:!0})}catch{$u[i]=e}return e}});var ea=m((sP,Ou)=>{"use strict";var ab=ne(),sb=Du(),Mu="__core-js_shared__",nb=ab[Mu]||sb(Mu,{});Ou.exports=nb});var As=m((nP,Vu)=>{"use strict";var ob=qe(),Bu=ea();(Vu.exports=function(i,e){return Bu[i]||(Bu[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:ob?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Lr=m((oP,_u)=>{"use strict";var ub=Qi(),lb=Object;_u.exports=function(i){return lb(ub(i))}});var Ue=m((uP,Nu)=>{"use strict";var cb=fe(),db=Lr(),pb=cb({}.hasOwnProperty);Nu.exports=Object.hasOwn||function(e,t){return pb(db(e),t)}});var Rs=m((lP,Fu)=>{"use strict";var hb=fe(),fb=0,mb=Math.random(),bb=hb(1 .toString);Fu.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+bb(++fb+mb,36)}});var ce=m((cP,Uu)=>{"use strict";var gb=ne(),vb=As(),qu=Ue(),Sb=Rs(),yb=Is(),Tb=Es(),er=gb.Symbol,Ls=vb("wks"),Ib=Tb?er.for||er:er&&er.withoutSetter||Sb;Uu.exports=function(i){return qu(Ls,i)||(Ls[i]=yb&&qu(er,i)?er[i]:Ib("Symbol."+i)),Ls[i]}});var Yu=m((dP,Gu)=>{"use strict";var Eb=me(),Hu=Qe(),ju=xs(),xb=Rr(),Pb=Ru(),kb=ce(),wb=TypeError,Ab=kb("toPrimitive");Gu.exports=function(i,e){if(!Hu(i)||ju(i))return i;var t=xb(i,Ab),r;if(t){if(e===void 0&&(e="default"),r=Eb(t,i,e),!Hu(r)||ju(r))return r;throw wb("Can't convert object to primitive value")}return e===void 0&&(e="number"),Pb(i,e)}});var ta=m((pP,Wu)=>{"use strict";var Rb=Yu(),Lb=xs();Wu.exports=function(i){var e=Rb(i,"string");return Lb(e)?e:e+""}});var Lt=m(zu=>{"use strict";var $b=ze(),Cb=bs(),Db=gs(),ra=Ne(),Qu=ta(),Mb=TypeError,$s=Object.defineProperty,Ob=Object.getOwnPropertyDescriptor,Cs="enumerable",Ds="configurable",Ms="writable";zu.f=$b?Db?function(e,t,r){if(ra(e),t=Qu(t),ra(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Ms in r&&!r[Ms]){var a=Ob(e,t);a&&a[Ms]&&(e[t]=r.value,r={configurable:Ds in r?r[Ds]:a[Ds],enumerable:Cs in r?r[Cs]:a[Cs],writable:!1})}return $s(e,t,r)}:$s:function(e,t,r){if(ra(e),t=Qu(t),ra(r),Cb)try{return $s(e,t,r)}catch{}if("get"in r||"set"in r)throw Mb("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var $r=m((fP,Ku)=>{"use strict";Ku.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var $t=m((mP,Ju)=>{"use strict";var Bb=ze(),Vb=Lt(),_b=$r();Ju.exports=Bb?function(i,e,t){return Vb.f(i,e,_b(1,t))}:function(i,e,t){return i[e]=t,i}});var ia=m((bP,Zu)=>{"use strict";var Nb=As(),Fb=Rs(),Xu=Nb("keys");Zu.exports=function(i){return Xu[i]||(Xu[i]=Fb(i))}});var aa=m((gP,el)=>{"use strict";el.exports={}});var _s=m((vP,il)=>{"use strict";var qb=Zo(),rl=ne(),Ub=Qe(),Hb=$t(),Os=Ue(),Bs=ea(),jb=ia(),Gb=aa(),tl="Object already initialized",Vs=rl.TypeError,Yb=rl.WeakMap,sa,Cr,na,Wb=function(i){return na(i)?Cr(i):sa(i,{})},Qb=function(i){return function(e){var t;if(!Ub(e)||(t=Cr(e)).type!==i)throw Vs("Incompatible receiver, "+i+" required");return t}};qb||Bs.state?(He=Bs.state||(Bs.state=new Yb),He.get=He.get,He.has=He.has,He.set=He.set,sa=function(i,e){if(He.has(i))throw Vs(tl);return e.facade=i,He.set(i,e),e},Cr=function(i){return He.get(i)||{}},na=function(i){return He.has(i)}):(Ct=jb("state"),Gb[Ct]=!0,sa=function(i,e){if(Os(i,Ct))throw Vs(tl);return e.facade=i,Hb(i,Ct,e),e},Cr=function(i){return Os(i,Ct)?i[Ct]:{}},na=function(i){return Os(i,Ct)});var He,Ct;il.exports={set:sa,get:Cr,has:na,enforce:Wb,getterFor:Qb}});var Ns=m((SP,ol)=>{"use strict";var zb=Pr(),nl=Function.prototype,al=nl.apply,sl=nl.call;ol.exports=typeof Reflect=="object"&&Reflect.apply||(zb?sl.bind(al):function(){return sl.apply(al,arguments)})});var Fs=m((yP,ul)=>{"use strict";var Kb=Jt(),Jb=fe();ul.exports=function(i){if(Kb(i)==="Function")return Jb(i)}});var pl=m(dl=>{"use strict";var ll={}.propertyIsEnumerable,cl=Object.getOwnPropertyDescriptor,Xb=cl&&!ll.call({1:2},1);dl.f=Xb?function(e){var t=cl(this,e);return!!t&&t.enumerable}:ll});var qs=m(fl=>{"use strict";var Zb=ze(),eg=me(),tg=pl(),rg=$r(),ig=Zt(),ag=ta(),sg=Ue(),ng=bs(),hl=Object.getOwnPropertyDescriptor;fl.f=Zb?hl:function(e,t){if(e=ig(e),t=ag(t),ng)try{return hl(e,t)}catch{}if(sg(e,t))return rg(!eg(tg.f,e,t),e[t])}});var Us=m((EP,ml)=>{"use strict";var og=Pe(),ug=ee(),lg=/#|\.prototype\./,Dr=function(i,e){var t=dg[cg(i)];return t==hg?!0:t==pg?!1:ug(e)?og(e):!!e},cg=Dr.normalize=function(i){return String(i).replace(lg,".").toLowerCase()},dg=Dr.data={},pg=Dr.NATIVE="N",hg=Dr.POLYFILL="P";ml.exports=Dr});var Mr=m((xP,gl)=>{"use strict";var bl=Fs(),fg=it(),mg=Pr(),bg=bl(bl.bind);gl.exports=function(i,e){return fg(i),e===void 0?i:mg?bg(i,e):function(){return i.apply(e,arguments)}}});var Ae=m((PP,Sl)=>{"use strict";var oa=ne(),gg=Ns(),vg=Fs(),Sg=ee(),yg=qs().f,Tg=Us(),tr=Xi(),Ig=Mr(),rr=$t(),vl=Ue(),Eg=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return gg(i,this,arguments)};return e.prototype=i.prototype,e};Sl.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?oa:a?oa[t]:(oa[t]||{}).prototype,o=r?tr:tr[t]||rr(tr,t,{})[t],l=o.prototype,u,c,d,f,h,b,I,g,T;for(f in e)u=Tg(r?f:t+(a?".":"#")+f,i.forced),c=!u&&n&&vl(n,f),b=o[f],c&&(i.dontCallGetSet?(T=yg(n,f),I=T&&T.value):I=n[f]),h=c&&I?I:e[f],!(c&&typeof b==typeof h)&&(i.bind&&c?g=Ig(h,oa):i.wrap&&c?g=Eg(h):s&&Sg(h)?g=vg(h):g=h,(i.sham||h&&h.sham||b&&b.sham)&&rr(g,"sham",!0),rr(o,f,g),s&&(d=t+"Prototype",vl(tr,d)||rr(tr,d,{}),rr(tr[d],f,h),i.real&&l&&(u||!l[f])&&rr(l,f,h)))}});var Il=m((kP,Tl)=>{"use strict";var Hs=ze(),xg=Ue(),yl=Function.prototype,Pg=Hs&&Object.getOwnPropertyDescriptor,js=xg(yl,"name"),kg=js&&function(){}.name==="something",wg=js&&(!Hs||Hs&&Pg(yl,"name").configurable);Tl.exports={EXISTS:js,PROPER:kg,CONFIGURABLE:wg}});var xl=m((wP,El)=>{"use strict";var Ag=Math.ceil,Rg=Math.floor;El.exports=Math.trunc||function(e){var t=+e;return(t>0?Rg:Ag)(t)}});var ua=m((AP,Pl)=>{"use strict";var Lg=xl();Pl.exports=function(i){var e=+i;return e!==e||e===0?0:Lg(e)}});var wl=m((RP,kl)=>{"use strict";var $g=ua(),Cg=Math.max,Dg=Math.min;kl.exports=function(i,e){var t=$g(i);return t<0?Cg(t+e,0):Dg(t,e)}});var Rl=m((LP,Al)=>{"use strict";var Mg=ua(),Og=Math.min;Al.exports=function(i){return i>0?Og(Mg(i),9007199254740991):0}});var la=m(($P,Ll)=>{"use strict";var Bg=Rl();Ll.exports=function(i){return Bg(i.length)}});var Dl=m((CP,Cl)=>{"use strict";var Vg=Zt(),_g=wl(),Ng=la(),$l=function(i){return function(e,t,r){var a=Vg(e),s=Ng(a),n=_g(r,s),o;if(i&&t!=t){for(;s>n;)if(o=a[n++],o!=o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Cl.exports={includes:$l(!0),indexOf:$l(!1)}});var Bl=m((DP,Ol)=>{"use strict";var Fg=fe(),Gs=Ue(),qg=Zt(),Ug=Dl().indexOf,Hg=aa(),Ml=Fg([].push);Ol.exports=function(i,e){var t=qg(i),r=0,a=[],s;for(s in t)!Gs(Hg,s)&&Gs(t,s)&&Ml(a,s);for(;e.length>r;)Gs(t,s=e[r++])&&(~Ug(a,s)||Ml(a,s));return a}});var Ys=m((MP,Vl)=>{"use strict";Vl.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Nl=m((OP,_l)=>{"use strict";var jg=Bl(),Gg=Ys();_l.exports=Object.keys||function(e){return jg(e,Gg)}});var ql=m(Fl=>{"use strict";var Yg=ze(),Wg=gs(),Qg=Lt(),zg=Ne(),Kg=Zt(),Jg=Nl();Fl.f=Yg&&!Wg?Object.defineProperties:function(e,t){zg(e);for(var r=Kg(t),a=Jg(t),s=a.length,n=0,o;s>n;)Qg.f(e,o=a[n++],r[o]);return e}});var Ws=m((VP,Ul)=>{"use strict";var Xg=rt();Ul.exports=Xg("document","documentElement")});var Js=m((_P,zl)=>{"use strict";var Zg=Ne(),ev=ql(),Hl=Ys(),tv=aa(),rv=Ws(),iv=Ki(),av=ia(),jl=">",Gl="<",zs="prototype",Ks="script",Wl=av("IE_PROTO"),Qs=function(){},Ql=function(i){return Gl+Ks+jl+i+Gl+"/"+Ks+jl},Yl=function(i){i.write(Ql("")),i.close();var e=i.parentWindow.Object;return i=null,e},sv=function(){var i=iv("iframe"),e="java"+Ks+":",t;return i.style.display="none",rv.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Ql("document.F=Object")),t.close(),t.F},ca,da=function(){try{ca=new ActiveXObject("htmlfile")}catch{}da=typeof document<"u"?document.domain&&ca?Yl(ca):sv():Yl(ca);for(var i=Hl.length;i--;)delete da[zs][Hl[i]];return da()};tv[Wl]=!0;zl.exports=Object.create||function(e,t){var r;return e!==null?(Qs[zs]=Zg(e),r=new Qs,Qs[zs]=null,r[Wl]=e):r=da(),t===void 0?r:ev.f(r,t)}});var Jl=m((NP,Kl)=>{"use strict";var nv=Pe();Kl.exports=!nv(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Zs=m((FP,Zl)=>{"use strict";var ov=Ue(),uv=ee(),lv=Lr(),cv=ia(),dv=Jl(),Xl=cv("IE_PROTO"),Xs=Object,pv=Xs.prototype;Zl.exports=dv?Xs.getPrototypeOf:function(i){var e=lv(i);if(ov(e,Xl))return e[Xl];var t=e.constructor;return uv(t)&&e instanceof t?t.prototype:e instanceof Xs?pv:null}});var ir=m((qP,ec)=>{"use strict";var hv=$t();ec.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:hv(i,e,t),i}});var an=m((UP,ic)=>{"use strict";var fv=Pe(),mv=ee(),bv=Qe(),gv=Js(),tc=Zs(),vv=ir(),Sv=ce(),yv=qe(),rn=Sv("iterator"),rc=!1,at,en,tn;[].keys&&(tn=[].keys(),"next"in tn?(en=tc(tc(tn)),en!==Object.prototype&&(at=en)):rc=!0);var Tv=!bv(at)||fv(function(){var i={};return at[rn].call(i)!==i});Tv?at={}:yv&&(at=gv(at));mv(at[rn])||vv(at,rn,function(){return this});ic.exports={IteratorPrototype:at,BUGGY_SAFARI_ITERATORS:rc}});var pa=m((HP,sc)=>{"use strict";var Iv=ce(),Ev=Iv("toStringTag"),ac={};ac[Ev]="z";sc.exports=String(ac)==="[object z]"});var ar=m((jP,nc)=>{"use strict";var xv=pa(),Pv=ee(),ha=Jt(),kv=ce(),wv=kv("toStringTag"),Av=Object,Rv=ha(function(){return arguments}())=="Arguments",Lv=function(i,e){try{return i[e]}catch{}};nc.exports=xv?ha:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Lv(e=Av(i),wv))=="string"?t:Rv?ha(e):(r=ha(e))=="Object"&&Pv(e.callee)?"Arguments":r}});var uc=m((GP,oc)=>{"use strict";var $v=pa(),Cv=ar();oc.exports=$v?{}.toString:function(){return"[object "+Cv(this)+"]"}});var fa=m((YP,cc)=>{"use strict";var Dv=pa(),Mv=Lt().f,Ov=$t(),Bv=Ue(),Vv=uc(),_v=ce(),lc=_v("toStringTag");cc.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;Bv(a,lc)||Mv(a,lc,{configurable:!0,value:e}),r&&!Dv&&Ov(a,"toString",Vv)}}});var pc=m((WP,dc)=>{"use strict";var Nv=an().IteratorPrototype,Fv=Js(),qv=$r(),Uv=fa(),Hv=Rt(),jv=function(){return this};dc.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Fv(Nv,{next:qv(+!r,t)}),Uv(i,a,!1,!0),Hv[a]=jv,i}});var fc=m((QP,hc)=>{"use strict";var Gv=fe(),Yv=it();hc.exports=function(i,e,t){try{return Gv(Yv(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var bc=m((zP,mc)=>{"use strict";var Wv=ee(),Qv=String,zv=TypeError;mc.exports=function(i){if(typeof i=="object"||Wv(i))return i;throw zv("Can't set "+Qv(i)+" as a prototype")}});var sn=m((KP,gc)=>{"use strict";var Kv=fc(),Jv=Ne(),Xv=bc();gc.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Kv(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Jv(a),Xv(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var Ac=m((JP,wc)=>{"use strict";var Zv=Ae(),eS=me(),ma=qe(),Pc=Il(),tS=ee(),rS=pc(),vc=Zs(),Sc=sn(),iS=fa(),aS=$t(),nn=ir(),sS=ce(),yc=Rt(),kc=an(),nS=Pc.PROPER,oS=Pc.CONFIGURABLE,Tc=kc.IteratorPrototype,ba=kc.BUGGY_SAFARI_ITERATORS,Or=sS("iterator"),Ic="keys",Br="values",Ec="entries",xc=function(){return this};wc.exports=function(i,e,t,r,a,s,n){rS(t,e,r);var o=function(T){if(T===a&&f)return f;if(!ba&&T in c)return c[T];switch(T){case Ic:return function(){return new t(this,T)};case Br:return function(){return new t(this,T)};case Ec:return function(){return new t(this,T)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Or]||c["@@iterator"]||a&&c[a],f=!ba&&d||o(a),h=e=="Array"&&c.entries||d,b,I,g;if(h&&(b=vc(h.call(new i)),b!==Object.prototype&&b.next&&(!ma&&vc(b)!==Tc&&(Sc?Sc(b,Tc):tS(b[Or])||nn(b,Or,xc)),iS(b,l,!0,!0),ma&&(yc[l]=xc))),nS&&a==Br&&d&&d.name!==Br&&(!ma&&oS?aS(c,"name",Br):(u=!0,f=function(){return eS(d,this)})),a)if(I={values:o(Br),keys:s?f:o(Ic),entries:o(Ec)},n)for(g in I)(ba||u||!(g in c))&&nn(c,g,I[g]);else Zv({target:e,proto:!0,forced:ba||u},I);return(!ma||n)&&c[Or]!==f&&nn(c,Or,f,{name:a}),yc[e]=f,I}});var Lc=m((XP,Rc)=>{"use strict";Rc.exports=function(i,e){return{value:i,done:e}}});var un=m((ZP,Oc)=>{"use strict";var uS=Zt(),on=ps(),$c=Rt(),Dc=_s(),lS=Lt().f,cS=Ac(),ga=Lc(),dS=qe(),pS=ze(),Mc="Array Iterator",hS=Dc.set,fS=Dc.getterFor(Mc);Oc.exports=cS(Array,"Array",function(i,e){hS(this,{type:Mc,target:uS(i),index:0,kind:e})},function(){var i=fS(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,ga(void 0,!0)):t=="keys"?ga(r,!1):t=="values"?ga(e[r],!1):ga([r,e[r]],!1)},"values");var Cc=$c.Arguments=$c.Array;on("keys");on("values");on("entries");if(!dS&&pS&&Cc.name!=="values")try{lS(Cc,"name",{value:"values"})}catch{}});var Vc=m((ek,Bc)=>{"use strict";var mS=ce(),bS=Rt(),gS=mS("iterator"),vS=Array.prototype;Bc.exports=function(i){return i!==void 0&&(bS.Array===i||vS[gS]===i)}});var ln=m((tk,Nc)=>{"use strict";var SS=ar(),_c=Rr(),yS=Xt(),TS=Rt(),IS=ce(),ES=IS("iterator");Nc.exports=function(i){if(!yS(i))return _c(i,ES)||_c(i,"@@iterator")||TS[SS(i)]}});var qc=m((rk,Fc)=>{"use strict";var xS=me(),PS=it(),kS=Ne(),wS=Ar(),AS=ln(),RS=TypeError;Fc.exports=function(i,e){var t=arguments.length<2?AS(i):e;if(PS(t))return kS(xS(t,i));throw RS(wS(i)+" is not iterable")}});var jc=m((ik,Hc)=>{"use strict";var LS=me(),Uc=Ne(),$S=Rr();Hc.exports=function(i,e,t){var r,a;Uc(i);try{if(r=$S(i,"return"),!r){if(e==="throw")throw t;return t}r=LS(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Uc(r),t}});var Sa=m((ak,Qc)=>{"use strict";var CS=Mr(),DS=me(),MS=Ne(),OS=Ar(),BS=Vc(),VS=la(),Gc=kr(),_S=qc(),NS=ln(),Yc=jc(),FS=TypeError,va=function(i,e){this.stopped=i,this.result=e},Wc=va.prototype;Qc.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=CS(e,r),u,c,d,f,h,b,I,g=function(y){return u&&Yc(u,"normal",y),new va(!0,y)},T=function(y){return a?(MS(y),o?l(y[0],y[1],g):l(y[0],y[1])):o?l(y,g):l(y)};if(s)u=i.iterator;else if(n)u=i;else{if(c=NS(i),!c)throw FS(OS(i)+" is not iterable");if(BS(c)){for(d=0,f=VS(i);f>d;d++)if(h=T(i[d]),h&&Gc(Wc,h))return h;return new va(!1)}u=_S(i,c)}for(b=s?i.next:u.next;!(I=DS(b,u)).done;){try{h=T(I.value)}catch(y){Yc(u,"throw",y)}if(typeof h=="object"&&h&&Gc(Wc,h))return h}return new va(!1)}});var Kc=m((sk,zc)=>{"use strict";var qS=ta(),US=Lt(),HS=$r();zc.exports=function(i,e,t){var r=qS(e);r in i?US.f(i,r,HS(0,t)):i[r]=t}});var Jc=m(()=>{"use strict";var jS=Ae(),GS=Sa(),YS=Kc();jS({target:"Object",stat:!0},{fromEntries:function(e){var t={};return GS(e,function(r,a){YS(t,r,a)},{AS_ENTRIES:!0}),t}})});var Zc=m((uk,Xc)=>{"use strict";un();Jc();var WS=Xi();Xc.exports=WS.Object.fromEntries});var td=m((lk,ed)=>{"use strict";ed.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var ad=m(()=>{"use strict";un();var QS=td(),zS=ne(),KS=ar(),JS=$t(),rd=Rt(),XS=ce(),id=XS("toStringTag");for(ya in QS)cn=zS[ya],Ta=cn&&cn.prototype,Ta&&KS(Ta)!==id&&JS(Ta,id,ya),rd[ya]=rd.Array;var cn,Ta,ya});var nd=m((pk,sd)=>{"use strict";var ZS=Zc();ad();sd.exports=ZS});var Ia=m((hk,od)=>{"use strict";var ey=nd();od.exports=ey});var ud=m(()=>{"use strict"});var Vr=m((bk,ld)=>{"use strict";var ty=Jt();ld.exports=typeof process<"u"&&ty(process)=="process"});var dd=m((gk,cd)=>{"use strict";var ry=Lt();cd.exports=function(i,e,t){return ry.f(i,e,t)}});var fd=m((vk,hd)=>{"use strict";var iy=rt(),ay=dd(),sy=ce(),ny=ze(),pd=sy("species");hd.exports=function(i){var e=iy(i);ny&&e&&!e[pd]&&ay(e,pd,{configurable:!0,get:function(){return this}})}});var bd=m((Sk,md)=>{"use strict";var oy=kr(),uy=TypeError;md.exports=function(i,e){if(oy(e,i))return i;throw uy("Incorrect invocation")}});var pn=m((yk,gd)=>{"use strict";var ly=fe(),cy=ee(),dn=ea(),dy=ly(Function.toString);cy(dn.inspectSource)||(dn.inspectSource=function(i){return dy(i)});gd.exports=dn.inspectSource});var Ed=m((Tk,Id)=>{"use strict";var py=fe(),hy=Pe(),vd=ee(),fy=ar(),my=rt(),by=pn(),Sd=function(){},gy=[],yd=my("Reflect","construct"),hn=/^\s*(?:class|function)\b/,vy=py(hn.exec),Sy=!hn.exec(Sd),_r=function(e){if(!vd(e))return!1;try{return yd(Sd,gy,e),!0}catch{return!1}},Td=function(e){if(!vd(e))return!1;switch(fy(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Sy||!!vy(hn,by(e))}catch{return!0}};Td.sham=!0;Id.exports=!yd||hy(function(){var i;return _r(_r.call)||!_r(Object)||!_r(function(){i=!0})||i})?Td:_r});var Pd=m((Ik,xd)=>{"use strict";var yy=Ed(),Ty=Ar(),Iy=TypeError;xd.exports=function(i){if(yy(i))return i;throw Iy(Ty(i)+" is not a constructor")}});var fn=m((Ek,wd)=>{"use strict";var kd=Ne(),Ey=Pd(),xy=Xt(),Py=ce(),ky=Py("species");wd.exports=function(i,e){var t=kd(i).constructor,r;return t===void 0||xy(r=kd(t)[ky])?e:Ey(r)}});var Rd=m((xk,Ad)=>{"use strict";var wy=fe();Ad.exports=wy([].slice)});var $d=m((Pk,Ld)=>{"use strict";var Ay=TypeError;Ld.exports=function(i,e){if(i<e)throw Ay("Not enough arguments");return i}});var mn=m((kk,Cd)=>{"use strict";var Ry=wr();Cd.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ry)});var xn=m((wk,qd)=>{"use strict";var ke=ne(),Ly=Ns(),$y=Mr(),Dd=ee(),Cy=Ue(),Fd=Pe(),Md=Ws(),Dy=Rd(),Od=Ki(),My=$d(),Oy=mn(),By=Vr(),Tn=ke.setImmediate,In=ke.clearImmediate,Vy=ke.process,bn=ke.Dispatch,_y=ke.Function,Bd=ke.MessageChannel,Ny=ke.String,gn=0,Nr={},Vd="onreadystatechange",Fr,Dt,vn,Sn;Fd(function(){Fr=ke.location});var En=function(i){if(Cy(Nr,i)){var e=Nr[i];delete Nr[i],e()}},yn=function(i){return function(){En(i)}},_d=function(i){En(i.data)},Nd=function(i){ke.postMessage(Ny(i),Fr.protocol+"//"+Fr.host)};(!Tn||!In)&&(Tn=function(e){My(arguments.length,1);var t=Dd(e)?e:_y(e),r=Dy(arguments,1);return Nr[++gn]=function(){Ly(t,void 0,r)},Dt(gn),gn},In=function(e){delete Nr[e]},By?Dt=function(i){Vy.nextTick(yn(i))}:bn&&bn.now?Dt=function(i){bn.now(yn(i))}:Bd&&!Oy?(vn=new Bd,Sn=vn.port2,vn.port1.onmessage=_d,Dt=$y(Sn.postMessage,Sn)):ke.addEventListener&&Dd(ke.postMessage)&&!ke.importScripts&&Fr&&Fr.protocol!=="file:"&&!Fd(Nd)?(Dt=Nd,ke.addEventListener("message",_d,!1)):Vd in Od("script")?Dt=function(i){Md.appendChild(Od("script"))[Vd]=function(){Md.removeChild(this),En(i)}}:Dt=function(i){setTimeout(yn(i),0)});qd.exports={set:Tn,clear:In}});var Pn=m((Ak,Hd)=>{"use strict";var Ud=function(){this.head=null,this.tail=null};Ud.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Hd.exports=Ud});var Gd=m((Rk,jd)=>{"use strict";var Fy=wr();jd.exports=/ipad|iphone|ipod/i.test(Fy)&&typeof Pebble<"u"});var Wd=m((Lk,Yd)=>{"use strict";var qy=wr();Yd.exports=/web0s(?!.*chrome)/i.test(qy)});var tp=m(($k,ep)=>{"use strict";var Mt=ne(),Qd=Mr(),Uy=qs().f,kn=xn().set,Hy=Pn(),jy=mn(),Gy=Gd(),Yy=Wd(),wn=Vr(),zd=Mt.MutationObserver||Mt.WebKitMutationObserver,Kd=Mt.document,Jd=Mt.process,Ea=Mt.Promise,Xd=Uy(Mt,"queueMicrotask"),Ln=Xd&&Xd.value,sr,An,Rn,xa,Zd;Ln||(qr=new Hy,Ur=function(){var i,e;for(wn&&(i=Jd.domain)&&i.exit();e=qr.get();)try{e()}catch(t){throw qr.head&&sr(),t}i&&i.enter()},!jy&&!wn&&!Yy&&zd&&Kd?(An=!0,Rn=Kd.createTextNode(""),new zd(Ur).observe(Rn,{characterData:!0}),sr=function(){Rn.data=An=!An}):!Gy&&Ea&&Ea.resolve?(xa=Ea.resolve(void 0),xa.constructor=Ea,Zd=Qd(xa.then,xa),sr=function(){Zd(Ur)}):wn?sr=function(){Jd.nextTick(Ur)}:(kn=Qd(kn,Mt),sr=function(){kn(Ur)}),Ln=function(i){qr.head||sr(),qr.add(i)});var qr,Ur;ep.exports=Ln});var ip=m((Ck,rp)=>{"use strict";rp.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch{}}});var Pa=m((Dk,ap)=>{"use strict";ap.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Ot=m((Mk,sp)=>{"use strict";var Wy=ne();sp.exports=Wy.Promise});var $n=m((Ok,np)=>{"use strict";np.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var up=m((Bk,op)=>{"use strict";var Qy=$n(),zy=Vr();op.exports=!Qy&&!zy&&typeof window=="object"&&typeof document=="object"});var nr=m((Vk,dp)=>{"use strict";var Ky=ne(),Hr=Ot(),Jy=ee(),Xy=Us(),Zy=pn(),eT=ce(),tT=up(),rT=$n(),iT=qe(),Cn=Ts(),lp=Hr&&Hr.prototype,aT=eT("species"),Dn=!1,cp=Jy(Ky.PromiseRejectionEvent),sT=Xy("Promise",function(){var i=Zy(Hr),e=i!==String(Hr);if(!e&&Cn===66||iT&&!(lp.catch&&lp.finally))return!0;if(!Cn||Cn<51||!/native code/.test(i)){var t=new Hr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[aT]=r,Dn=t.then(function(){})instanceof r,!Dn)return!0}return!e&&(tT||rT)&&!cp});dp.exports={CONSTRUCTOR:sT,REJECTION_EVENT:cp,SUBCLASSING:Dn}});var or=m((_k,hp)=>{"use strict";var pp=it(),nT=TypeError,oT=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw nT("Bad Promise constructor");e=r,t=a}),this.resolve=pp(e),this.reject=pp(t)};hp.exports.f=function(i){return new oT(i)}});var Cp=m(()=>{"use strict";var uT=Ae(),lT=qe(),Ra=Vr(),yt=ne(),dr=me(),fp=ir(),mp=sn(),cT=fa(),dT=fd(),pT=it(),Aa=ee(),hT=Qe(),fT=bd(),mT=fn(),yp=xn().set,_n=tp(),bT=ip(),gT=Pa(),vT=Pn(),Tp=_s(),La=Ot(),Nn=nr(),Ip=or(),$a="Promise",Ep=Nn.CONSTRUCTOR,ST=Nn.REJECTION_EVENT,yT=Nn.SUBCLASSING,Mn=Tp.getterFor($a),TT=Tp.set,ur=La&&La.prototype,Bt=La,ka=ur,xp=yt.TypeError,On=yt.document,Fn=yt.process,Bn=Ip.f,IT=Bn,ET=!!(On&&On.createEvent&&yt.dispatchEvent),Pp="unhandledrejection",xT="rejectionhandled",bp=0,kp=1,PT=2,qn=1,wp=2,wa,gp,kT,vp,Ap=function(i){var e;return hT(i)&&Aa(e=i.then)?e:!1},Rp=function(i,e){var t=e.value,r=e.state==kp,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===wp&&AT(e),e.rejection=qn),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(xp("Promise-chain cycle")):(u=Ap(l))?dr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Lp=function(i,e){i.notified||(i.notified=!0,_n(function(){for(var t=i.reactions,r;r=t.get();)Rp(r,i);i.notified=!1,e&&!i.rejection&&wT(i)}))},$p=function(i,e,t){var r,a;ET?(r=On.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),yt.dispatchEvent(r)):r={promise:e,reason:t},!ST&&(a=yt["on"+i])?a(r):i===Pp&&bT("Unhandled promise rejection",t)},wT=function(i){dr(yp,yt,function(){var e=i.facade,t=i.value,r=Sp(i),a;if(r&&(a=gT(function(){Ra?Fn.emit("unhandledRejection",t,e):$p(Pp,e,t)}),i.rejection=Ra||Sp(i)?wp:qn,a.error))throw a.value})},Sp=function(i){return i.rejection!==qn&&!i.parent},AT=function(i){dr(yp,yt,function(){var e=i.facade;Ra?Fn.emit("rejectionHandled",e):$p(xT,e,i.value)})},lr=function(i,e,t){return function(r){i(e,r,t)}},cr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=PT,Lp(i,!0))},Vn=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw xp("Promise can't be resolved itself");var r=Ap(e);r?_n(function(){var a={done:!1};try{dr(r,e,lr(Vn,a,i),lr(cr,a,i))}catch(s){cr(a,s,i)}}):(i.value=e,i.state=kp,Lp(i,!1))}catch(a){cr({done:!1},a,i)}}};if(Ep&&(Bt=function(e){fT(this,ka),pT(e),dr(wa,this);var t=Mn(this);try{e(lr(Vn,t),lr(cr,t))}catch(r){cr(t,r)}},ka=Bt.prototype,wa=function(e){TT(this,{type:$a,done:!1,notified:!1,parent:!1,reactions:new vT,rejection:!1,state:bp,value:void 0})},wa.prototype=fp(ka,"then",function(e,t){var r=Mn(this),a=Bn(mT(this,Bt));return r.parent=!0,a.ok=Aa(e)?e:!0,a.fail=Aa(t)&&t,a.domain=Ra?Fn.domain:void 0,r.state==bp?r.reactions.add(a):_n(function(){Rp(a,r)}),a.promise}),gp=function(){var i=new wa,e=Mn(i);this.promise=i,this.resolve=lr(Vn,e),this.reject=lr(cr,e)},Ip.f=Bn=function(i){return i===Bt||i===kT?new gp(i):IT(i)},!lT&&Aa(La)&&ur!==Object.prototype)){vp=ur.then,yT||fp(ur,"then",function(e,t){var r=this;return new Bt(function(a,s){dr(vp,r,a,s)}).then(e,t)},{unsafe:!0});try{delete ur.constructor}catch{}mp&&mp(ur,ka)}uT({global:!0,constructor:!0,wrap:!0,forced:Ep},{Promise:Bt});cT(Bt,$a,!1,!0);dT($a)});var Vp=m((qk,Bp)=>{"use strict";var RT=ce(),Mp=RT("iterator"),Op=!1;try{Dp=0,Un={next:function(){return{done:!!Dp++}},return:function(){Op=!0}},Un[Mp]=function(){return this},Array.from(Un,function(){throw 2})}catch{}var Dp,Un;Bp.exports=function(i,e){if(!e&&!Op)return!1;var t=!1;try{var r={};r[Mp]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var Hn=m((Uk,_p)=>{"use strict";var LT=Ot(),$T=Vp(),CT=nr().CONSTRUCTOR;_p.exports=CT||!$T(function(i){LT.all(i).then(void 0,function(){})})});var Np=m(()=>{"use strict";var DT=Ae(),MT=me(),OT=it(),BT=or(),VT=Pa(),_T=Sa(),NT=Hn();DT({target:"Promise",stat:!0,forced:NT},{all:function(e){var t=this,r=BT.f(t),a=r.resolve,s=r.reject,n=VT(function(){var o=OT(t.resolve),l=[],u=0,c=1;_T(e,function(d){var f=u++,h=!1;c++,MT(o,t,d).then(function(b){h||(h=!0,l[f]=b,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var qp=m(()=>{"use strict";var FT=Ae(),qT=qe(),UT=nr().CONSTRUCTOR,Gn=Ot(),HT=rt(),jT=ee(),GT=ir(),Fp=Gn&&Gn.prototype;FT({target:"Promise",proto:!0,forced:UT,real:!0},{catch:function(i){return this.then(void 0,i)}});!qT&&jT(Gn)&&(jn=HT("Promise").prototype.catch,Fp.catch!==jn&>(Fp,"catch",jn,{unsafe:!0}));var jn});var Up=m(()=>{"use strict";var YT=Ae(),WT=me(),QT=it(),zT=or(),KT=Pa(),JT=Sa(),XT=Hn();YT({target:"Promise",stat:!0,forced:XT},{race:function(e){var t=this,r=zT.f(t),a=r.reject,s=KT(function(){var n=QT(t.resolve);JT(e,function(o){WT(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Hp=m(()=>{"use strict";var ZT=Ae(),eI=me(),tI=or(),rI=nr().CONSTRUCTOR;ZT({target:"Promise",stat:!0,forced:rI},{reject:function(e){var t=tI.f(this);return eI(t.reject,void 0,e),t.promise}})});var Yn=m((Jk,jp)=>{"use strict";var iI=Ne(),aI=Qe(),sI=or();jp.exports=function(i,e){if(iI(i),aI(e)&&e.constructor===i)return e;var t=sI.f(i),r=t.resolve;return r(e),t.promise}});var Wp=m(()=>{"use strict";var nI=Ae(),oI=rt(),Gp=qe(),uI=Ot(),Yp=nr().CONSTRUCTOR,lI=Yn(),cI=oI("Promise"),dI=Gp&&!Yp;nI({target:"Promise",stat:!0,forced:Gp||Yp},{resolve:function(e){return lI(dI&&this===cI?uI:this,e)}})});var Qp=m(()=>{"use strict";Cp();Np();qp();Up();Hp();Wp()});var Xp=m(()=>{"use strict";var pI=Ae(),hI=qe(),Ca=Ot(),fI=Pe(),Kp=rt(),Jp=ee(),mI=fn(),zp=Yn(),bI=ir(),Qn=Ca&&Ca.prototype,gI=!!Ca&&fI(function(){Qn.finally.call({then:function(){}},function(){})});pI({target:"Promise",proto:!0,real:!0,forced:gI},{finally:function(i){var e=mI(this,Kp("Promise")),t=Jp(i);return this.then(t?function(r){return zp(e,i()).then(function(){return r})}:i,t?function(r){return zp(e,i()).then(function(){throw r})}:i)}});!hI&&Jp(Ca)&&(Wn=Kp("Promise").prototype.finally,Qn.finally!==Wn&&bI(Qn,"finally",Wn,{unsafe:!0}));var Wn});var Da=m((aw,Zp)=>{"use strict";var vI=rt();Zp.exports=vI});var th=m((sw,eh)=>{"use strict";ud();Qp();Xp();var SI=Da();eh.exports=SI("Promise","finally")});var ih=m((nw,rh)=>{"use strict";var yI=th();rh.exports=yI});var Ma=m((ow,ah)=>{"use strict";var TI=ih();ah.exports=TI});var hh=m(()=>{"use strict";var AI=Ae(),RI=Lr(),LI=la(),$I=ua(),CI=ps();AI({target:"Array",proto:!0},{at:function(e){var t=RI(this),r=LI(t),a=$I(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});CI("at")});var mh=m((uA,fh)=>{"use strict";hh();var DI=Da();fh.exports=DI("Array","at")});var gh=m((lA,bh)=>{"use strict";var MI=mh();bh.exports=MI});var Ba=m((cA,vh)=>{"use strict";var OI=gh();vh.exports=OI});var Vh=m(()=>{"use strict"});var _h=m(()=>{"use strict"});var Fh=m((F$,Nh)=>{"use strict";var dE=Qe(),pE=Jt(),hE=ce(),fE=hE("match");Nh.exports=function(i){var e;return dE(i)&&((e=i[fE])!==void 0?!!e:pE(i)=="RegExp")}});var Uh=m((q$,qh)=>{"use strict";var mE=ar(),bE=String;qh.exports=function(i){if(mE(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return bE(i)}});var jh=m((U$,Hh)=>{"use strict";var gE=Ne();Hh.exports=function(){var i=gE(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var Wh=m((H$,Yh)=>{"use strict";var vE=me(),SE=Ue(),yE=kr(),TE=jh(),Gh=RegExp.prototype;Yh.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Gh)&&!SE(i,"flags")&&yE(Gh,i)?vE(TE,i):e}});var zh=m((j$,Qh)=>{"use strict";var mo=fe(),IE=Lr(),EE=Math.floor,ho=mo("".charAt),xE=mo("".replace),fo=mo("".slice),PE=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,kE=/\$([$&'`]|\d{1,2})/g;Qh.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=kE;return a!==void 0&&(a=IE(a),l=PE),xE(s,l,function(u,c){var d;switch(ho(c,0)){case"$":return"$";case"&":return i;case"`":return fo(e,0,t);case"'":return fo(e,n);case"<":d=a[fo(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>o){var h=EE(f/10);return h===0?u:h<=o?r[h-1]===void 0?ho(c,1):r[h-1]+ho(c,1):u}d=r[f-1]}return d===void 0?"":d})}});var ef=m(()=>{"use strict";var wE=Ae(),AE=me(),bo=fe(),Kh=Qi(),RE=ee(),LE=Xt(),$E=Fh(),br=Uh(),CE=Rr(),DE=Wh(),ME=zh(),OE=ce(),BE=qe(),VE=OE("replace"),_E=TypeError,Zh=bo("".indexOf),NE=bo("".replace),Jh=bo("".slice),FE=Math.max,Xh=function(i,e,t){return t>i.length?-1:e===""?t:Zh(i,e,t)};wE({target:"String",proto:!0},{replaceAll:function(e,t){var r=Kh(this),a,s,n,o,l,u,c,d,f,h=0,b=0,I="";if(!LE(e)){if(a=$E(e),a&&(s=br(Kh(DE(e))),!~Zh(s,"g")))throw _E("`.replaceAll` does not allow non-global regexes");if(n=CE(e,VE),n)return AE(n,e,r,t);if(BE&&a)return NE(br(r),e,t)}for(o=br(r),l=br(e),u=RE(t),u||(t=br(t)),c=l.length,d=FE(1,c),h=Xh(o,l,0);h!==-1;)f=u?br(t(l,h,o)):ME(l,o,h,[],void 0,t),I+=Jh(o,b,h)+f,b=h+c,h=Xh(o,l,h+d);return b<o.length&&(I+=Jh(o,b)),I}})});var rf=m((W$,tf)=>{"use strict";Vh();_h();ef();var qE=Da();tf.exports=qE("String","replaceAll")});var sf=m((Q$,af)=>{"use strict";var UE=rf();af.exports=UE});var of=m((z$,nf)=>{"use strict";var HE=sf();nf.exports=HE});var dx={};om(dx,{ChromecastState:()=>xr,HttpConnectionType:()=>Gi,Observable:()=>et.Observable,PlaybackState:()=>he,Player:()=>_i,SDK_VERSION:()=>cx,Subject:()=>et.Subject,Subscription:()=>et.Subscription,Surface:()=>Yi,VERSION:()=>ls,ValueSubject:()=>et.ValueSubject,VideoFormat:()=>St,VideoQuality:()=>et.VideoQuality});module.exports=um(dx);var ls="__VERSION__";var he=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(he||{}),St=(y=>(y.MPEG="MPEG",y.DASH="DASH_SEP",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(St||{});var xr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(xr||{}),Gi=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Gi||{});var Yi=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Yi||{});var V=require("@vkontakte/videoplayer-shared");var $o=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Wi=class{constructor(e){this.connection$=new V.ValueSubject(void 0);this.castState$=new V.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new V.Subject;this.realCastState$=new V.ValueSubject("NOT_AVAILABLE");this.subscription=new V.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,V.isNonNullable)(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||$o("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:V.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(){(0,V.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,V.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,V.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,V.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.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(0,V.assertNever)(a.sessionState)}})).add((0,V.merge)((0,V.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,V.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,V.map)(a=>a.castState)),(0,V.observableFrom)([r.getCastState()])).pipe((0,V.filterChanged)(),(0,V.map)(lm),(0,V.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=(0,V.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();(0,V.assertNonNullable)(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;((0,V.isNullable)(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,V.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:V.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},lm=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,V.assertNever)(i)}};var Ff=_e(Ia(),1);var uh=_e(Ma(),1);var zn=require("@vkontakte/videoplayer-shared");var de=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,zn.assertNever)(t)}return i},Kn=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:(0,zn.assertNever)(e)}};var P=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var Ke=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new Ke.Subject;this.transitionEnded$=new Ke.Subject;this.transitionUpdated$=new Ke.Subject;this.forceChanged$=new Ke.Subject;this.stateChangeStarted$=(0,Ke.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ke.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,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:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,Ke.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var sh=require("@vkontakte/videoplayer-shared"),nh=i=>{switch(i){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,sh.assertNever)(i)}};var R=require("@vkontakte/videoplayer-shared");var II=5,EI=5,xI=500,oh=7e3,jr=class{constructor(e){this.subscription=new R.Subscription;this.loadMediaTimeoutSubscription=new R.Subscription;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,R.assertNever)(e)}break}default:(0,R.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(nh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let 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);let e=new R.Subscription;this.subscription.add(e),this.subscription.add((0,R.merge)(this.videoState.stateChangeStarted$.pipe((0,R.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,R.map)(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new R.Subject;e.add(a.pipe((0,R.debounce)(xI)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>II)&&a.next(o),s=o})),e.add((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<EI&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.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:(0,R.assertNever)(n)}}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,R.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,R.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,R.observableFrom)(["init"])).pipe((0,R.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];(0,R.assertNonNullable)(u);let c=(0,R.getHighestQuality)(Object.keys(u));(0,R.assertNonNullable)(c);let d=u[c];(0,R.assertNonNullable)(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];(0,R.assertNonNullable)(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let u=t[e];(0,R.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];(0,R.assertNonNullable)(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];(0,R.assertNonNullable)(u),r=de(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.ErrorCategory.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,R.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return(0,R.isNonNullable)(o)&&(n.metadata.title=o),(0,R.isNonNullable)(l)&&(n.metadata.subtitle=l),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add((0,R.timeout)(oh).subscribe(()=>s(`timeout(${oh})`)))});(0,uh.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:R.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Gr=i=>{i.removeAttribute("src"),i.load()};var lh=i=>{try{i.pause(),i.playbackRate=0,Gr(i),i.remove()}catch(e){console.error(e)}};var Jn=class{constructor(){this.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)}},Xn=window.WeakMap?new WeakMap:new Jn,be=i=>{let e=i.querySelector("video"),t=!!e;return e?Gr(e):(e=document.createElement("video"),i.appendChild(e)),Xn.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ge=i=>{let e=Xn.get(i);Xn.delete(i),e?Gr(i):lh(i)};var L=require("@vkontakte/videoplayer-shared");var Tt=require("@vkontakte/videoplayer-shared"),Oa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=(0,Tt.isNullable)(a),u=new Tt.Subscription;return a&&u.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),l&&i.setState(c.to)},s)),u},Je=(i,e,t)=>Oa(e,()=>i.loop,r=>{(0,Tt.isNonNullable)(r)&&(i.loop=r)},{onError:t}),ve=(i,e,t,r)=>Oa(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,Tt.isNonNullable)(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),Re=(i,e,t,r)=>Oa(e,()=>i.playbackRate,a=>{(0,Tt.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),It=Oa;var PI=i=>["__",i.language,i.label].join("|"),kI=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Zn=class i{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(It(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(It(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(It(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:a})),this.subscription.add(It(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;(0,L.isNonNullable)(t.align)&&(a.align=t.align),(0,L.isNonNullable)(t.position)&&(a.position=t.position),(0,L.isNonNullable)(t.size)&&(a.size=t.size),(0,L.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:PI(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!kI(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,L.assertNonNullable)(this.video);let 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){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.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)}},Le=Zn;var nt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.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()}};var ch=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},eo=i=>{let e=ch(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},dh=i=>{let e=ch(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var A=require("@vkontakte/videoplayer-shared");var wI=3,ph=(i,e,t=wI)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var Se=i=>{let e=M=>(0,A.fromEvent)(i,M).pipe((0,A.mapTo)(void 0)),r=(0,A.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(M=>(0,A.fromEvent)(i,M))).pipe((0,A.map)(M=>M.type==="ended"?i.readyState<2:i.readyState<3),(0,A.filterChanged)()),a=(0,A.merge)((0,A.fromEvent)(i,"progress"),(0,A.fromEvent)(i,"timeupdate")).pipe((0,A.map)(()=>ph(i.buffered,i.currentTime))),n=(0,A.getCurrentBrowser)().browser===A.CurrentClientBrowser.Safari?(0,A.combine)({play:e("play").pipe((0,A.once)()),playing:e("playing")}).pipe((0,A.mapTo)(void 0)):e("playing"),o=(0,A.fromEvent)(i,"volumechange").pipe((0,A.map)(()=>({muted:i.muted,volume:i.volume}))),l=(0,A.fromEvent)(i,"ratechange").pipe((0,A.map)(()=>i.playbackRate)),u=(0,A.fromEvent)(i,"error").pipe((0,A.filter)(()=>!!(i.error||i.played.length)),(0,A.map)(()=>{let M=i.error;return{id:M?`MediaError#${M.code}`:"HtmlVideoError",category:A.ErrorCategory.VIDEO_PIPELINE,message:M?M.message:"Error event from HTML video element",thrown:i.error??void 0}})),c=(0,A.fromEvent)(i,"timeupdate").pipe((0,A.map)(()=>i.currentTime)),d=new A.Subject,f=.3,h;c.subscribe(M=>{i.loop&&(0,A.isNonNullable)(h)&&(0,A.isNonNullable)(M)&&h>=i.duration-f&&M<=f&&d.next(h),h=M});let b=(0,A.fromEvent)(i,"enterpictureinpicture"),I=(0,A.fromEvent)(i,"leavepictureinpicture"),g=new A.ValueSubject(dh(i));b.subscribe(()=>g.next(!0)),I.subscribe(()=>g.next(!1));let T=new A.ValueSubject(eo(i));return(0,A.fromEvent)(i,"fullscreenchange").pipe((0,A.map)(()=>eo(i))).subscribe(T),{playing$:n,pause$:e("pause").pipe((0,A.filter)(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,A.fromEvent)(i,"durationchange").pipe((0,A.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:g,inFullscreen$:T}};var ot=require("@vkontakte/videoplayer-shared"),Et=i=>{switch(i){case"mobile":return ot.VideoQuality.Q_144P;case"lowest":return ot.VideoQuality.Q_240P;case"low":return ot.VideoQuality.Q_360P;case"sd":case"medium":return ot.VideoQuality.Q_480P;case"hd":case"high":return ot.VideoQuality.Q_720P;case"fullhd":case"full":return ot.VideoQuality.Q_1080P;case"quadhd":case"quad":return ot.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ot.VideoQuality.Q_2160P}};var ro=_e(Ba(),1),F=require("@vkontakte/videoplayer-shared");var to=!1,ut={},Sh=i=>{to=i},yh=()=>{ut={}},Th=i=>{i(ut)},Yr=(i,e)=>{to&&(ut.meta=ut.meta??{},ut.meta[i]=e)},pe=class{constructor(e){this.name=e}next(e){if(!to)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var BI=new pe("best_bitrate"),VI=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Va=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,F.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},_I='Assertion "ABR Tracks is empty array" failed',NI=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{(0,F.assertNotEmptyArray)(i,_I);let f=r.usePixelRatio?window.devicePixelRatio??1:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},b=h&&(0,F.videoSizeToQuality)(h),I=r.considerPlaybackRate&&(0,F.isNonNullable)(o)?o:1,g=i.filter(w=>!(0,F.isInvariantQuality)(w.quality)).sort((w,$)=>(0,F.isHigher)(w.quality,$.quality)?-1:1),T=(0,ro.default)(g,-1)?.quality,y=(0,ro.default)(g,0)?.quality,M=(0,F.isNullable)(a)||(0,F.isNonNullable)(a.min)&&(0,F.isNonNullable)(a.max)&&(0,F.isLower)(a.max,a.min)||(0,F.isNonNullable)(a.min)&&y&&(0,F.isHigher)(a.min,y)||(0,F.isNonNullable)(a.max)&&T&&(0,F.isLower)(a.max,T),E=I*VI(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),k={},j=g.filter(w=>(b?(0,F.isLower)(w.quality,b):!0)?((0,F.isNonNullable)(t)&&isFinite(t)&&(0,F.isNonNullable)(w.bitrate)?t-s>=w.bitrate*E:!0)?r.lazyQualitySwitch&&(0,F.isNonNullable)(r.minBufferToSwitchUp)&&l&&!(0,F.isInvariantQuality)(l.quality)&&(n??0)<r.minBufferToSwitchUp&&(0,F.isHigher)(w.quality,l.quality)?(k[w.quality]="Buffer",!1):!!c&&(0,F.isHigherOrEqual)(w.quality,c)?(k[w.quality]="DroppedFramesLimit",!1):M||((0,F.isNullable)(a.max)||(0,F.isLowerOrEqual)(w.quality,a.max))&&((0,F.isNullable)(a.min)||(0,F.isHigherOrEqual)(w.quality,a.min))?!0:(k[w.quality]="FitsQualityLimits",!1):(k[w.quality]="FitsThroughput",!1):(k[w.quality]="FitsContainer",!1))[0];j&&j.bitrate&&BI.next(j.bitrate);let N=j??g[Math.ceil((g.length-1)/2)]??i[0];N.quality!==u?.last?.quality&&d({message:`
|
|
7
7
|
[available tracks]
|
|
8
|
-
${
|
|
8
|
+
${i.map(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(
|
|
12
|
+
${Object.entries(r??{}).map(([w,$])=>`${w}: ${$}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${b},
|
|
17
17
|
throughput: ${t},
|
|
18
|
-
reserve: ${
|
|
19
|
-
playbackRate: ${
|
|
20
|
-
playbackRateFactor: ${
|
|
21
|
-
forwardBufferHealth: ${
|
|
22
|
-
bitrateFactor: ${
|
|
23
|
-
minBufferToSwitchUp: ${
|
|
24
|
-
droppedVideoMaxQualityLimit: ${
|
|
25
|
-
limitsAreInvalid: ${
|
|
26
|
-
maxQualityLimit: ${
|
|
27
|
-
minQualityLimit: ${
|
|
18
|
+
reserve: ${s},
|
|
19
|
+
playbackRate: ${o},
|
|
20
|
+
playbackRateFactor: ${I},
|
|
21
|
+
forwardBufferHealth: ${n},
|
|
22
|
+
bitrateFactor: ${E},
|
|
23
|
+
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
24
|
+
droppedVideoMaxQualityLimit: ${c},
|
|
25
|
+
limitsAreInvalid: ${M},
|
|
26
|
+
maxQualityLimit: ${a?.max},
|
|
27
|
+
minQualityLimit: ${a?.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
30
|
+
${Object.entries(k).map(([w,$])=>`${w}: ${$}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
|
-
[best track] ${
|
|
34
|
-
[selected track] ${
|
|
35
|
-
`});
|
|
36
|
-
[last selected] ${
|
|
37
|
-
`}),k}return u?.recordSwitch(x),x};var ke=a=>new URL(a).hostname,R;(function(a){a.STOPPED="stopped",a.MANIFEST_READY="manifest_ready",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(R||(R={}));const si=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))};var Ge=async a=>{const e=a.muted;try{await a.play()}catch(t){if(!si(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(i){return si(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};function te(){return s.now()}function Pi(a){return te()-a}function ai(a){const e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=o=>i.test(o);return{resolve:(o,c,l=!1)=>{r(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return l&&(o+=u+"lowLat=1",u="&"),c&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function ks(a,e,t){const i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Et(a,e,t,i){const r=window.XMLHttpRequest;let n,o,c,l=!1,u=0,d,h,p=!1,f="arraybuffer",m=7e3,T=2e3,b=()=>{if(l)return;s.assertNonNullable(d);const N=Pi(d);let W;if(N<T){W=T-N,setTimeout(b,W);return}T*=2,T>m&&(T=m),o&&o.abort(),o=new r,F()};const y=N=>(n=N,w),C=N=>(h=N,w),P=()=>(f="json",w),g=()=>{if(!l){if(--u>=0){b(),i&&i();return}l=!0,h&&h(),t&&t()}},E=N=>(p=N,w),F=()=>{d=te(),o=new r,o.open("get",a);let N=0,W,K=0;const de=()=>(s.assertNonNullable(d),Math.max(d,Math.max(W||0,K||0)));if(n&&o.addEventListener("progress",$=>{const _=te();n.updateChunk&&$.loaded>N&&(n.updateChunk(de(),$.loaded-N),N=$.loaded,W=_)}),c&&(o.timeout=c,o.addEventListener("timeout",()=>g())),o.addEventListener("load",()=>{if(l)return;s.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const _=o.response.byteLength-N;_&&n.updateChunk&&n.updateChunk(de(),_)}o.responseType==="json"&&!Object.values(o.response).length?g():(h&&h(),e(o.response))}else g()}),o.addEventListener("error",()=>{g()}),p){const $=()=>{s.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=te(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=f,o.send(),w},w={withBitrateReporting:y,withParallel:E,withJSONResponse:P,withRetryCount:N=>(u=N,w),withRetryInterval:(N,W)=>(s.isNonNullable(N)&&(T=N),s.isNonNullable(W)&&(m=W),w),withTimeout:N=>(c=N,w),withFinally:C,send:F,abort:()=>{o&&(o.abort(),o=void 0),l=!0,h&&h()}};return w}const As=100,ws=2e3,$s=500;let Ps=class{intervals=[];currentRate=0;logger;constructor(e){this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-$s;if(t-e>ws){let i=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,r+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,c=n.end-n.start;i+=o;const l=n.bytes*o/c;r+=l,n.start=t,n.bytes-=l}}}if(r>0&&i>0){const n=r*8/(i/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>As&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class Cs{pendingQueue=[];activeRequests={};completeRequests={};averageSegmentDuration=2e3;lastPrefetchStart=0;throttleTimeout=null;RETRY_COUNT;TIMEOUT;BITRATE_ESTIMATOR;MAX_PARALLEL_REQUESTS;logger;constructor(e,t,i,r,n){this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=te(),r=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=l=>{e._complete=1,e._responseData=l,e._downloadTime=te()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},c=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Et(t,n,()=>r("error"),c),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=te();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const c=this.pendingQueue.indexOf(e);c!==-1&&this.pendingQueue.splice(c,1),this.logger(`Request not prefetched, starting new request, url=${e}${c===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=i,n._retryCB=r,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Tt=1e4,Mt=3,Ls=6e4,Ds=10,xs=1,Rs=500;class Ns{paused=!1;autoQuality=!0;maxAutoQuality=void 0;buffering=!0;destroyed=!1;videoPlayStarted=!1;lowLatency=!1;rep;bitrate=0;manifest=[];bitrateSwitcher;filesFetcher;sourceBuffer=0;mediaSource;currentManifestEntry;manifestRequest;manifestRefetchTimer;bufferStates=[];downloadRate;sourceJitter=-1;chunkRateEstimator;manifestUrl;urlResolver;params;constructor(e){this.params=e,this.chunkRateEstimator=new Ps(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ai(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ai(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let c=0;c<this.manifest.length;++c)n=this.manifest[c],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!r||n.bitrate>r.bitrate)&&(r=n):(!i||i.bitrate>n.bitrate)&&(i=n));return r||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{ks(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Cs(Mt,Tt,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let n=!1,o=null,c=null,l=null,u=null,d=!1;const h=()=>{const g=n&&(!d||d===this.rep);return g||t("Not running!"),g},p=(g,E,F)=>{l&&l.abort(),l=Et(this.urlResolver.resolve(g,!1),E,F,()=>this._retryCallback()).withTimeout(Tt).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mt).withFinally(()=>{l=null}).send()},f=(g,E,F)=>{s.assertNonNullable(this.filesFetcher),c?.abort(),c=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),E,F,()=>this._retryCallback()).withFinally(()=>{c=null}).send()},m=g=>{const E=i.playbackRate;i.playbackRate!==g&&(t(`Playback rate switch: ${E}=>${g}`),i.playbackRate=g)},T=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const F=te()-1e4;let B=0;for(let M=0;M<this.bufferStates.length;M++){const k=this.bufferStates[M];g=Math.min(g,k.buf),k.ts<F&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${g} drop=${B} jitter=${this.sourceJitter}`);let x=g-xs;this.sourceJitter>=0?x-=this.sourceJitter/2:this.sourceJitter-=1,x>3?m(1.15):x>1?m(1.1):x>.3?m(1.05):m(1)}},y=g=>{let E;const F=()=>E&&E.start?E.start.length:0,B=$=>E.start[$]/1e3,x=$=>E.dur[$]/1e3,M=$=>E.fragIndex+$,k=($,_)=>({chunkIdx:M($),startTS:B($),dur:x($),discontinuity:_}),w=()=>{let $=0;if(E&&E.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=_;this.sourceJitter>1&&(J+=this.sourceJitter-1);let se=E.dur.length-1;for(;se>=0&&(J-=E.dur[se],!(J<=0));--se);$=Math.min(se,E.dur.length-1-Q),$=Math.max($,0)}return k($,!0)},N=$=>{const _=F();if(!(_<=0)){if(s.isNonNullable($)){for(let Q=0;Q<_;Q++)if(B(Q)>$)return k(Q)}return w()}},W=$=>{const _=F(),Q=$?$.chunkIdx+1:0,J=Q-E.fragIndex;if(!(_<=0)){if(!$||J<0||J-_>Ds)return t(`Resync: offset=${J} bChunks=${_} chunk=`+JSON.stringify($)),w();if(!(J>=_))return k(Q-E.fragIndex,!1)}},K=($,_,Q)=>{u&&u.abort(),u=Et(this.urlResolver.resolve($,!0,this.lowLatency),_,Q,()=>this._retryCallback()).withTimeout(Tt).withRetryCount(Mt).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,_)=>{K(g,Q=>{if(!h())return;E=Q;const J=!!E.lowLatency;J!==this.lowLatency&&T(J);let se=0;for(let Ce=0;Ce<E.dur.length;++Ce)se+=E.dur[Ce];se>0&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(N(_))},()=>this._handleNetworkError())},nextChunk:W}},C=()=>{n=!1,c&&c.abort(),l&&l.abort(),u&&u.abort(),s.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:g=>{const{videoElement:E,logger:F}=this.params;let B=y(e.jidxUrl),x,M,k,w,N=0,W,K,de;const $=()=>{W&&(clearTimeout(W),W=void 0);const O=Math.max(Rs,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=N+O,re=te(),he=Math.min(1e4,ae-re);N=re;const Ae=()=>{u||h()&&B.seek(()=>{h()&&(N=te(),_(),$())})};he>0?W=window.setTimeout(()=>{this.paused?$():Ae()},he):Ae()},_=()=>{let O;for(;O=B.nextChunk(w);)w=O,xt(O);const ae=B.nextChunk(k);if(ae){if(k&&ae.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?$():(C(),this._initPlayerWith(e));return}Ce(ae)}else $()},Q=(O,ae)=>{if(!h()||!this.sourceBuffer)return;let re,he,Ae;const at=ne=>{window.setTimeout(()=>{h()&&Q(O,ae)},ne)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),at(100);else{const ne=te(),Le=E.currentTime;!this.paused&&E.buffered.length>1&&K===Le&&ne-de>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),K!==Le&&(K=Le,de=ne);const fe=this._getBufferSizeSec();if(fe>30)F(`Buffered ${fe} seconds; delaying appendBuffer`),at(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:ne,buf:fe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(be){if(be.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Ae=this.sourceBuffer.buffered.length,Ae!==0&&(re=this.sourceBuffer.buffered.start(0),he=Le,he-re>4&&this.sourceBuffer.remove(re,he-3)),at(1e3);else throw be}}},J=()=>{M&&x&&(F([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(k)]),Q(M,function(){M=null,_()}))},se=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),Ce=O=>{h()&&f(se(O),(ae,re)=>{if(h()){if(re/=1e3,M=ae,k=O,o=O.startTS,re){const he=Math.min(10,O.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}J()}},()=>this._handleNetworkError())},xt=O=>{h()&&(s.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(O),!1)))},mt=O=>{h()&&(e.cachedHeader=O,Q(O,()=>{x=!0,J()}))};n=!0,B.seek(O=>{if(h()){if(N=te(),!O){$();return}w=O,!s.isNullable(g)||O.startTS>g?Ce(O):(k=O,_())}},g),e.cachedHeader?mt(e.cachedHeader):p(e.headerUrl,mt,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,s.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return s.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let p,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(f=this._getBufferSizeSec(),m=h/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}p=this._selectQuality(h),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(p,f)=>{const m=te();if(this.chunkRateEstimator.addInterval(p,m,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-p,speed:b}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let o=-1/0,c,l=!0;const u=()=>{let h=n.get();if(h&&c&&this.autoQuality){if(l&&h>c&&Pi(o)<3e4)return;i(h)}l=this.autoQuality};return{updateChunk:(h,p)=>{const f=n.updateChunk(h,p);return f&&u(),f},notifySwitch:h=>{const p=te();h<c&&(o=p),c=h}}}_fetchManifest(e,t,i){this.manifestRequest=Et(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Tt).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){const{videoElement:e}=this.params;Ge(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState(R.PAUSED))})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,n=o=>{const c=[];return o?.length?(o.forEach((l,u)=>{l.video&&r.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,c.push(l))}),c.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.bitrate}),c):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Ls))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Ci{onDroopedVideoFramesLimit$=new s.Subject;subscription=new s.Subscription;log;video;droppedFramesChecker;isAuto;playing=!1;tracks=[];forceChecker$=new s.Subject;isForceCheckCounter=0;prevTotalVideoFrames=0;prevDroppedVideoFrames=0;currentTimer;limitCounts={};currentQuality;maxQualityLimit;connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(s.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=s.interval(this.droppedFramesChecker.checkTime).pipe(s.filter(()=>this.playing),s.filter(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(s.debounce(this.droppedFramesChecker.checkTime)),i=s.merge(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!s.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)};onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}checkDroppedFrames=()=>{const{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,n=1-(i-r)/i;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&s.isHigher(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)};onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){const t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>s.isLower(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const Ut=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement,st=(a,e)=>new s.Observable(t=>{if(!window.IntersectionObserver)return;const i={root:null},r=new IntersectionObserver((o,c)=>{o.forEach(l=>t.next(l.isIntersecting||Ut()))},{...i,...e});r.observe(a);const n=s.fromEvent(document,"visibilitychange").pipe(s.map(o=>!document.hidden||Ut())).subscribe(o=>t.next(o));return()=>{r.unobserve(a),n.unsubscribe}}),Is=[R.PAUSED,R.PLAYING,R.READY],Bs=[R.PAUSED,R.PLAYING,R.READY];class Vs{subscription=new s.Subscription;video;videoState=new z(R.STOPPED);dash;representations$=new s.ValueSubject([]);textTracksManager=new Ne;droppedFramesManager=new Ci;maxSeekBackTime$=new s.ValueSubject(1/0);zeroTime$=new s.ValueSubject(void 0);liveOffset=new zt;log;params;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:s.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};s.merge(this.videoState.stateChangeStarted$.pipe(s.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=Ue(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Ye(this.video);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.representations$.pipe(s.map(r=>r.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===R.READY&&this.videoState.setState(R.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(R.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===I.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(R.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(s.filterChanged(),s.map(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(s.combine({zeroTime:this.zeroTime$.pipe(s.filter(s.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(pt(this.video,this.params.desiredState.isLooped,t)).add(je(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(it(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(st(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const n=r&&s.videoQualityToHeight(r);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case R.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case R.MANIFEST_READY:case R.READY:this.params.desiredState.playbackState.getTransition()?.to===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case R.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case R.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return s.assertNever(r.to)}},t)).add(s.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.observableFrom(["init"])).pipe(s.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),He(this.video)}createLiveDashPlayer(){const e=new Ns({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){const e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&s.isNonNullable(t)?t:Lt(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),n=r?.id,o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(o||n!==c)&&this.setVideoTrack(r),l&&this.setAutoQuality(i),o||l||n!==c){const u=e.find(({track:d})=>d.id===n)?.representation;s.assertNonNullable(u,"Representations missing"),this.dash.startPlay(u,i)}}setVideoTrack(e){const t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;s.assertNonNullable(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===R.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}_dashCb=e=>{switch(e.name){case"buffering":{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:s.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const t=e.manifest,i=[];for(const r of t){const n=r.name??r.index.toString(10),o=Ct(r.name)??s.videoSizeToQuality(r.video),c=r.bitrate/1e3,l={...r.video};if(!o)continue;const u={id:n,quality:o,bitrate:c,size:l};i.push({track:u,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to===R.MANIFEST_READY&&this.videoState.setState(R.MANIFEST_READY);break}case"qualitySwitch":{const t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),s.isNonNullable(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};syncPlayback=()=>{const e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(n)};`}),i===exports.PlaybackState.STOPPED){e!==R.STOPPED&&(this.videoState.startTransitionTo(R.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(R.STOPPED));return}if(t)return;const o=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Bs.includes(e)&&(o||c)){this.prepare();return}if(r?.to!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&Is.includes(e)){this.seek(n.position-this.liveOffset.getTotalPausedTime());return}switch(e){case R.STOPPED:this.videoState.startTransitionTo(R.MANIFEST_READY),this.dash.attachSource(Se(this.params.source.url));return;case R.MANIFEST_READY:this.videoState.startTransitionTo(R.READY),this.prepare();break;case R.READY:if(i===exports.PlaybackState.PAUSED)this.videoState.setState(R.PAUSED);else if(i===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(R.PLAYING);const l=r?.from;l&&l===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play()}return;case R.PLAYING:i===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(R.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case R.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(R.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(Se(this.params.source.url,l))}return;default:return s.assertNever(e)}}}var Z;(function(a){a.VIDEO="video",a.AUDIO="audio",a.TEXT="text"})(Z||(Z={}));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 kt;(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"})(kt||(kt={}));var le;(function(a){a.BYTE_RANGE="byteRange",a.TEMPLATE="template"})(le||(le={}));var L;(function(a){a.NONE="none",a.DOWNLOADING="downloading",a.DOWNLOADED="downloaded",a.PARTIALLY_FED="partially_fed",a.PARTIALLY_EJECTED="partially_ejected",a.FED="fed"})(L||(L={}));var et;(function(a){a.MP4="mp4",a.WEBM="webm"})(et||(et={}));var At;(function(a){a[a.RECTANGULAR=0]="RECTANGULAR",a[a.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",a[a.CUBEMAP=2]="CUBEMAP",a[a.MESH=3]="MESH"})(At||(At={}));var G;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(G||(G={}));var ut=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){const r=a.start(i)*1e3,n=a.end(i)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};class ri{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,n=i.length;r<n;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,n=i.length;r<n;r++){const o=i[r];try{o.callback.call(this,e)}catch(c){Promise.resolve().then(()=>{throw c})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Li extends ri{constructor(){super(),this.listeners||ri.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Di=class{constructor(){Object.defineProperty(this,"signal",{value:new Li,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Di.prototype[Symbol.toStringTag]="AbortController",Li.prototype[Symbol.toStringTag]="AbortSignal");function xi(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Ms(a){typeof a=="function"&&(a={fetch:a});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!xi({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(u,d){let h;d&&d.signal&&(h=d.signal,delete d.signal);const p=new t(u,d);return h&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),p},n.prototype=t.prototype);const o=e;return{fetch:(l,u)=>{const d=n&&n.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(d){let h;try{h=new DOMException("Aborted","AbortError")}catch{h=new Error("Aborted"),h.name="AbortError"}if(d.aborted)return Promise.reject(h);const p=new Promise((f,m)=>{d.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,o(l,u)])}return o(l,u)},Request:n}}const Dt=xi({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ri=Dt?Ms({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Dt?Ri.fetch:window.fetch;Dt?Ri.Request:window.Request;const Ze=Dt?Di:window.AbortController;var Ht=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};const _s=(a,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Fs=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ni=Fs?_s:window.requestIdleCallback,Os=16;let Ni=!1;try{Ni=s.getCurrentBrowser().browser===s.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=Os}catch(a){console.error(a)}class Us{bufferFull$=new s.Subject;error$=new s.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 r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Ni&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!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:s.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(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:s.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:s.assertNever(t)}}}var oi=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};class oe{source;boxParser;type;size32;size64;usertype;content;children;cursor=0;get id(){return this.type}get size(){return this.size32}constructor(e,t){this.source=e,this.boxParser=t,this.children=[];const i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;const r=this.size32?this.size32-8:void 0,n=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,n,r),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 Ii extends oe{}class Hs extends oe{}class js extends oe{majorBrand;minorVersion;compatibleBrands;constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){const r=this.readString(4);this.compatibleBrands.push(r),i-=4}}}class Ys extends oe{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Gs extends oe{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class qs extends oe{data;constructor(e,t){super(e,t),this.data=this.content}}class Pe extends oe{version;flags;constructor(e,t){super(e,t);const i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}}class Bi extends Pe{referenceId;timescale;earliestPresentationTime32;firstOffset32;earliestPresentationTime64;firstOffset64;reserved;referenceCount;segments;get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),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 i=0;i<this.referenceCount;i++){let r=this.readUint32();const n=r>>>31,o=r<<1>>>1,c=this.readUint32();r=this.readUint32();const l=r>>>28,u=r<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:c,SAPType:l,SAPDeltaTime:u})}}}class zs extends oe{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Ws extends oe{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}var Fe;(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"})(Fe||(Fe={}));class Qs extends Pe{stereoMode;constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=Fe.MONOSCOPIC;break;case 1:this.stereoMode=Fe.TOP_BOTTOM;break;case 2:this.stereoMode=Fe.LEFT_RIGHT;break;case 3:this.stereoMode=Fe.STEREO_CUSTOM;break;case 4:this.stereoMode=Fe.RIGHT_LEFT;break}this.cursor+=1}}class Js extends Pe{poseYawDegrees;posePitchDegrees;poseRollDegrees;constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Xs extends Pe{projectionBoundsTop;projectionBoundsBottom;projectionBoundsLeft;projectionBoundsRight;constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Ks extends oe{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class Zs extends Pe{creationTime;modificationTime;trackId;duration;layer;alternateGroup;volume;matrix;width;height;constructor(e,t){super(e,t),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 ea extends oe{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class ta extends oe{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class ia extends Pe{sequenceNumber;constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}}class sa extends oe{parseChildrenBoxes(){return this.scanForBoxes(this.content)}}class aa extends Pe{trackId;baseDataOffset;sampleDescriptionIndex;defaultSampleDuration;defaultSampleSize;defaultSampleFlags;constructor(e,t){super(e,t),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 ra extends Pe{baseMediaDecodeTime32=0;baseMediaDecodeTime64=BigInt(0);get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e,t){super(e,t),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class na extends Pe{sampleCount;dataOffset;firstSampleFlags;sampleDuration=[];sampleSize=[];sampleFlags=[];sampleCompositionTimeOffset=[];optionalFields=0;constructor(e,t){super(e,t),this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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())}}var Y;(function(a){a.FtypBox="ftyp",a.MoovBox="moov",a.MoofBox="moof",a.MdatBox="mdat",a.SidxBox="sidx",a.TrakBox="trak",a.MdiaBox="mdia",a.MfhdBox="mfhd",a.TkhdBox="tkhd",a.TrafBox="traf",a.TfhdBox="tfhd",a.TfdtBox="tfdt",a.TrunBox="trun",a.MinfBox="minf",a.Sv3dBox="sv3d",a.St3dBox="st3d",a.PrhdBox="prhd",a.ProjBox="proj",a.EquiBox="equi",a.UuidBox="uuid",a.UnknownBox="unknown"})(Y||(Y={}));const oa={[Y.FtypBox]:js,[Y.MoovBox]:Ys,[Y.MoofBox]:Gs,[Y.MdatBox]:qs,[Y.SidxBox]:Bi,[Y.TrakBox]:zs,[Y.MdiaBox]:Ks,[Y.MfhdBox]:ia,[Y.TkhdBox]:Zs,[Y.TrafBox]:sa,[Y.TfhdBox]:aa,[Y.TfdtBox]:ra,[Y.TrunBox]:na,[Y.MinfBox]:ea,[Y.Sv3dBox]:Ws,[Y.St3dBox]:Qs,[Y.PrhdBox]:Js,[Y.ProjBox]:ta,[Y.EquiBox]:Xs,[Y.UuidBox]:Hs,[Y.UnknownBox]:Ii};class Oe{options;constructor(e={}){this.options={offset:0,...e}}parse(e){const t=[];let i=this.options.offset;for(;i<e.byteLength;)try{const n=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),o=this.createBox(n,new DataView(e.buffer,e.byteOffset+i));if(!o.size)break;t.push(o),i+=o.size}catch{break}return t}createBox(e,t){const i=oa[e];return i?new i(t,new Oe):new Ii(t,new Oe)}}class Qt{index;constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}}const ca=new TextDecoder("ascii"),ua=a=>ca.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",la=a=>{const e=new Bi(a,new Oe);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,c={status:L.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,c})},da=(a,e)=>{const i=new Oe().parse(a),r=new Qt(i),n=r.findAll("moof"),o=e?r.findAll("uuid"):r.findAll("mdat");if(!(o.length&&n.length))return null;const c=n[0],l=o[o.length-1],u=c.source.byteOffset,h=l.source.byteOffset-c.source.byteOffset+l.size;return new DataView(a.buffer,u,h)},ha=(a,e)=>{const i=new Oe().parse(a),n=new Qt(i).findAll("traf"),o=n[n.length-1].children.find(h=>h.type==="tfhd"),c=n[n.length-1].children.find(h=>h.type==="tfdt"),l=n[n.length-1].children.find(h=>h.type==="trun");let u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((h,p)=>h+p,0):u=o.defaultSampleDuration*l.sampleCount,(Number(c.baseMediaDecodeTime)+u)/e*1e3},fa=a=>{const e={is3dVideo:!1,stereoMode:0,projectionType:At.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Oe().parse(a),r=new Qt(i);if(r.find("sv3d")){e.is3dVideo=!0;const o=r.find("st3d");o&&(e.stereoMode=o.stereoMode);const c=r.find("prhd");c&&(e.projectionData.pose.yaw=c.poseYawDegrees,e.projectionData.pose.pitch=c.posePitchDegrees,e.projectionData.pose.roll=c.poseRollDegrees);const l=r.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},pa={validateData:ua,parseInit:fa,getIndexRange:()=>{},parseSegments:la,parseFeedableSegmentChunk:da,getSegmentEndTime:ha};var S;(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"})(S||(S={}));var v;(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"})(v||(v={}));const ci={[S.EBML]:{type:v.Master},[S.EBMLVersion]:{type:v.UnsignedInteger},[S.EBMLReadVersion]:{type:v.UnsignedInteger},[S.EBMLMaxIDLength]:{type:v.UnsignedInteger},[S.EBMLMaxSizeLength]:{type:v.UnsignedInteger},[S.DocType]:{type:v.String},[S.DocTypeVersion]:{type:v.UnsignedInteger},[S.DocTypeReadVersion]:{type:v.UnsignedInteger},[S.Void]:{type:v.Binary},[S.Segment]:{type:v.Master},[S.SeekHead]:{type:v.Master},[S.Seek]:{type:v.Master},[S.SeekID]:{type:v.Binary},[S.SeekPosition]:{type:v.UnsignedInteger},[S.Info]:{type:v.Master},[S.TimestampScale]:{type:v.UnsignedInteger},[S.Duration]:{type:v.Float},[S.Tracks]:{type:v.Master},[S.TrackEntry]:{type:v.Master},[S.Video]:{type:v.Master},[S.Projection]:{type:v.Master},[S.ProjectionType]:{type:v.UnsignedInteger},[S.ProjectionPrivate]:{type:v.Master},[S.Chapters]:{type:v.Master},[S.Cluster]:{type:v.Master},[S.Timestamp]:{type:v.UnsignedInteger},[S.SilentTracks]:{type:v.Master},[S.SilentTrackNumber]:{type:v.UnsignedInteger},[S.Position]:{type:v.UnsignedInteger},[S.PrevSize]:{type:v.UnsignedInteger},[S.SimpleBlock]:{type:v.Binary},[S.BlockGroup]:{type:v.Master},[S.EncryptedBlock]:{type:v.Binary},[S.Attachments]:{type:v.Master},[S.Tags]:{type:v.Master},[S.Cues]:{type:v.Master},[S.CuePoint]:{type:v.Master},[S.CueTime]:{type:v.UnsignedInteger},[S.CueTrackPositions]:{type:v.Master},[S.CueTrack]:{type:v.UnsignedInteger},[S.CueClusterPosition]:{type:v.UnsignedInteger},[S.CueRelativePosition]:{type:v.UnsignedInteger},[S.CueDuration]:{type:v.UnsignedInteger},[S.CueBlockNumber]:{type:v.UnsignedInteger},[S.CueCodecState]:{type:v.UnsignedInteger},[S.CueReference]:{type:v.Master},[S.CueRefTime]:{type:v.UnsignedInteger}},Vi=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=wt(a,t),r=i in ci,n=r?ci[i].type:v.Binary,o=a.getUint8(t);let c=0;o&128?c=1:o&64?c=2:o&32?c=3:o&16?c=4:o&8?c=5:o&4?c=6:o&2?c=7:o&1&&(c=8);const l=new DataView(a.buffer,a.byteOffset+t+1,c-1),u=o&255>>c,d=wt(l),h=u*2**((c-1)*8)+d,p=t+c;let f;return p+h>a.byteLength?f=new DataView(a.buffer,a.byteOffset+p):f=new DataView(a.buffer,a.byteOffset+p,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:p,tagSize:p+h,value:f,valueSize:h}},wt=(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},Te=(a,e)=>{switch(e){case v.SignedInteger:return a.getInt8(0);case v.UnsignedInteger:return wt(a);case v.Float:return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case v.String:return new TextDecoder("ascii").decode(a);case v.UTF8:return new TextDecoder("utf-8").decode(a);case v.Date:return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case v.Master:return a;case v.Binary:return a;default:s.assertNever(e)}},tt=(a,e)=>{let t=0;for(;t<a.byteLength;){const i=new DataView(a.buffer,a.byteOffset+t),r=Vi(i);if(!e(r))return;r.type===v.Master&&tt(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},ma=a=>{if(a.getUint32(0)!==S.EBML)return!1;let e,t,i;const r=Vi(a);return tt(r.value,({tag:n,type:o,value:c})=>(n===S.EBMLReadVersion?e=Te(c,o):n===S.DocType?t=Te(c,o):n===S.DocTypeReadVersion&&(i=Te(c,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Mi=[S.Info,S.SeekHead,S.Tracks,S.TrackEntry,S.Video,S.Projection,S.ProjectionType,S.ProjectionPrivate,S.Chapters,S.Cluster,S.Cues,S.Attachments,S.Tags],Sa=[S.Timestamp,S.SilentTracks,S.SilentTrackNumber,S.Position,S.PrevSize,S.SimpleBlock,S.BlockGroup,S.EncryptedBlock],ba=a=>{let e,t,i,r,n=!1,o=!1,c=!1,l,u,d=!1;const h=0;return tt(a,({tag:p,type:f,value:m,valueSize:T})=>{if(p===S.SeekID){const b=Te(m,f);u=wt(b)}else p!==S.SeekPosition&&(u=void 0);return p===S.Segment?(e=m.byteOffset,t=m.byteOffset+T):p===S.Info?n=!0:p===S.SeekHead?o=!0:p===S.TimestampScale?i=Te(m,f):p===S.Duration?r=Te(m,f):p===S.SeekPosition&&u===S.Cues?l=Te(m,f):p===S.Tracks?tt(m,({tag:b,type:y,value:C})=>b===S.ProjectionType?(d=Te(C,y)===1,!1):!0):n&&o&&Mi.includes(p)&&(c=!0),!c}),s.assertNonNullable(e,"Failed to parse webm Segment start"),s.assertNonNullable(t,"Failed to parse webm Segment end"),s.assertNonNullable(r,"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(r/1e9*i*1e3),cuesSeekPosition:l,is3dVideo:d,stereoMode:h,projectionType:At.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ga=a=>{if(s.isNullable(a.cuesSeekPosition))return;const e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ya=(a,e)=>{let t=!1,i=!1;const r=c=>s.isNonNullable(c.time)&&s.isNonNullable(c.position),n=[];let o;return tt(a,({tag:c,type:l,value:u})=>{switch(c){case S.Cues:t=!0;break;case S.CuePoint:o&&r(o)&&n.push(o),o={};break;case S.CueTime:o&&(o.time=Te(u,l));break;case S.CueTrackPositions:break;case S.CueClusterPosition:o&&(o.position=Te(u,l));break;default:t&&Mi.includes(c)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((c,l)=>{const{time:u,position:d}=c,h=n[l+1];return{status:L.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},va=a=>{let e=0,t=!1;try{tt(a,i=>i.tag===S.Cluster?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Sa.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=[S.SimpleBlock,S.BlockGroup,S.EncryptedBlock].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Ta={validateData:ma,parseInit:ba,getIndexRange:ga,parseSegments:ya,parseFeedableSegmentChunk:va},Ea=a=>{if(a.includes("/")){const e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)},ui=a=>{if(!a.startsWith("P"))return;const e=(o,c)=>{const l=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(l)?0:l)*c},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),r=i?.[1]==="-"?-1:1,n={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Je=(a,e)=>{let t=a;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(c,l)=>s.isNullable(n)?c:s.isNullable(l)?n:n.padStart(parseInt(l,10),"0"))}return t},ka=(a,e)=>{const i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},n=i.children[0],o=n.getElementsByTagName("Period")[0],c=n.querySelector("BaseURL")?.textContent?.trim()??"",l=o.children,u=n.getAttribute("type")==="dynamic",d=n.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0;let p;const f=n.getAttribute("mediaPresentationDuration"),m=o.getAttribute("duration"),b=n.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=ui(f);else if(m){const g=ui(m);s.isNonNullable(g)&&(p=g)}else b&&(p=parseInt(b,10));let y=0;const C=n.getAttribute("profiles")?.split(",")??[],P=C.includes(kt.WEBM_AS_IN_FFMPEG)||C.includes(kt.WEBM_AS_IN_SPEC)?et.WEBM:et.MP4;for(const g of l){const E=g.getAttribute("mimeType"),F=g.getAttribute("codecs"),B=g.getAttribute("contentType")??E?.split("/")[0],x=g.getAttribute("profiles")?.split(",")??[],M=g.querySelectorAll("Representation"),k=g.querySelector("SegmentTemplate");if(B===Z.TEXT){for(const w of M){const N=w.getAttribute("id")||"",W=g.getAttribute("lang"),K=g.getAttribute("label"),de=w.querySelector("BaseURL")?.textContent?.trim()??"",$=new URL(de||c,e).toString(),_=N.includes("_auto");r[Z.TEXT].push({id:N,lang:W,label:K,isAuto:_,kind:Z.TEXT,url:$})}continue}for(const w of M){const N=w.getAttribute("mimeType")??E,W=w.getAttribute("codecs")??F??"",K=w.getAttribute("contentType")??N?.split("/")[0]??B,de=g.getAttribute("profiles")?.split(",")??[],$=parseInt(w.getAttribute("width")??"",10),_=parseInt(w.getAttribute("height")??"",10),Q=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,J=w.getAttribute("frameRate")??"",se=w.getAttribute("quality")??void 0,Ce=J?Ea(J):void 0,xt=w.getAttribute("id")??(y++).toString(10),mt=K==="video"?`${_}p`:K==="audio"?`${Q}Kbps`:W,O=`${xt}@${mt}`,ae=w.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(ae||c,e).toString(),he=[...C,...x,...de];let Ae;const at=w.querySelector("SegmentBase"),ne=w.querySelector("SegmentTemplate")??k;if(at){const fe=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[be,Rt]=fe.split("-").map(qe=>parseInt(qe,10)),De={from:be,to:Rt},rt=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[Nt,St]=rt?rt.split("-").map(qe=>parseInt(qe,10)):[],nt=rt?{from:Nt,to:St}:void 0;Ae={type:le.BYTE_RANGE,url:re,initRange:De,indexRange:nt}}else if(ne){const fe={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},be=parseInt(ne.getAttribute("timescale")??"",10),Rt=ne.getAttribute("initialization")??"",De=ne.getAttribute("media"),rt=parseInt(ne.getAttribute("startNumber")??"",10)??1,Nt=Je(Rt,fe);if(!De)throw new ReferenceError("No media attribute in SegmentTemplate");const St=ne.querySelectorAll("SegmentTimeline S")??[],nt=[];let qe=0,It="",Bt=0;if(St.length){let bt=rt,pe=0;for(const ze of St){const ge=parseInt(ze.getAttribute("d")??"",10),Ie=parseInt(ze.getAttribute("r")??"",10)||0,gt=parseInt(ze.getAttribute("t")??"",10);pe=Number.isFinite(gt)?gt:pe;const Vt=ge/be*1e3,Gi=pe/be*1e3;for(let yt=0;yt<Ie+1;yt++){const qi=Je(De,{...fe,segmentNumber:bt.toString(10),segmentTime:(pe+yt*ge).toString(10)}),Kt=(Gi??0)+yt*Vt,zi=Kt+Vt;bt++,nt.push({time:{from:Kt,to:zi},url:qi})}pe+=(Ie+1)*ge,qe+=(Ie+1)*Vt}Bt=pe/be*1e3,It=Je(De,{...fe,segmentNumber:bt.toString(10),segmentTime:pe.toString(10)})}else if(s.isNonNullable(p)){const pe=parseInt(ne.getAttribute("duration")??"",10)/be*1e3,ze=Math.ceil(p/pe);let ge=0;for(let Ie=1;Ie<ze;Ie++){const gt=Je(De,{...fe,segmentNumber:Ie.toString(10),segmentTime:ge.toString(10)});nt.push({time:{from:ge,to:ge+pe},url:gt}),ge+=pe}Bt=ge,It=Je(De,{...fe,segmentNumber:ze.toString(10),segmentTime:ge.toString(10)})}const Yi={time:{from:Bt,to:1/0},url:It};Ae={type:le.TEMPLATE,baseUrl:re,segmentTemplateUrl:De,initUrl:Nt,totalSegmentsDurationMs:qe,segments:nt,nextSegmentBeyondManifest:Yi,timescale:be}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!K||!N)continue;const Le={video:Z.VIDEO,audio:Z.AUDIO,text:Z.TEXT}[K];Le&&r[Le].push({id:O,kind:Le,segmentReference:Ae,profiles:he,duration:p,bitrate:Q,mime:N,codecs:W,width:$,height:_,fps:Ce,quality:se})}}return{dynamic:u,liveAvailabilityStartTime:h,duration:p,container:P,representations:r}},Aa=({id:a,width:e,height:t,bitrate:i,fps:r,quality:n})=>{const o=(n?Ct(n):void 0)??s.videoSizeToQuality({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},wa=({id:a,bitrate:e})=>({id:a,bitrate:e}),$a=(a,e,t)=>{const i=e.indexOf(t);return a.at(Math.round(a.length*i/e.length))??a.at(-1)},Pa=({id:a,lang:e,label:t,url:i,isAuto:r})=>({id:a,url:i,isAuto:r,type:"internal",language:e,label:t}),li=a=>"url"in a,We=a=>a.type===le.TEMPLATE,jt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);class di{currentSegmentLength$=new s.ValueSubject(0);onLastSegment$=new s.ValueSubject(!1);fullyBuffered$=new s.ValueSubject(!1);playingRepresentation$=new s.ValueSubject(void 0);playingRepresentationInit$=new s.ValueSubject(void 0);error$=new s.Subject;gaps=[];subscription=new s.Subscription;kind;container;containerParser;initData;parsedInitData;representations;segments;allInitsLoaded=!1;activeSegments=new Set;mediaSource;playingRepresentationId;downloadingRepresentationId;switchingToRepresentationId;sourceBuffer;downloadAbortController=new Ze;destroyAbortController=new Ze;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;loadByteRangeSegmentsTimeoutId=0;constructor(e,t,i,r,{fetcher:n,tuning:o,getCurrentPosition:c,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:d}){switch(this.fetcher=n,this.tuning=o,this.compatibilityMode=u,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=c,this.isActiveLowLatency=l,this.isLive=!!d?.dynamic,this.container=i,i){case et.MP4:this.containerParser=pa;break;case et.WEBM:this.containerParser=Ta;break;default:s.assertNever(i)}this.initData=new Map(r.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}startWith=s.abortable(this.destroyAbortController.signal,async function*(e){const t=this.representations.get(e);s.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 Us(this.sourceBuffer),this.subscription.add(s.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},o=>this.error$.next({id:"SegmentEjection",category:s.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:o}))),this.subscription.add(s.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:s.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(o=>{if(!this.sourceBuffer)return;const c=Math.min(this.bufferLimit,oi(this.sourceBuffer.buffered)*.8);this.bufferLimit=c,this.pruneBuffer(this.getCurrentPosition(),o)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(o=>this.error$.next(o))),yield this.loadInit(t,"high",!0);const i=this.initData.get(t.id),r=this.segments.get(t.id),n=this.parsedInitData.get(t.id);s.assertNonNullable(i,"No init buffer for starting representation"),s.assertNonNullable(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(n))}.bind(this));switchTo=s.abortable(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;const t=this.representations.get(e);s.assertNonNullable(t,`No such representation ${e}`);let i=this.segments.get(e),r=this.initData.get(e);if(s.isNullable(r)||s.isNullable(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),s.assertNonNullable(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);const n=this.getCurrentPosition();s.isNonNullable(n)&&(this.isLive||(i.forEach(o=>o.status=L.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 Ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(s.isNullable(e)||s.isNullable(this.downloadingRepresentationId)||s.isNullable(this.playingRepresentationId)||s.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(s.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=ut(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&oi(this.sourceBuffer.buffered)>=this.bufferLimit){const u=ut(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let c=[];if(!this.activeSegments.size&&(c=this.selectForwardBufferSegments(i,t.segmentReference.type,n),c.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(c.includes(r))u="high";else{const d=c.at(0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(c,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===L.FED&&!c.length&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const l=i.at(-1);l&&l.status===L.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===l))}searchGaps(e,t){this.gaps=[];let i=0;const r=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+r}),i=n.time.to;s.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,r=[];let n=0,o=t.length-1;do r.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()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e?.representations[this.kind].find(r=>r.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=s.abortable(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(const c of this.representations.keys()){const l=e.find(h=>h.id===c);l&&this.representations.set(c,l);const u=this.representations.get(c);if(!u||!We(u.segmentReference))return;const d=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,d)}const t=this.switchingToRepresentationId??this.downloadingRepresentationId,i=this.representations.get(t);s.assertNonNullable(i);const r=this.segments.get(t);s.assertNonNullable(r,"No segments for starting representation");const n=this.initData.get(t);if(s.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(r,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||!We(t.segmentReference))return;const i=t.segmentReference.segments.map(c=>({...c,status:L.NONE,size:void 0})),r=this.segments.get(t.id)??[],n=r.at(-1)?.time.to??0,o=i?.findIndex(c=>Math.floor(n)>=Math.floor(c.time.from)&&Math.floor(n)<=Math.floor(c.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,c)}else{const c=i.slice(o+1);this.segments.set(t.id,[...r,...c])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(const t of this.representations.values()){const i=t.segmentReference;if(!We(i))return;const r=Math.round(e.segment.time.to*i.timescale/1e3).toString(10),n=Je(i.segmentTemplateUrl,{segmentTime:r}),o=this.segments.get(t.id)??[],c=o.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));c&&(c.time.to=e.segment.time.to),!!o.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||o.push({status:L.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(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{const T=p<=i&&f>=i,b=p>i||T||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&p<=i+y||f<=i+y;return(h===L.NONE||h===L.PARTIALLY_EJECTED&&b&&C&&this.sourceBuffer&&!Ht(this.sourceBuffer.buffered,i))&&b&&C});if(r===-1)return[];if(t!==le.BYTE_RANGE)return e.slice(r,r+1);const n=e;let o=0,c=0;const l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let h=r;h<n.length&&(o<=u||c<=d);h++){const p=n[h];if(o+=p.byte.to+1-p.byte.from,c+=p.time.to+1-p.time.from,p.status===L.NONE||p.status===L.PARTIALLY_EJECTED)l.push(p);else break}return l}async loadSegments(e,t,i="auto"){t.segmentReference.type===le.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=L.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:n,url:o,signal:c,onProgress:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&c&&(await s.abortable(c,async function*(){const d=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),c.aborted&&this.abortActiveSegments([e]));try{const d=await this.fetcher.fetch(o,{range:n,signal:c,onProgress:l,priority:i,isLowLatency:this.isActiveLowLatency()});if(!d)return;const h=new DataView(d);if(this.isActiveLowLatency()){const p=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(h,p)}l&&r.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(h,c),r.segment.status=L.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),jt(d)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const l of e)l.status=L.DOWNLOADING,this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:n,signal:o,onProgress:c}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await s.abortable(o,async function*(){const l=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),s.fromEvent(window,"online").pipe(s.once()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:r,onProgress:c,signal:o,priority:i}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),jt(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(We(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:n}=this.downloadAbortController;return{url:i,range:r,signal:n,onProgress:(c,l)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:l,signal:n,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!We(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 r=i.toString(),{signal:n}=this.downloadAbortController,o=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!n.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:n,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:n,onProgress:l,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const c of this.activeSegments){const{segment:l}=c;if(c.representationId===t){if(n.aborted){r();continue}if(c.loadedBytes=i,c.loadedBytes>c.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+c.feedingBytes,c.loadedBytes-c.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(u,this.isLive);d?.byteLength&&(l.status=L.PARTIALLY_FED,c.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),c.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const c=this.representations.get(t);if(!c)return;const l=c.segmentReference.type,u=e.byteLength;for(const d of this.activeSegments){const{segment:h}=d,p=l===le.BYTE_RANGE,f=p?h.byte.to-h.byte.from+1:u;if(d.representationId!==t||!(!p||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const T=p?h.byte.from-i:0,b=p?h.byte.to-i:e.byteLength,y=T<r,C=b<=r;if(h.status===L.DOWNLOADING&&y&&C){h.status=L.DOWNLOADED;const P=new DataView(e.buffer,e.byteOffset+T,f);this.sourceBufferTaskQueue.append(P,n).then(g=>g&&!n.aborted?this.onSegmentFullyAppended(d,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(d.loadedBytes=Math.min(f,r-T),d.loadedBytes>d.feedingBytes)){const P=new DataView(e.buffer,e.byteOffset+T+d.feedingBytes,d.loadedBytes-d.feedingBytes),g=d.loadedBytes===f?P:this.containerParser.parseFeedableSegmentChunk(P);g?.byteLength&&(h.status=L.PARTIALLY_FED,d.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,n).then(E=>{if(n.aborted)o();else if(E)d.fedBytes+=g.byteLength,d.fedBytes===f&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<f)return;o()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=L.FED,li(e.segment)&&(e.segment.size=e.fedBytes);for(const i of this.representations.values())if(i.id!==t)for(const r of this.segments.get(i.id)??[])r.status===L.FED&&r.time.from===e.segment.time.from&&r.time.to===e.segment.time.to&&(r.status=L.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===L.PARTIALLY_FED||e.status===L.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=L.NONE),e.status=L.PARTIALLY_EJECTED):e.status=L.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[r,n]of this.initData.entries()){const o=n instanceof Promise;t||=o,n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=ni(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?s.abortable(this.destroyAbortController.signal,async function*(){const c=s.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async c=>{if(!c)return;const{init:l,dataView:u,segments:d}=c,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h);let p=d;this.isLive&&We(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,c=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:s.ErrorCategory.WTF,message:"loadInit threw",thrown:c})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||s.isNullable(e)||this.sourceBuffer.updating)return!1;let r=0,n=1/0,o=-1/0,c=!1;const l=u=>{n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const d=li(u)?u.size??0:u.byte.to-u.byte.from;r+=d};for(const u of this.segments.values())for(const d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;d.status===L.FED&&l(d)}if(c=isFinite(n)&&isFinite(o),!c){r=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;d.status===L.FED&&l(d)}}if(c=isFinite(n)&&isFinite(o),!c)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const d=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const p of this.segments.values())for(const f of p)if(f.status===L.NONE&&Math.round(f.time.from)<=Math.round(d)&&Math.round(f.time.to)>=Math.round(h)){n=d,o=h;break}}if(c=isFinite(n)&&isFinite(o),!c&&i){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const h of d)h.time.from>e+u&&h.status===L.FED&&l(h)}return c=isFinite(n)&&isFinite(o),c?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 r={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,c=this.sourceBuffer.buffered.end(n)*1e3;if(!(c<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&c>=i.time.to){r=void 0;break}c>i.time.from&&c<i.time.to&&(r.from=c),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ni(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:s.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(s.isNullable(this.sourceBuffer)||s.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==L.FED&&n!==L.PARTIALLY_EJECTED)continue;const o=Math.floor(r.time.from),c=Math.ceil(r.time.to),l=e.some(d=>d.from-t<=o&&d.to+t>=c),u=e.filter(d=>o>=d.from-t&&o<=d.to+t||c>=d.from-t&&c<=d.to+t);l||(u.length===1||this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status=L.PARTIALLY_EJECTED:r.status=L.NONE)}}}var Yt=a=>{const e=new URL(a);return e.searchParams.set("quic","1"),e.toString()},Ca=a=>{const e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?exports.HttpConnectionType.HTTP1:e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}},Ke;(function(a){a[a.HEADER=0]="HEADER",a[a.PARAM=1]="PARAM"})(Ke||(Ke={}));class La{throughputEstimator;requestQuic;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);abortAllController=new Ze;subscription=new s.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}=Ca(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchManifest=s.abortable(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Yt(t));const i=yield ht(t,{signal:this.abortAllController.signal}).catch(ot);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));fetch=s.abortable(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?Ke.HEADER:Ke.PARAM,range:i,onProgress:r,priority:n="auto",signal:o,measureThroughput:c=!0,isLowLatency:l=!1}={}){let u=e;const d=new Headers;if(i)switch(t){case Ke.HEADER:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case Ke.PARAM:{const x=new URL(u,location.href);x.searchParams.append("bytes",`${i.from}-${i.to}`),u=x.toString();break}default:s.assertNever(t)}this.requestQuic&&(u=Yt(u));let h=this.abortAllController.signal,p;if(o){const x=new Ze;if(p=s.merge(s.fromEvent(this.abortAllController.signal,"abort"),s.fromEvent(o,"abort")).subscribe(()=>{try{x.abort()}catch(M){ot(M)}}),this.abortAllController.signal.aborted||o.aborted)try{x.abort()}catch(M){ot(M)}h=x.signal}const f=s.now(),m=yield ht(u,{priority:n,headers:d,signal:h}).catch(ot),T=s.now();if(!m)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(T-f),!m.ok||!m.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!r&&!c)return p?.unsubscribe(),m.arrayBuffer();const[b,y]=m.body.tee(),C=b.getReader();c&&this.throughputEstimator?.trackStream(y,l);let P=0,g=new Uint8Array(0),E=!1;const F=x=>{p?.unsubscribe(),E=!0,ot(x)},B=s.abortable(h,async function*({done:x,value:M}){if(P===0&&this.lastRequestFirstBytes$.next(s.now()-f),h.aborted){p?.unsubscribe();return}if(!x&&M){const k=new Uint8Array(g.length+M.length);k.set(g),k.set(M,g.length),g=k,P+=M.byteLength,r?.(new DataView(g.buffer),P),yield C?.read().then(B,F)}}.bind(this));return yield C?.read().then(B,F),p?.unsubscribe(),E?null:g.buffer}.bind(this));async fetchRepresentation(e,t,i="auto"){const{type:r}=e;switch(r){case le.BYTE_RANGE:return await this.fetchByteRangeRepresentation(e,t,i)??null;case le.TEMPLATE:return await this.fetchTemplateRepresentation(e,i)??null;default:s.assertNever(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}fetchByteRangeRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t,i){if(e.type!==le.BYTE_RANGE)return null;const{from:r,to:n}=e.initRange;let o=r,c=n,l=!1,u,d;e.indexRange&&(u=e.indexRange.from,d=e.indexRange.to,l=n+1===u,l&&(o=Math.min(u,r),c=Math.max(d,n))),o=Math.min(o,0);const h=yield this.fetch(e.url,{range:{from:o,to:c},priority:i,measureThroughput:!1});if(!h)return null;const p=new DataView(h,r-o,n-o+1);if(!t.validateData(p))throw new Error("Invalid media file");const f=t.parseInit(p),m=e.indexRange??t.getIndexRange(f);if(!m)throw new ReferenceError("No way to load representation index");let T;if(l)T=new DataView(h,m.from-o,m.to-m.from+1);else{const y=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!y)return null;T=new DataView(y)}const b=t.parseSegments(T,f,m);return{init:f,dataView:new DataView(h),segments:b}}.bind(this));fetchTemplateRepresentation=s.abortable(this.abortAllController.signal,async function*(e,t){if(e.type!==le.TEMPLATE)return null;const i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(o=>({...o,status:L.NONE,size:void 0})),dataView:new DataView(r)}:null}.bind(this))}const ot=a=>{if(!jt(a))throw a},Xe=1e3,$t=(a,e,t)=>t*e+(1-t)*a,_i=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Da=(a,e,t,i)=>{let r=0,n=t;const o=_i(a,e),c=e<i?e:i;for(let l=0;l<c;l++)a[n]>o?r++:r--,n=(a.length+n-1)%a.length;return Math.abs(r)===c};class Jt{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 s.ValueSubject(e.initial),this.debounced$=new s.ValueSubject(e.initial);const t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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 c=0;c<this.pastMeasures.length;c++)this.pastMeasures[c]!==void 0&&(t+=(this.pastMeasures[c]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;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)&&(s.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 xa extends Jt{slow;fast;constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Ra extends Jt{emaSmoothed;constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=_i(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);const i=Da(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Na extends Jt{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?$t(this.smoothed,e,this.params.emaAlpha):e}}class Gt{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new xa({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ra({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 Na({initial:e,label:"liveEdgeDelay",...t})}}const Ia=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)},Be=()=>window.ManagedMediaSource||window.MediaSource,Fi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Ba=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Va=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,hi=["timeupdate","progress","play","seeked","stalled","waiting"];var ue;(function(a){a.NONE="none",a.MANIFEST_READY="manifest_ready",a.REPRESENTATIOS_READY="representations_ready",a.RUNNING="running"})(ue||(ue={}));let Ma=class{element=null;manifestUrlString="";source=null;manifest=null;tuning;videoBufferManager;audioBufferManager;bufferManagers;throughputEstimator;subscription=new s.Subscription;representationSubscription=new s.Subscription;fetcher;state$=new z(ue.NONE);currentVideoRepresentation$=new s.ValueSubject(void 0);currentVideoRepresentationInit$=new s.ValueSubject(void 0);currentVideoSegmentLength$=new s.ValueSubject(0);currentAudioSegmentLength$=new s.ValueSubject(0);error$=new s.Subject;lastConnectionType$=new s.ValueSubject(void 0);lastConnectionReused$=new s.ValueSubject(void 0);lastRequestFirstBytes$=new s.ValueSubject(void 0);isLive$=new s.ValueSubject(!1);liveDuration$=new s.ValueSubject(0);liveAvailabilityStartTime$=new s.ValueSubject(void 0);bufferLength$=new s.ValueSubject(0);liveLoadBufferLength$=new s.ValueSubject(0);livePositionFromPlayer$=new s.ValueSubject(0);liveEstimatedDelay;timeInWaiting=0;isActiveLowLatency=!1;isUpdatingLive=!1;isJumpGapAfterSeekLive=!1;liveLastSeekOffset=0;forceEnded$=new s.Subject;gapWatchdogStarted=!1;gapWatchdogSubscription;stallWatchdogSubscription;destroyController=new Ze;constructor(e){this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new La({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Gt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}initManifest=s.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(ue.MANIFEST_READY),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState(ue.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:s.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));updateManifest=s.abortable(this.destroyController.signal,async function*(){const e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(r=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:s.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:r})});if(!e)return null;let t;try{t=ka(e??"",this.manifestUrlString)}catch(r){this.error$.next({id:"ManifestParsing",category:s.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:r})}if(!t)return null;const i=({kind:r,mime:n,codecs:o})=>!!(this.element?.canPlayType?.(n)&&Be()?.isTypeSupported?.(`${n}; codecs="${o}"`)||r===Z.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(([r,n])=>[r,n.filter(i)]))}}.bind(this));async seekLive(e){s.assertNonNullable(this.element);const t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=Se(this.manifestUrlString,t,X.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initRepresentations=s.abortable(this.destroyController.signal,async function*(e,t,i){s.assertNonNullable(this.manifest),s.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ue.REPRESENTATIOS_READY);const r=f=>{this.representationSubscription.add(s.fromEvent(f,"error").pipe(s.filter(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Va():new MediaSource;const n=document.createElement("source");if(r(n),n.src=URL.createObjectURL(this.source),this.element.appendChild(n),this.tuning.useManagedMediaSource&&Fi())if(i){const f=document.createElement("source");r(f),f.type="application/x-mpegurl",f.src=i.url,this.element.appendChild(f)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const o={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 di(Z.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,o),this.bufferManagers=[this.videoBufferManager],s.isNonNullable(t)&&(this.audioBufferManager=new di(Z.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,o),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(s.interval(Xe).subscribe(f=>{if(this.element?.paused){const m=ei(this.manifestUrlString,X.DASH_CMAF_OFFSET_P);this.manifestUrlString=Se(this.manifestUrlString,m+Xe,X.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(s.merge(...hi.filter(f=>f!=="waiting").map(f=>s.fromEvent(this.element,f))).pipe(s.map(f=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),s.filterChanged(),s.filter(f=>!!f),s.tap(f=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(s.filter(m=>this.isActiveLowLatency&&!!m)).subscribe(m=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(m=>{if(!this.isActiveLowLatency)return;const T=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,C=m-T;let P=1+Math.sign(C)*y;Math.abs(C)<b?P=1:Math.abs(C)>b*2&&(P=1+Math.sign(C)*y*2),Ia(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let T=0;if(m){const b=(this.element?.currentTime??0)*1e3;T=Math.min(...this.bufferManagers.map(C=>C.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let f=0;this.representationSubscription.add(s.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(s.throttle(Xe)).subscribe(async({liveLoadBufferLength:m,bufferLength:T})=>{if(s.assertNonNullable(this.element),this.isUpdatingLive)return;const b=this.element.playbackRate,y=ei(this.manifestUrlString,X.DASH_CMAF_OFFSET_P),C=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(C,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),g=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,F=this.isActiveLowLatency?T:m;let B=ye.None;if(this.isActiveLowLatency?B=ye.ActiveLowLatency:F<P+E&&F>=P?B=ye.LiveWithTargetOffset:y!==0&&F<P&&(B=ye.LiveForwardBuffering),isFinite(m)&&(f=m>f?m:f),B===ye.LiveForwardBuffering||B===ye.LiveWithTargetOffset){const x=f-(P+g),M=this.normolizeLiveOffset(Math.trunc(y+x/b)),k=Math.abs(M-y);let w;!m||k<=this.tuning.dashCmafLive.offsetCalculationError?w=y:M>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=M:w=0,this.manifestUrlString=Se(this.manifestUrlString,w,X.DASH_CMAF_OFFSET_P)}B!==ye.None&&B!==ye.ActiveLowLatency&&(f=0,this.updateLive())}))}const c=s.merge(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe(s.map(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),l=s.merge(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe(s.map(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add(s.merge(this.forceEnded$,s.combine({allBuffersFull:c,someBufferEnded:l}).pipe(s.filter(({allBuffersFull:f,someBufferEnded:m})=>f&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{this.source?.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:s.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(s.merge(...this.bufferManagers.map(f=>f.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(f=>this.source?.addEventListener("sourceopen",f)));const u=this.manifest.duration??0,d=(f,m)=>Math.max(f,m.duration??0),h=this.manifest.representations.audio.reduce(d,u),p=this.manifest.representations.video.reduce(d,u);(h||p)&&(this.source.duration=Math.max(h,p)/1e3),this.audioBufferManager&&s.isNonNullable(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState(ue.REPRESENTATIOS_READY)}.bind(this));initBuffer(){s.assertNonNullable(this.element),this.state$.setState(ue.RUNNING),this.subscription.add(s.merge(...hi.map(e=>s.fromEvent(this.element,e)),s.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:s.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(s.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(s.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ht(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);const e=()=>{if(this.element){if(this.timeInWaiting+=Xe,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=s.interval(Xe).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:s.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{[Z.VIDEO]:this.videoBufferManager,[Z.AUDIO]:this.audioBufferManager,[Z.TEXT]:null}[e]?.switchTo(t)}seek(e,t){s.assertNonNullable(this.element),s.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),Ht(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?.querySelectorAll("source").forEach(e=>e.remove()),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(ue.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(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}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=s.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:s.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=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(const n of this.bufferManagers)for(const o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-r<=t&&o.to+r>t&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){const n=Math.max(...i)+10;n===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=n/1e3}}};class _a{fov;orientation;constructor(e,t){this.fov=e,this.orientation=t}}class Fa{options;camera;rotating=!1;fading=!1;lastTickTS=0;lastCameraTurn;lastCameraTurnTS=0;fadeStartSpeed=null;fadeCorrection;fadeTime=0;rotationSpeed;constructor(e,t){this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var Oa=`#define GLSLIFY 1
|
|
38
|
-
attribute vec2
|
|
39
|
-
|
|
33
|
+
[best track] ${j?.quality}
|
|
34
|
+
[selected track] ${N?.quality}
|
|
35
|
+
`});let Y=N&&u&&u.history[N.id]&&(0,F.now)()-u.history[N.id]<=r.trackCooldown&&(!u.last||N.id!==u.last.id);if(N?.id&&u&&!Y&&u.recordSelection(N),Y&&u?.last){let w=u.last;return u?.recordSwitch(w),d({message:`
|
|
36
|
+
[last selected] ${w?.quality}
|
|
37
|
+
`}),w}return u?.recordSwitch(N),N},xt=NI;var oe=i=>new URL(i).hostname;var B=require("@vkontakte/videoplayer-shared");var Ih=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},ye=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Ih(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Ih(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};var we=require("@vkontakte/videoplayer-shared");var Xe=require("@vkontakte/videoplayer-shared");function ue(){return(0,Xe.now)()}function io(i){return ue()-i}function ao(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Eh(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function pr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,f=!1,h="arraybuffer",b=7e3,I=2e3,g=()=>{if(l)return;(0,Xe.assertNonNullable)(c);let U=io(c),re;if(U<I){re=I-U,setTimeout(g,re);return}I*=2,I>b&&(I=b),n&&n.abort(),n=new a,z()},T=U=>(s=U,$),y=U=>(d=U,$),M=()=>(h="json",$),E=()=>{if(!l){if(--u>=0){g(),r&&r();return}l=!0,d&&d(),t&&t()}},k=U=>(f=U,$),z=()=>{c=ue(),n=new a,n.open("get",i);let U=0,re,le=0,Me=()=>((0,Xe.assertNonNullable)(c),Math.max(c,Math.max(re||0,le||0)));if(s&&n.addEventListener("progress",C=>{let W=ue();s.updateChunk&&C.loaded>U&&(s.updateChunk(Me(),C.loaded-U),U=C.loaded,re=W)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(l)return;(0,Xe.assertNonNullable)(n);let C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&s){let W=n.response.byteLength-U;W&&s.updateChunk&&s.updateChunk(Me(),W)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),f){let C=()=>{(0,Xe.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=ue(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=h,n.send(),$},$={withBitrateReporting:T,withParallel:k,withJSONResponse:M,withRetryCount:U=>(u=U,$),withRetryInterval:(U,re)=>((0,Xe.isNonNullable)(U)&&(I=U),(0,Xe.isNonNullable)(re)&&(b=re),$),withTimeout:U=>(o=U,$),withFinally:y,send:z,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return $}var Wr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Qr=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ue(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=ue()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=pr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var _a=1e4,so=3;var qI=6e4,UI=10,HI=1,jI=500,zr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Wr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ao(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ao(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,we.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Eh(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Qr(so,_a,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,l=null,u=null,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,k,z)=>{l&&l.abort(),l=pr(this.urlResolver.resolve(E,!1),k,z,()=>this._retryCallback()).withTimeout(_a).withBitrateReporting(this.bitrateSwitcher).withRetryCount(so).withFinally(()=>{l=null}).send()},h=(E,k,z)=>{(0,we.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),k,z,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},b=E=>{let k=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${k}=>${E}`),r.playbackRate=E)},I=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}let z=ue()-1e4,j=0;for(let Y=0;Y<this.bufferStates.length;Y++){let w=this.bufferStates[Y];E=Math.min(E,w.buf),w.ts<z&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${E} drop=${j} jitter=${this.sourceJitter}`);let N=E-HI;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?b(1.15):N>1?b(1.1):N>.3?b(1.05):b(1)}},T=E=>{let k,z=()=>k&&k.start?k.start.length:0,j=C=>k.start[C]/1e3,N=C=>k.dur[C]/1e3,Y=C=>k.fragIndex+C,w=(C,W)=>({chunkIdx:Y(C),startTS:j(C),dur:N(C),discontinuity:W}),$=()=>{let C=0;if(k&&k.dur){let W=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ie=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,se=W;this.sourceJitter>1&&(se+=this.sourceJitter-1);let Te=k.dur.length-1;for(;Te>=0&&(se-=k.dur[Te],!(se<=0));--Te);C=Math.min(Te,k.dur.length-1-ie),C=Math.max(C,0)}return w(C,!0)},U=C=>{let W=z();if(!(W<=0)){if((0,we.isNonNullable)(C)){for(let ie=0;ie<W;ie++)if(j(ie)>C)return w(ie)}return $()}},re=C=>{let W=z(),ie=C?C.chunkIdx+1:0,se=ie-k.fragIndex;if(!(W<=0)){if(!C||se<0||se-W>UI)return t(`Resync: offset=${se} bChunks=${W} chunk=`+JSON.stringify(C)),$();if(!(se>=W))return w(ie-k.fragIndex,!1)}},le=(C,W,ie)=>{u&&u.abort(),u=pr(this.urlResolver.resolve(C,!0,this.lowLatency),W,ie,()=>this._retryCallback()).withTimeout(_a).withRetryCount(so).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(C,W)=>{le(E,ie=>{if(!d())return;k=ie;let se=!!k.lowLatency;se!==this.lowLatency&&I(se);let Te=0;for(let bt=0;bt<k.dur.length;++bt)Te+=k.dur[bt];Te>0&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Te/k.dur.length)),a({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,C(U(W))},()=>this._handleNetworkError())},nextChunk:re}},y=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),(0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:k,logger:z}=this.params,j=T(e.jidxUrl),N,Y,w,$,U=0,re,le,Me,C=()=>{re&&(clearTimeout(re),re=void 0);let K=Math.max(jI,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ie=U+K,Ee=ue(),Oe=Math.min(1e4,Ie-Ee);U=Ee;let tt=()=>{u||d()&&j.seek(()=>{d()&&(U=ue(),W(),C())})};Oe>0?re=window.setTimeout(()=>{this.paused?C():tt()},Oe):tt()},W=()=>{let K;for(;K=j.nextChunk($);)$=K,is(K);let Ie=j.nextChunk(w);if(Ie){if(w&&Ie.discontinuity){z("Detected discontinuity; restarting playback"),this.paused?C():(y(),this._initPlayerWith(e));return}bt(Ie)}else C()},ie=(K,Ie)=>{if(!d()||!this.sourceBuffer)return;let Ee,Oe,tt,Tr=xe=>{window.setTimeout(()=>{d()&&ie(K,Ie)},xe)};if(this.sourceBuffer.updating)z("Source buffer is updating; delaying appendBuffer"),Tr(100);else{let xe=ue(),gt=k.currentTime;!this.paused&&k.buffered.length>1&&le===gt&&xe-Me>500&&(z("Stall suspected; trying to fix"),this._fixupStall()),le!==gt&&(le=gt,Me=xe);let Be=this._getBufferSizeSec();if(Be>30)z(`Buffered ${Be} seconds; delaying appendBuffer`),Tr(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:xe,buf:Be}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ie&&Ie()}catch(Ye){if(Ye.name==="QuotaExceededError")z("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Ee=this.sourceBuffer.buffered.start(0),Oe=gt,Oe-Ee>4&&this.sourceBuffer.remove(Ee,Oe-3)),Tr(1e3);else throw Ye}}},se=()=>{Y&&N&&(z([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(w)]),ie(Y,function(){Y=null,W()}))},Te=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),bt=K=>{d()&&h(Te(K),(Ie,Ee)=>{if(d()){if(Ee/=1e3,Y=Ie,w=K,n=K.startTS,Ee){let Oe=Math.min(10,K.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}se()}},()=>this._handleNetworkError())},is=K=>{d()&&((0,we.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Te(K),!1)))},Ni=K=>{d()&&(e.cachedHeader=K,ie(K,()=>{N=!0,se()}))};s=!0,j.seek(K=>{if(d()){if(U=ue(),!K){C();return}$=K,!(0,we.isNullable)(E)||K.startTS>E?bt(K):(w=K,W())}},E),e.cachedHeader?Ni(e.cachedHeader):f(e.headerUrl,Ni,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,we.isNonNullable)(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,we.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,we.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let f,h,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),b=d/this.bitrate,h>10&&b>.8||h>15&&b>.5||h>20&&b>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(f,h)=>{let b=ue();if(this.chunkRateEstimator.addInterval(f,b,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:b-f,speed:g}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&io(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,f)=>{let h=s.updateChunk(d,f);return h&&u(),h},notifySwitch:d=>{let f=ue();d<o&&(n=f),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(_a).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ye(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},qI))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var te=require("@vkontakte/videoplayer-shared"),no=class{constructor(){this.onDroopedVideoFramesLimit$=new te.Subject;this.subscription=new te.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new te.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,te.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,te.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,te.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,te.interval)(this.droppedFramesChecker.checkTime).pipe((0,te.filter)(()=>this.playing),(0,te.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,te.debounce)(this.droppedFramesChecker.checkTime)),r=(0,te.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>(0,te.isLower)(r,a)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Na=no;var Fa=require("@vkontakte/videoplayer-shared"),xh=require("@vkontakte/videoplayer-shared");var Kr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var GI=(i,e)=>new Fa.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||Kr()))},{...r,...e});a.observe(i);let s=(0,xh.fromEvent)(document,"visibilitychange").pipe((0,Fa.map)(n=>!document.hidden||Kr())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),$e=GI;var YI=["paused","playing","ready"],WI=["paused","playing","ready"],Jr=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new H("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new Le;this.droppedFramesManager=new Na;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.ValueSubject(void 0);this.liveOffset=new nt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:B.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=Et(a.name)??(0,B.videoSizeToQuality)(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,B.isNonNullable)(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(WI.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&YI.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(de(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let l=a?.from;l&&l==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(de(this.params.source.url,l))}return;default:return(0,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=be(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Se(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe((0,B.map)(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,B.filterChanged)(),(0,B.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add($e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,B.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,B.assertNever)(a.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ge(this.video)}createLiveDashPlayer(){let e=new zr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&(0,B.isNonNullable)(t)?t:xt(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:c})=>c.id===s)?.representation;(0,B.assertNonNullable)(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;(0,B.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(de(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Ph=Jr;var Pt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var D=require("@vkontakte/videoplayer-shared");var qa=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},hr=class extends qa{constructor(){super(),this.listeners||qa.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Xr=class{constructor(){Object.defineProperty(this,"signal",{value:new hr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Xr.prototype[Symbol.toStringTag]="AbortController",hr.prototype[Symbol.toStringTag]="AbortSignal");function Ua(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function oo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Ua({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let f=new t(u,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((h,b)=>{c.addEventListener("abort",()=>b(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,n(l,u)])}return n(l,u)},Request:s}}var Zr=Ua({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),kh=Zr?oo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Zr?kh.fetch:window.fetch,PR=Zr?kh.Request:window.Request,ct=Zr?Xr:window.AbortController,kR=Zr?hr:window.AbortSignal;var xf=_e(Ia(),1);var ei=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var vr=_e(Ba(),1);var QI=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},zI=i=>window.clearTimeout(i),wh=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",uo=wh?QI:window.requestIdleCallback,RR=wh?zI:window.cancelIdleCallback;var gf=_e(Ma(),1);var Ce=require("@vkontakte/videoplayer-shared"),KI=16,Ah=!1;try{Ah=(0,Ce.getCurrentBrowser)().browser===Ce.CurrentClientBrowser.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=KI}catch(i){console.error(i)}var lo=class{constructor(e){this.bufferFull$=new Ce.Subject;this.error$=new Ce.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let 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:Ce.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Ah&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),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}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ce.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{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:(0,Ce.assertNever)(t)}}},Rh=lo;var co=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var fr=class extends Q{};var ti=class extends Q{};var ri=class extends Q{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var ii=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends Q{constructor(t,r){super(t,r);this.data=this.content}};var ae=class extends Q{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Vt=class extends ae{constructor(t,r){super(t,r);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 a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,l=this.readUint32();s=this.readUint32();let u=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var ni=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends ae{constructor(t,r){super(t,r);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var li=class extends ae{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ci=class extends ae{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var di=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends ae{constructor(t,r){super(t,r);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()}};var hi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends ae{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var bi=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends ae{constructor(t,r){super(t,r);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())}};var vi=class extends ae{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Si=class extends ae{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)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())}};var XI={ftyp:ri,moov:ii,moof:ai,mdat:si,sidx:Vt,trak:ni,mdia:di,mfhd:mi,tkhd:pi,traf:bi,tfhd:gi,tfdt:vi,trun:Si,minf:hi,sv3d:oi,st3d:ui,prhd:li,proj:fi,equi:ci,uuid:ti,unknown:fr},_t=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=XI[e];return r?new r(t,new i):new fr(t,new i)}};var mr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var eE=new TextDecoder("ascii"),tE=i=>eE.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",rE=i=>{let e=new Vt(i,new _t),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},iE=(i,e)=>{let r=new _t().parse(i),a=new mr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,d=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,d)},aE=(i,e)=>{let r=new _t().parse(i),s=new mr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),l=s[s.length-1].children.find(d=>d.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((d,f)=>d+f,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},sE=i=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new _t().parse(i),a=new mr(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},Lh={validateData:tE,parseInit:sE,getIndexRange:()=>{},parseSegments:rE,parseFeedableSegmentChunk:iE,getSegmentEndTime:aE};var dt=require("@vkontakte/videoplayer-shared");var Ch=require("@vkontakte/videoplayer-shared");var $h={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Dh=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=yi(i,t),a=r in $h,s=a?$h[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,c=yi(l),d=u*2**((o-1)*8)+c,f=t+o,h;return f+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+f):h=new DataView(i.buffer,i.byteOffset+f,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+d,value:h,valueSize:d}},yi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},je=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return yi(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:(0,Ch.assertNever)(e)}},Nt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Dh(r);if(!e(a))return;a.type==="master"&&Nt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Mh=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Dh(i);return Nt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=je(o,n):s===17026?t=je(o,n):s===17029&&(r=je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Oh=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],nE=[231,22612,22743,167,171,163,160,175],oE=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Nt(i,({tag:f,type:h,value:b,valueSize:I})=>{if(f===21419){let g=je(b,h);u=yi(g)}else f!==21420&&(u=void 0);return f===408125543?(e=b.byteOffset,t=b.byteOffset+I):f===357149030?s=!0:f===290298740?n=!0:f===2807729?r=je(b,h):f===17545?a=je(b,h):f===21420&&u===475249515?l=je(b,h):f===374648427?Nt(b,({tag:g,type:T,value:y})=>g===30321?(c=je(y,T)===1,!1):!0):s&&n&&Oh.includes(f)&&(o=!0),!o}),(0,dt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,dt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,dt.assertNonNullable)(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},uE=i=>{if((0,dt.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lE=(i,e)=>{let t=!1,r=!1,a=o=>(0,dt.isNonNullable)(o.time)&&(0,dt.isNonNullable)(o.position),s=[],n;return Nt(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=je(u,l));break;case 183:break;case 241:n&&(n.position=je(u,l));break;default:t&&Oh.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:c}=o,d=s[l+1];return{status:"none",time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},cE=i=>{let e=0,t=!1;try{Nt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):nE.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Bh={validateData:Mh,parseInit:oE,getIndexRange:uE,parseSegments:lE,parseFeedableSegmentChunk:cE};var go=_e(of(),1),gr=require("@vkontakte/videoplayer-shared");var uf=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var lf=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Ft=(i,e)=>{let t=i;t=(0,go.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,go.default)(t,n,(o,l)=>(0,gr.isNullable)(s)?o:(0,gr.isNullable)(l)?s:s.padStart(parseInt(l,10),"0"))}return t},df=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,f,h=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)f=lf(h);else if(b){let E=lf(b);(0,gr.isNonNullable)(E)&&(f=E)}else g&&(f=parseInt(g,10));let T=0,y=s.getAttribute("profiles")?.split(",")??[],M=y.includes("urn:webm:dash:profile:webm-on-demand:2012")||y.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let E of l){let k=E.getAttribute("mimeType"),z=E.getAttribute("codecs"),j=E.getAttribute("contentType")??k?.split("/")[0],N=E.getAttribute("profiles")?.split(",")??[],Y=E.querySelectorAll("Representation"),w=E.querySelector("SegmentTemplate");if(j==="text"){for(let $ of Y){let U=$.getAttribute("id")||"",re=E.getAttribute("lang"),le=E.getAttribute("label"),Me=$.querySelector("BaseURL")?.textContent?.trim()??"",C=new URL(Me||o,e).toString(),W=U.includes("_auto");a.text.push({id:U,lang:re,label:le,isAuto:W,kind:"text",url:C})}continue}for(let $ of Y){let U=$.getAttribute("mimeType")??k,re=$.getAttribute("codecs")??z??"",le=$.getAttribute("contentType")??U?.split("/")[0]??j,Me=E.getAttribute("profiles")?.split(",")??[],C=parseInt($.getAttribute("width")??"",10),W=parseInt($.getAttribute("height")??"",10),ie=parseInt($.getAttribute("bandwidth")??"",10)/1e3,se=$.getAttribute("frameRate")??"",Te=$.getAttribute("quality")??void 0,bt=se?uf(se):void 0,is=$.getAttribute("id")??(T++).toString(10),Ni=le==="video"?`${W}p`:le==="audio"?`${ie}Kbps`:re,K=`${is}@${Ni}`,Ie=$.querySelector("BaseURL")?.textContent?.trim()??"",Ee=new URL(Ie||o,e).toString(),Oe=[...y,...N,...Me],tt,Tr=$.querySelector("SegmentBase"),xe=$.querySelector("SegmentTemplate")??w;if(Tr){let Be=$.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ye,as]=Be.split("-").map(zt=>parseInt(zt,10)),vt={from:Ye,to:as},Ir=$.querySelector("SegmentBase")?.getAttribute("indexRange"),[ss,Fi]=Ir?Ir.split("-").map(zt=>parseInt(zt,10)):[],Er=Ir?{from:ss,to:Fi}:void 0;tt={type:"byteRange",url:Ee,initRange:vt,indexRange:Er}}else if(xe){let Be={representationId:$.getAttribute("id")??void 0,bandwidth:$.getAttribute("bandwidth")??void 0},Ye=parseInt(xe.getAttribute("timescale")??"",10),as=xe.getAttribute("initialization")??"",vt=xe.getAttribute("media"),Ir=parseInt(xe.getAttribute("startNumber")??"",10)??1,ss=Ft(as,Be);if(!vt)throw new ReferenceError("No media attribute in SegmentTemplate");let Fi=xe.querySelectorAll("SegmentTimeline S")??[],Er=[],zt=0,ns="",os=0;if(Fi.length){let qi=Ir,Ve=0;for(let Kt of Fi){let We=parseInt(Kt.getAttribute("d")??"",10),At=parseInt(Kt.getAttribute("r")??"",10)||0,Ui=parseInt(Kt.getAttribute("t")??"",10);Ve=Number.isFinite(Ui)?Ui:Ve;let us=We/Ye*1e3,Zf=Ve/Ye*1e3;for(let Hi=0;Hi<At+1;Hi++){let em=Ft(vt,{...Be,segmentNumber:qi.toString(10),segmentTime:(Ve+Hi*We).toString(10)}),Ro=(Zf??0)+Hi*us,tm=Ro+us;qi++,Er.push({time:{from:Ro,to:tm},url:em})}Ve+=(At+1)*We,zt+=(At+1)*us}os=Ve/Ye*1e3,ns=Ft(vt,{...Be,segmentNumber:qi.toString(10),segmentTime:Ve.toString(10)})}else if((0,gr.isNonNullable)(f)){let Ve=parseInt(xe.getAttribute("duration")??"",10)/Ye*1e3,Kt=Math.ceil(f/Ve),We=0;for(let At=1;At<Kt;At++){let Ui=Ft(vt,{...Be,segmentNumber:At.toString(10),segmentTime:We.toString(10)});Er.push({time:{from:We,to:We+Ve},url:Ui}),We+=Ve}os=We,ns=Ft(vt,{...Be,segmentNumber:Kt.toString(10),segmentTime:We.toString(10)})}let Xf={time:{from:os,to:1/0},url:ns};tt={type:"template",baseUrl:Ee,segmentTemplateUrl:vt,initUrl:ss,totalSegmentsDurationMs:zt,segments:Er,nextSegmentBeyondManifest:Xf,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!le||!U)continue;let gt={video:"video",audio:"audio",text:"text"}[le];gt&&a[gt].push({id:K,kind:gt,segmentReference:tt,profiles:Oe,duration:f,bitrate:ie,mime:U,codecs:re,width:C,height:W,fps:bt,quality:Te})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:f,container:M,representations:a}};var So=_e(Ba(),1);var pf=require("@vkontakte/videoplayer-shared"),hf=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?Et(s):void 0)??(0,pf.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},ff=({id:i,bitrate:e})=>({id:i,bitrate:e}),mf=(i,e,t)=>{let r=e.indexOf(t);return(0,So.default)(i,Math.round(i.length*r/e.length))??(0,So.default)(i,-1)},bf=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),yo=i=>"url"in i,qt=i=>i.type==="template",Ti=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ii=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ct;this.destroyAbortController=new ct;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,x.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 Rh(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:x.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,co(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,x.assertNonNullable)(r,"No init buffer for starting representation"),(0,x.assertNonNullable)(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);(0,x.assertNonNullable)(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,x.isNullable)(a)||(0,x.isNullable)(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,x.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();(0,x.isNonNullable)(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let o of this.representations.keys()){let l=e.find(d=>d.id===o);l&&this.representations.set(o,l);let u=this.representations.get(o);if(!u||!qt(u.segmentReference))return;let c=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,c)}let t=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(t);(0,x.assertNonNullable)(r);let a=this.segments.get(t);(0,x.assertNonNullable)(a,"No segments for starting representation");let s=this.initData.get(t);if((0,x.assertNonNullable)(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=l,this.isLive=!!c?.dynamic,this.container=r,r){case"mp4":this.containerParser=Lh;break;case"webm":this.containerParser=Bh;break;default:(0,x.assertNever)(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ct,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Pt(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&co(this.sourceBuffer.buffered)>=this.bufferLimit){let u=Pt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let c=(0,vr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&Pt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,vr.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){for(let t of e?.representations[this.kind].values()??[]){if(!t||!qt(t.segmentReference))return;let r=t.segmentReference.segments.map(o=>({...o,status:"none",size:void 0})),a=this.segments.get(t.id)??[],s=(0,vr.default)(a,-1)?.time.to??0,n=r?.findIndex(o=>Math.floor(s)>=Math.floor(o.time.from)&&Math.floor(s)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;let o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{let o=r.slice(n+1);this.segments.set(t.id,[...a,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let r=t.segmentReference;if(!qt(r))return;let a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),s=Ft(r.segmentTemplateUrl,{segmentTime:a}),n=this.segments.get(t.id)??[],o=n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||n.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:s})}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.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(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:f,to:h}},b)=>{let I=f<=r&&h>=r,g=f>r||I||b===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&!ei(this.sourceBuffer.buffered,r))&&g&&y});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=u||o<=c);d++){let f=s[d];if(n+=f.byte.to+1-f.byte.from,o+=f.time.to+1-f.time.from,f.status==="none"||f.status==="partially_ejected")l.push(f);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,x.abortable)(o,async function*(){let c=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let f=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,f)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ti(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,x.abortable)(n,async function*(){let l=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),Ti(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(qt(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,vr.default)(e,0).byte.from,to:(0,vr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qt(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let l=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,f=l==="byteRange",h=f?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!f||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let I=f?d.byte.from-r:0,g=f?d.byte.to-r:e.byteLength,T=I<a,y=g<=a;if(d.status==="downloading"&&T&&y){d.status="downloaded";let M=new DataView(e.buffer,e.byteOffset+I,h);this.sourceBufferTaskQueue.append(M,s).then(E=>E&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(h,a-I),c.loadedBytes>c.feedingBytes)){let M=new DataView(e.buffer,e.byteOffset+I+c.feedingBytes,c.loadedBytes-c.feedingBytes),E=c.loadedBytes===h?M:this.containerParser.parseFeedableSegmentChunk(M);E?.byteLength&&(d.status="partially_fed",c.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(k=>{if(s.aborted)n();else if(k)c.fedBytes+=E.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",yo(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=uo(()=>(0,gf.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:c}=o,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&qt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=yo(u)?u.size??0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&l(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&l(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(let f of this.segments.values())for(let h of f)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+u&&d.status==="fed"&&l(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let 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(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=uo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),l=e.some(c=>c.from-t<=n&&c.to+t>=o),u=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);l||(u.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ei=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var vf=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};var X=require("@vkontakte/videoplayer-shared");var Ha=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.abortAllController=new ct;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ei(t));let r=yield lt(t,{signal:this.abortAllController.signal}).catch(xi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let N=new URL(u,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),u=N.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(u=Ei(u));let d=this.abortAllController.signal,f;if(n){let N=new ct;if(f=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{N.abort()}catch(Y){xi(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(Y){xi(Y)}d=N.signal}let h=(0,X.now)(),b=yield lt(u,{priority:s,headers:c,signal:d}).catch(xi),I=(0,X.now)();if(!b)return f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(I-h),!b.ok||!b.body)return f?.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return f?.unsubscribe(),b.arrayBuffer();let[g,T]=b.body.tee(),y=g.getReader();o&&this.throughputEstimator?.trackStream(T,l);let M=0,E=new Uint8Array(0),k=!1,z=N=>{f?.unsubscribe(),k=!0,xi(N)},j=(0,X.abortable)(d,async function*({done:N,value:Y}){if(M===0&&this.lastRequestFirstBytes$.next((0,X.now)()-h),d.aborted){f?.unsubscribe();return}if(!N&&Y){let w=new Uint8Array(E.length+Y.length);w.set(E),w.set(Y,E.length),E=w,M+=Y.byteLength,a?.(new DataView(E.buffer),M),yield y?.read().then(j,z)}}.bind(this));return yield y?.read().then(j,z),f?.unsubscribe(),k?null:E.buffer}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let f=new DataView(d,a-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let h=t.parseInit(f),b=e.indexRange??t.getIndexRange(h);if(!b)throw new ReferenceError("No way to load representation index");let I;if(l)I=new DataView(d,b.from-n,b.to-b.from+1);else{let T=yield this.fetch(e.url,{range:b,priority:r,measureThroughput:!1});if(!T)return null;I=new DataView(T)}let g=t.parseSegments(I,h,b);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=vf(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:(0,X.assertNever)(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},xi=i=>{if(!Ti(i))throw i};var Ut=(i,e,t)=>t*e+(1-t)*i,To=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Sf=(i,e,t,r)=>{let a=0,s=t,n=To(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};var Pi=require("@vkontakte/videoplayer-shared"),kt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Pi.ValueSubject(e.initial),this.debounced$=new Pi.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new pe(`raw_${t}`),this.smoothedSeries$=new pe(`smoothed_${t}`),this.reportedSeries$=new pe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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>s||this.smoothed<n)&&((0,Pi.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ja=class extends kt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Ut(this.slow,t,this.params.emaAlphaSlow),this.fast=Ut(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var Ga=class extends kt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=To(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ut(this.emaSmoothed,t,this.params.emaAlpha);let a=Sf(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var Ya=class extends kt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ut(this.smoothed,t,this.params.emaAlpha):t}};var Ht=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ja({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ga({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Ya({initial:e,label:"liveEdgeDelay",...t})}};var yf=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var pt=()=>window.ManagedMediaSource||window.MediaSource,Wa=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Tf=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),If=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Ef=["timeupdate","progress","play","seeked","stalled","waiting"];var Qa=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new ct;this.initManifest=(0,v.abortable)(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=de(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=df(e??"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let r=({kind:a,mime:s,codecs:n})=>!!(this.element?.canPlayType?.(s)&&pt()?.isTypeSupported?.(`${s}; codecs="${n}"`)||a==="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:(0,xf.default)(Object.entries(t.representations).map(([a,s])=>[a,s.filter(r)]))}}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,r){(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add((0,v.fromEvent)(h,"error").pipe((0,v.filter)(b=>!!this.element?.played.length)).subscribe(b=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?If():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Wa())if(r){let h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;let n={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 Ii("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)&&(this.audioBufferManager=new Ii("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),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((0,v.interval)(1e3).subscribe(h=>{if(this.element?.paused){let b=Kn(this.manifestUrlString,2);this.manifestUrlString=de(this.manifestUrlString,b+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...Ef.filter(h=>h!=="waiting").map(h=>(0,v.fromEvent)(this.element,h))).pipe((0,v.map)(h=>this.element?Pt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.filter)(h=>!!h),(0,v.tap)(h=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe((0,v.filter)(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let I=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=b-I,M=1+Math.sign(y)*T;Math.abs(y)<g?M=1:Math.abs(y)>g*2&&(M=1+Math.sign(y)*T*2),yf(this.element,M)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{let I=0;if(b){let g=(this.element?.currentTime??0)*1e3;I=Math.min(...this.bufferManagers.map(y=>y.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==I&&this.liveLoadBufferLength$.next(I)}));let h=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:b,bufferLength:I})=>{if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,T=Kn(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,M=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,z=this.isActiveLowLatency?I:b,j=3;if(this.isActiveLowLatency?j=0:z<M+k&&z>=M?j=1:T!==0&&z<M&&(j=2),isFinite(b)&&(h=b>h?b:h),j===2||j===1){let N=h-(M+E),Y=this.normolizeLiveOffset(Math.trunc(T+N/g)),w=Math.abs(Y-T),$;!b||w<=this.tuning.dashCmafLive.offsetCalculationError?$=T:Y>0&&w>this.tuning.dashCmafLive.offsetCalculationError?$=Y:$=0,this.manifestUrlString=de(this.manifestUrlString,$,2)}j!==3&&j!==0&&(h=0,this.updateLive())}))}let o=(0,v.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),l=(0,v.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:o,someBufferEnded:l}).pipe((0,v.filter)(({allBuffersFull:h,someBufferEnded:b})=>h&&b))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(h=>this.source?.addEventListener("sourceopen",h)));let u=this.manifest.duration??0,c=(h,b)=>Math.max(h,b.duration??0),d=this.manifest.representations.audio.reduce(c,u),f=this.manifest.representations.video.reduce(c,u);(d||f)&&(this.source.duration=Math.max(d,f)/1e3),this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ha({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ht.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=de(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...Ef.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ei(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),ei(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),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("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}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;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var za=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ka=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Pf=`attribute vec2 a_vertex;
|
|
38
|
+
attribute vec2 a_texel;
|
|
39
|
+
|
|
40
|
+
varying vec2 v_texel;
|
|
41
|
+
|
|
42
|
+
void main(void) {
|
|
43
|
+
// direct vertex drawing
|
|
44
|
+
gl_Position = vec4(a_vertex, 0.0, 1.0);
|
|
45
|
+
// save texel vector to pass to fragment shader
|
|
46
|
+
v_texel = a_texel;
|
|
47
|
+
}
|
|
48
|
+
`;var kf=`#ifdef GL_ES
|
|
49
|
+
precision highp float;
|
|
50
|
+
precision highp int;
|
|
40
51
|
#else
|
|
41
|
-
precision highp float;
|
|
42
|
-
#define GLSLIFY 1
|
|
52
|
+
precision highp float;
|
|
43
53
|
#endif
|
|
54
|
+
|
|
44
55
|
#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 Ha{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 r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new _a(this.params.fov,this.params.orientation),this.cameraRotationManager=new Fa(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"),r=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(r,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(Oa,this.gl.VERTEX_SHADER),i=this.createShader(Ua,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 r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/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,r=this.camera.fov.y/180/2,n=e-i,o=t-r,c=e+i,l=t-r,u=e+i,d=t+r,h=e-i,p=t+r;return[n,o,c,l,u,d,h,p]}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}}class Oi{scene3D;subscription=new s.Subscription;videoState=new z(G.STOPPED);video;player;params;elementSize$=new s.ValueSubject(void 0);textTracksManager=new Ne;droppedFramesManager=new Ci;videoTracks$=new s.ValueSubject([]);audioTracks=[];audioRepresentations=new Map;videoTrackSwitchHistory=new Ts;textTracks=[];liveOffset;constructor(e){this.params=e,this.video=Ue(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(ke(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ma({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=Ye(this.video),r=this.constructor.name,n=c=>{e.error$.next({id:r,category:s.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:c})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(c,l)=>this.subscription.add(c.subscribe(l,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,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(s.map(u=>u.map(({track:d})=>d)))}),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(s.filter(s.isNonNullable),s.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(pt(this.video,t.isLooped,r)),this.subscription.add(je(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(it(this.video,t.playbackRate,i.playbackRateState$,r)),n(s.observeElementSize(this.video),this.elementSize$),n(st(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===G.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u===ue.MANIFEST_READY){const d=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();s.assertNonNullable(h,"Manifest not loaded or empty");const p=Array.from(h.audio).sort((b,y)=>y.bitrate-b.bitrate),f=Array.from(h.video).sort((b,y)=>y.bitrate-b.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const b of p){const y=wa(b);y&&this.audioTracks.push({track:y,representation:b})}for(const b of f){const y=Aa(b);if(y){d.push({track:y,representation:b});const C=!this.params.tuning.isAudioDisabled&&$a(p,f,b);C&&this.audioRepresentations.set(b.id,C)}}this.videoTracks$.next(d);for(const b of m){const y=Pa(b);y&&this.textTracks.push({track:y,representation:b})}this.params.output.availableVideoTracks$.next(d.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 T=this.selectVideoRepresentation();s.assertNonNullable(T),this.player.initRepresentations(T.id,this.audioRepresentations.get(T.id)?.id,this.params.sourceHls)}else u===ue.REPRESENTATIOS_READY&&(this.videoState.setState(G.READY),this.player.initBuffer())},r));const o=u=>e.error$.next({id:"RepresentationSwitch",category:s.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(s.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,s.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),d=this.player.state$.getTransition();if(u!==ue.RUNNING||d||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(h){let T=h.id;!this.params.output.elementVisible$.getValue()&&f&&(T=this.videoTracks$.getValue().map(y=>y.representation).sort((y,C)=>C.bitrate-y.bitrate).filter(y=>{const C=s.videoSizeToQuality(y),P=s.videoSizeToQuality(h);if(C&&P)return s.isLowerOrEqual(C,P)&&s.isLowerOrEqual(C,m)}).map(y=>y.id)[0]),this.player.switchRepresentation(Z.VIDEO,T).catch(o);const b=this.audioRepresentations.get(h.id);b&&this.player.switchRepresentation(Z.AUDIO,b.id).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(s.filterChanged(),s.map(u=>u&&this.videoTracks$.getValue().find(({representation:{id:d}})=>d===u)?.track)).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);const c=t.playbackState.stateChangeStarted$.pipe(s.map(({to:u})=>u===exports.PlaybackState.READY),s.filterChanged());this.subscription.add(s.merge(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(s.merge(c,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const l=s.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){const e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,i=this.videoTracks$.getValue().find(({track:{id:h}})=>h===t)?.track,r=this.params.output.currentVideoTrack$.getValue(),n=ut(this.video.buffered,this.video.currentTime*1e3),o=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,c=Math.min(n/Math.min(o,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),l=Math.max(i&&!e?this.audioRepresentations.get(i.id)?.bitrate??0:0,r?this.audioRepresentations.get(r.id)?.bitrate??0:0),u=Lt(this.videoTracks$.getValue().map(({track:h})=>h),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:l,forwardBufferHealth:c,current:r,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),d=e?u??i:i??u;return d&&this.videoTracks$.getValue().find(({track:h})=>h===d)?.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(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state===I.Requested&&i?.to!==exports.PlaybackState.PAUSED&&e!==G.STOPPED&&t!==exports.PlaybackState.STOPPED){const o=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-o,r.forcePrecise)}if(t===exports.PlaybackState.STOPPED){e!==G.STOPPED&&(this.videoState.startTransitionTo(G.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(G.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(e){case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();return;case G.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case G.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.liveOffset?.pause(),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.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&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}};init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ha(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(){Ge(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState(G.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.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),He(this.video)}}class ja extends Oi{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)}}class Ya extends Oi{constructor(e){super(e),this.liveOffset=new zt}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(s.combine({interval:s.interval(Xe),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()===G.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(s.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(s.map(({liveBufferTime:r,liveAvailabilityStartTime:n})=>r&&n?r+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===G.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,r)})}}const me={};var V;(function(a){a.INITIALIZING="initializing",a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(V||(V={}));const Qe=(a,e)=>new s.Observable(t=>{const i=(r,n)=>t.next(n);return a.on(e,i),()=>a.off(e,i)});class Ga{subscription=new s.Subscription;videoState=new z(V.INITIALIZING);video;params;hls;textTracksManager=new Ne;trackLevels=new Map;constructor(e){this.video=Ue(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(ke(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),He(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:s.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(me.Hls=r.default,me.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){s.assertNonNullable(me.Hls,"hls.js not loaded"),this.hls=new me.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){s.assertNonNullable(me.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:s.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=Ye(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),n(r.inPiP$,t.inPiP$),n(r.inFullscreen$,t.inFullscreen$),this.subscription.add(pt(this.video,e.isLooped,i)),this.subscription.add(je(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(it(this.video,e.playbackRate,r.playbackRateState$,i)),n(st(this.video),t.elementVisible$),this.subscription.add(Qe(this.hls,me.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:s.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},i)),n(Qe(this.hls,me.Events.MANIFEST_PARSED).pipe(s.map(({levels:u})=>u.reduce((d,h)=>{const p=h.name||h.height.toString(10),{width:f,height:m}=h,T=Ct(h.attrs.QUALITY??"")??s.videoSizeToQuality({width:f,height:m});if(!T)return d;const b=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:T,bitrate:h.bitrate/1e3,size:{width:f,height:m},fps:b};return this.trackLevels.set(p,{track:y,level:h}),d.push(y),d},[]))),t.availableVideoTracks$),n(Qe(this.hls,me.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const d=[];for(const h of u.subtitleTracks){const p=h.name,f=h.attrs.URI||"",m=h.lang,T="internal";d.push({id:p,url:f,language:m,type:T})}e.internalTextTracks.startTransitionTo(d)}}),n(Qe(this.hls,me.Events.LEVEL_LOADING).pipe(s.map(({url:u})=>ke(u))),t.hostname$),n(Qe(this.hls,me.Events.FRAG_CHANGED),u=>{const{video:d,audio:h}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((h?.endPTS??0)-(h?.startPTS??0))*1e3)}),this.subscription.add(we(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>Array.from(this.trackLevels.values()).find(({level:d})=>d===u)?.track,c=Qe(this.hls,me.Events.LEVEL_SWITCHED).pipe(s.map(({level:u})=>o(this.hls.levels[u])));c.pipe(s.filter(s.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(we(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{if(s.isNullable(u))return;const d=this.trackLevels.get(u.id)?.level;if(!d)return;const h=this.hls.levels.indexOf(d),p=this.hls.currentLevel,f=this.hls.levels[p];!f||d.bitrate>f.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:c,onError:i})),n(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const l=s.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}syncPlayback=()=>{const e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!==V.INITIALIZING)switch(i?.to!==exports.PlaybackState.PAUSED&&r.state===I.Requested&&this.seek(r.position),t){case exports.PlaybackState.STOPPED:switch(e){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:s.assertNever(e)}break;case exports.PlaybackState.READY:switch(e){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:s.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:s.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:s.assertNever(e)}break;default:s.assertNever(t)}};prepare(){this.videoState.startTransitionTo(V.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(V.PLAYING),await Ge(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(V.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(V.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(V.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const fi="X-Playback-Duration";var pi=async a=>{const e=await ht(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(fi)?parseInt(e.headers.get(fi),10):void 0};const qa=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){const[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=s.videoSizeToQuality({width:t,height:i})}return e??null},za=(a,e)=>{const t=a.split(`
|
|
46
|
-
`),i=[],r=[];for(let n=0;n<t.length;n++){const o=t[n],c=o.match(/^#EXT-X-STREAM-INF:(.+)/),l=o.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!l)){if(c){const u=Object.fromEntries(c[1].split(",").map(b=>b.split("="))),d=u.QUALITY??`stream-${u.BANDWIDTH}`,h=qa(u);let p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const f=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0;let m;if(u.RESOLUTION){const[b,y]=u.RESOLUTION.split("x").map(C=>parseInt(C,10));b&&y&&(m={width:b,height:y})}const T=new URL(t[++n],e).toString();h&&i.push({id:d,quality:h,url:T,bandwidth:p,size:m,fps:f})}if(l){const u=Object.fromEntries(l[1].split(",").map(f=>f.split("=")).map(([f,m])=>[f,m.replace(/^"|"$/g,"")])),d=u.URI?.replace(/playlist$/,"subtitles.vtt"),h=u.LANGUAGE,p=u.NAME;d&&h&&r.push({type:"internal",id:h,label:p,language:h,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Wa=a=>new Promise(e=>{setTimeout(()=>{e()},a)});let _t=0;const Xt=async(a,e=a,t)=>{const r=await(await ht(a)).text();_t+=1;try{const{qualityManifests:n,textTracks:o}=za(r,e);return{qualityManifests:n,textTracks:o}}catch{if(_t<=t.manifestRetryMaxCount)return await Wa(s.getExponentialDelay(_t-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Xt(a,e,t)}return{qualityManifests:[],textTracks:[]}};var U;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.CHANGING_MANIFEST="changing_manifest",a.PAUSED="paused"})(U||(U={}));class Qa{subscription=new s.Subscription;videoState=new z(U.STOPPED);video;params;textTracksManager=new Ne;masterManifest;manifests$=new s.ValueSubject([]);maxSeekBackTime$;liveOffset=new zt;manifestStartTime$=new s.ValueSubject(void 0);constructor(e){this.params=e,this.video=Ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:s.VideoQuality.INVARIANT,url:this.params.source.url},Xt(Se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:s.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:s.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(ke(this.params.source.url)),this.maxSeekBackTime$=new s.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){const{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),n=r?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!r&&t.startTransitionTo(this.masterManifest),o.find(l=>l.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=c=>{e.error$.next({id:"HlsLiveProvider",category:s.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:c})},r=Ye(this.video),n=(c,l)=>this.subscription.add(c.subscribe(l,i));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(it(this.video,t.playbackRate,r.playbackRateState$,i)),n(st(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===U.READY&&this.videoState.setState(U.READY),this.videoState.getState()===U.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(s.filterChanged(),s.map(c=>-c/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&s.isNonNullable(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const p=this.manifests$.getValue().find(f=>f.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ke(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),l&&l.from===U.CHANGING_MANIFEST&&this.videoState.setState(l.to),c&&c.state===I.Requested&&this.seek(c.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{const c=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(s.combine({startTime:this.manifestStartTime$.pipe(s.filter(s.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:c,currentTime:l})=>this.params.output.liveTime$.next(c+l*1e3),i)),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:l,quality:u,size:d,bandwidth:h,fps:p})=>({id:l,quality:u,size:d,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){const e=this.selectManifest();if(s.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:c,min:l}=t?.to??i??{};for(const[u,d]of[[c,"mq"],[l,"lq"]]){const h=String(parseFloat(u||""));d&&u&&r.searchParams.set(d,h)}}const n=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?X.DASH_CMAF_OFFSET_P:X.OFFSET_P,o=Se(r.toString(),this.liveOffset.getTotalOffset(),n);this.video.setAttribute("src",o),this.video.load(),pi(o).then(c=>{if(!s.isNullable(c))this.maxSeekBackTime$.next(c);else{const l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(s.isNullable(l)||!isFinite(l))try{ht(o).then(u=>u.text()).then(u=>{const d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(d){const h=new URL(d,o).toString();pi(h).then(p=>{s.isNullable(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.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(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i===exports.PlaybackState.STOPPED){t!==U.STOPPED&&(this.videoState.startTransitionTo(U.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(U.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(t===U.STOPPED){this.videoState.startTransitionTo(U.READY),this.prepare();return}if(n||o||c){const d=this.videoState.getState();this.videoState.setState(U.CHANGING_MANIFEST),this.videoState.startTransitionTo(d),this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),u.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!==exports.PlaybackState.PAUSED&&u.state===I.Requested){this.videoState.startTransitionTo(U.READY),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case U.READY:i===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed());return;case U.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.video.pause()):r?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case U.PAUSED:if(i===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(U.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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else r?.to===exports.PlaybackState.PAUSED&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case U.CHANGING_MANIFEST:break;default:return s.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 Ja{subscription=new s.Subscription;videoState=new z(j.STOPPED);video;params;textTracksManager=new Ne;masterManifest;manifests$=new s.ValueSubject([]);constructor(e){this.params=e,this.video=Ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:s.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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Xt(Se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).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:s.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(),r=t.getTransition(),n=r?.to?.id??t.getState()?.id??"master",o=this.manifests$.getValue();if(!o.length)return;const c=i?"master":n;return i&&!r&&t.startTransitionTo(this.masterManifest),o.find(l=>l.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=c=>{e.error$.next({id:"HlsProvider",category:s.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:c})},r=Ye(this.video),n=(c,l)=>this.subscription.add(c.subscribe(l));if(n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(pt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(it(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(j.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===j.READY&&this.videoState.setState(j.READY),this.videoState.getState()===j.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const c=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&s.isNonNullable(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ke(p.url));const f=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(f!==m){const T=this.params.output.element$.getValue();T&&(this.params.desiredState.playbackRate.setState(f),T.playbackRate=f)}}}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),l&&l.from===j.CHANGING_MANIFEST&&this.videoState.setState(l.to),c.state===I.Requested&&this.seek(c.position)},i))),this.subscription.add(this.manifests$.pipe(s.map(c=>c.map(({id:l,quality:u,size:d,bandwidth:h,fps:p})=>({id:l,quality:u,size:d,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!s.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:c}=this.video;this.subscription.add(s.merge(s.fromEvent(c,"addtrack"),s.fromEvent(c,"removetrack"),s.fromEvent(c,"change"),s.observableFrom(["init"])).subscribe(()=>{for(let l=0;l<c.length;l++)c[l].mode="hidden"},i))}const o=s.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,s.observableFrom(["init"])).pipe(s.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){const e=this.selectManifest();if(s.isNullable(e))return;const t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){const{max:n,min:o}=t?.to??i??{};for(const[c,l]of[[n,"mq"],[o,"lq"]]){const u=String(parseFloat(c||""));l&&c&&r.searchParams.set(l,u)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(j.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.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(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),c=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),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(t===j.STOPPED){this.videoState.startTransitionTo(j.READY),this.prepare();return}if(n||o||c){const d=this.videoState.getState();this.videoState.setState(j.CHANGING_MANIFEST),this.videoState.startTransitionTo(d);const{currentTime:h}=this.video;this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),u.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:h*1e3,forcePrecise:!0});return}switch(r?.to!==exports.PlaybackState.PAUSED&&u.state===I.Requested&&this.seek(u.position),t){case j.READY:i===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(j.PAUSED),A(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()):r?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case j.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(j.PLAYING),this.playIfAllowed()):r?.to===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case j.CHANGING_MANIFEST:break;default:return s.assertNever(t)}}}var q;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(q||(q={}));class Xa{subscription=new s.Subscription;videoState=new z(q.STOPPED);video;trackUrls={};params;textTracksManager=new Ne;constructor(e){this.params=e,this.video=Ue(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const n=r.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=c=>{e.error$.next({id:"MpegProvider",category:s.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:c})},r=Ye(this.video),n=(c,l)=>this.subscription.add(c.subscribe(l,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(pt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(it(this.video,t.playbackRate,r.playbackRateState$,i)),n(st(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===q.READY&&this.videoState.setState(q.READY);const c=this.params.desiredState.videoTrack.getTransition();if(c&&s.isNonNullable(c.to)){this.params.desiredState.videoTrack.setState(c.to),this.params.output.currentVideoTrack$.next(this.trackUrls[c.to.id].track);const l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){const d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(l),d.playbackRate=l)}}this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=s.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.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),He(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState()?.id;s.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];s.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Yt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ke(t))}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.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!==q.STOPPED&&(this.videoState.startTransitionTo(q.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(q.STOPPED),A(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(),c=this.params.desiredState.seekState.getState();if(n&&e!==q.READY&&!o){this.handleQualityLimitTransition(n.to.max);return}if(e===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){const{currentTime:l}=this.video;this.prepare(),c.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:l*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&&c.state===I.Requested&&this.seek(c.position),e){case q.READY:t===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):t===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),A(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&&A(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&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}};handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){const r=Object.values(this.trackUrls).find(c=>!s.isInvariantQuality(c.track.quality)&&s.isLowerOrEqual(c.track.quality,e))?.track,n=this.params.desiredState.videoTrack.getState()?.id,o=this.trackUrls[n??"0"]?.track;if(r&&o&&s.isHigherOrEqual(o.quality,r.quality)&&(t=r),!t){const c=Object.values(this.trackUrls).filter(u=>!s.isInvariantQuality(u.track.quality)&&s.isHigher(u.track.quality,e)),l=c.length;l&&(t=c[l-1].track)}t&&(i=t.quality)}else if(!e){const r=Object.values(this.trackUrls).map(n=>n.track);t=Lt(r,{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 mi=["stun:videostun.mycdn.me:80"],Ka=1e3,Za=3,Ft=()=>null;class er{options;ws=null;peerConnection=null;serverUrl="";streamKey="";stream=null;signalingType="JOIN";retryTimeout;retryCount=0;externalStartCallback=Ft;externalStopCallback=Ft;externalErrorCallback=Ft;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:mi}]};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:s.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),Ka)}normalizeOptions(e={}){const t={stunServerList:mi,maxRetryNumber:Za,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var H;(function(a){a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused"})(H||(H={}));class tr{subscription;params;log;video;videoState=new z(H.STOPPED);liveStreamClient;maxSeekBackTime$=new s.ValueSubject(0);constructor(e){this.subscription=new s.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ue(e.container),this.liveStreamClient=new er(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),He(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:s.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};s.merge(this.videoState.stateChangeStarted$.pipe(s.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(s.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:c})=>{this.log({message:`[videoState change] ${c}: ${JSON.stringify(o)}`})});const r=Ye(this.video),n=(o,c)=>this.subscription.add(o.subscribe(c,i));n(r.timeUpdate$,e.liveTime$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(st(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===H.READY&&this.videoState.setState(H.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(je(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case H.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case H.READY:break;case H.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case H.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return s.assertNever(o.to)}},i)).add(s.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,s.observableFrom(["init"])).pipe(s.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(ke(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:s.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(H.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:s.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:s.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!==H.STOPPED&&(this.videoState.startTransitionTo(H.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(H.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(e===H.STOPPED){this.videoState.startTransitionTo(H.READY),this.prepare();return}if(n){this.prepare();return}switch(e){case H.READY:t===exports.PlaybackState.PAUSED?(this.videoState.setState(H.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):t===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed());return;case H.PLAYING:t===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(H.PAUSED),this.video.pause()):i?.to===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case H.PAUSED:t===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed()):i?.to===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return s.assertNever(e)}}}class Si{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}}var ie;(function(a){a.DASH="dash",a.HLS="hls",a.MPEG="mpeg",a.DASH_ANY_MPEG="dash_any_mpeg",a.DASH_ANY_WEBM="dash_any_webm",a.DASH_SEP="dash_sep"})(ie||(ie={}));var Re;(function(a){a.VP9="vp9",a.AV1="av1",a.NONE="none",a.SMOOTH="smooth",a.POWER_EFFICIENT="power_efficient"})(Re||(Re={}));const Ui=s.getCurrentBrowser().device===s.CurrentClientDevice.Android,Pt=document.createElement("video"),ir='video/mp4; codecs="avc1.42000a,mp4a.40.2"',sr='video/mp4; codecs="hev1.1.6.L93.B0"',Hi='video/webm; codecs="vp09.00.10.08"',ji='video/webm; codecs="av01.0.00M.08"',ar='audio/mp4; codecs="mp4a.40.2"',rr='audio/webm; codecs="opus"',Ve={mms:Fi(),mse:Ba(),hls:!!(Pt.canPlayType?.("application/x-mpegurl")||Pt.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ce={mp4:!!Pt.canPlayType?.("video/mp4"),webm:!!Pt.canPlayType?.("video/webm"),cmaf:!0},Ee={h264:!!Be()?.isTypeSupported?.(ir),h265:!!Be()?.isTypeSupported?.(sr),vp9:!!Be()?.isTypeSupported?.(Hi),av1:!!Be()?.isTypeSupported?.(ji),aac:!!Be()?.isTypeSupported?.(ar),opus:!!Be()?.isTypeSupported?.(rr)},ct=(Ee.h264||Ee.h265)&&Ee.aac;let Me;const nr=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:ji}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Hi}})]);Me={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{nr()}catch(a){console.error(a)}const ft=Ve.hls&&ce.mp4,or=()=>Object.keys(Ee).filter(a=>Ee[a]),cr=(a,e=!1,t=!1)=>{const i=Ve.mse||Ve.mms&&t;return a.filter(r=>{switch(r){case exports.VideoFormat.DASH_SEP:return i&&ce.mp4&&ct;case exports.VideoFormat.DASH_WEBM:return i&&ce.webm&&Ee.vp9&&Ee.opus;case exports.VideoFormat.DASH_WEBM_AV1:return i&&ce.webm&&Ee.av1&&Ee.opus;case exports.VideoFormat.DASH_LIVE:return Ve.mse&&ce.mp4&&ct;case exports.VideoFormat.DASH_LIVE_CMAF:return i&&ce.mp4&&ct&&ce.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return i&&ce.mp4&&ct;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ft||e&&Ve.mse&&ce.mp4&&ct;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ft;case exports.VideoFormat.MPEG:return ce.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ve.webrtc&&Ve.ws&&Ee.h264&&(ce.mp4||ce.webm);default:return s.assertNever(r)}})},xe=a=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(a){case Re.VP9:return[e,t];case Re.AV1:return[t,e];case Re.NONE:return[];case Re.SMOOTH:return Me?Me[t].smooth?[t,e]:Me[e].smooth?[e,t]:[t,e]:[e,t];case Re.POWER_EFFICIENT:return Me?Me[t].powerEfficient?[t,e]:Me[e].powerEfficient?[e,t]:[t,e]:[e,t];default:s.assertNever(a)}return[e,t]},ur=({webmCodec:a,androidPreferredFormat:e})=>{if(Ui)switch(e){case ie.MPEG:return[exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case ie.DASH:return[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];case ie.DASH_ANY_MPEG:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.DASH_ANY_WEBM:return[...xe(a),exports.VideoFormat.MPEG,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case ie.DASH_SEP:return[exports.VideoFormat.DASH_SEP,exports.VideoFormat.MPEG,...xe(a),exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];default:s.assertNever(e)}return ft?[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...xe(a),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},lr=({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],r=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...r],o=[...r,...i];let c;if(Ui)switch(a){case ie.DASH:case ie.DASH_ANY_MPEG:case ie.DASH_ANY_WEBM:case ie.DASH_SEP:{c=n;break}case ie.HLS:case ie.MPEG:{c=o;break}default:s.assertNever(a)}else ft?c=o:c=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...c]:[...c,exports.VideoFormat.WEB_RTC_LIVE]},bi=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 dr=a=>new s.Observable(e=>{const t=new s.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(s.map(({from:u,to:d})=>`${u}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,n=a.providerChanged$.pipe(s.map(({type:u})=>u!==void 0)),o=new s.Subject;let c=0,l="unknown";return t.add(i.subscribe(u=>{c&&window.clearTimeout(c),l=u,c=window.setTimeout(()=>o.next(u),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(c),l="unknown",c=0})),t.add(n.subscribe(u=>{c&&(window.clearTimeout(c),c=0,u&&(c=window.setTimeout(()=>o.next(l),a.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(c),t.unsubscribe()}});const hr={chunkDuration:5e3,maxParallelRequests:5};class fr{current$=new s.ValueSubject({type:void 0});providerError$=new s.Subject;noAvailableProvidersError$=new s.Subject;providerOutput={position$:new s.ValueSubject(0),duration$:new s.ValueSubject(1/0),volume$:new s.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new s.ValueSubject(void 0),currentVideoSegmentLength$:new s.ValueSubject(0),currentAudioSegmentLength$:new s.ValueSubject(0),availableVideoTracks$:new s.ValueSubject([]),availableAudioTracks$:new s.ValueSubject([]),isAudioAvailable$:new s.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new s.ValueSubject(!1),autoVideoTrackLimits$:new s.ValueSubject(void 0),currentBuffer$:new s.ValueSubject(void 0),isBuffering$:new s.ValueSubject(!0),error$:new s.Subject,warning$:new s.Subject,willSeekEvent$:new s.Subject,seekedEvent$:new s.Subject,loopedEvent$:new s.Subject,endedEvent$:new s.Subject,firstBytesEvent$:new s.Subject,firstFrameEvent$:new s.Subject,canplay$:new s.Subject,isLive$:new s.ValueSubject(void 0),isLowLatency$:new s.ValueSubject(!1),canChangePlaybackSpeed$:new s.ValueSubject(!0),liveTime$:new s.ValueSubject(void 0),liveBufferTime$:new s.ValueSubject(void 0),availableTextTracks$:new s.ValueSubject([]),currentTextTrack$:new s.ValueSubject(void 0),hostname$:new s.ValueSubject(void 0),httpConnectionType$:new s.ValueSubject(void 0),httpConnectionReused$:new s.ValueSubject(void 0),inPiP$:new s.ValueSubject(!1),inFullscreen$:new s.ValueSubject(!1),element$:new s.ValueSubject(void 0),elementVisible$:new s.ValueSubject(!0),availableSources$:new s.ValueSubject(void 0),is3DVideo$:new s.ValueSubject(!1)};subscription=new s.Subscription;screenFormatsIterator;chromecastFormatsIterator;log;params;failoverIndex;constructor(e){this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=cr([...lr(this.params.tuning),...ur(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(c=>s.isNonNullable(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let n=[];i?n=[i]:r.length?n=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.includes(c))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Si(n);const o=[...bi(!0),...bi(!1)];this.chromecastFormatsIterator=new Si(o.filter(c=>s.isNonNullable(e.sources[c]))),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(s.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:s.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}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(),r=i.state!==I.None;if(this.params.desiredState.seekState.setState({state:I.Requested,position:r?i.position:t,forcePrecise:r?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 ee.SCREEN:return this.createScreenProvider(t);case ee.CHROMECAST:return this.createChromecastProvider(t);default:return s.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const c=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t[exports.VideoFormat.HLS_ONDEMAND]||t[exports.VideoFormat.HLS]);return s.assertNonNullable(c),new ja({...o,source:c,sourceHls:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Ya({...o,source:c})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),ft||!this.params.tuning.useHlsJs?new Ja({...o,source:c}):new Ga({...o,source:c})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Qa({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Xa({...o,source:c})}case exports.VideoFormat.DASH_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new Vs({...o,source:c,config:{...hr,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const c=this.applyFailoverHost(t[e]);return s.assertNonNullable(c),new tr({container:i,source:c,desiredState:r,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 s.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:n}=this.params,o=this.providerOutput,c=this.params.dependencies.chromecastInitializer.connection$.getValue();return s.assertNonNullable(c),new cs({connection:c,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ee.CHROMECAST:ee.SCREEN}chooseFormat(e){switch(e){case ee.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ee.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return s.assertNever(e)}}skipFormat(e){switch(e){case ee.SCREEN:return this.screenFormatsIterator.next();case ee.CHROMECAST:return this.chromecastFormatsIterator.next();default:return s.assertNever(e)}}handleNoFormatsError(e){switch(e){case ee.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ee.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return s.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const n=new URL(r);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(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new s.Subscription;let t=!1,i=0;return e.add(s.merge(this.providerOutput.error$,dr({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(s.map(r=>({id:`ProviderHangup:${r}`,category:s.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(s.filter(({to:n})=>n===exports.PlaybackState.PLAYING),s.once()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const n=this.current$.getValue().destination;if(n===ee.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ee.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=r.category===s.ErrorCategory.NETWORK,c=r.category===s.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit&&!c;l&&!c&&(o&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(n??ee.SCREEN)}})),e}}const pr=5e3,gi="one_video_throughput",yi="one_video_rtt",lt=window.navigator.connection,vi=()=>{const a=lt?.downlink;if(s.isNonNullable(a)&&a!==10)return a*1e3},Ti=()=>{const a=lt?.rtt;if(s.isNonNullable(a)&&a!==3e3)return a},Ei=(a,e,t)=>{const i=t*8,r=i/a;return i/(r+e)};class dt{throughput;rtt;subscription=new s.Subscription;tuningConfig;concurrentDownloads=new Set;throughput$;rtt$;rttAdjustedThroughput$;constructor(e){this.tuningConfig=e;const t=dt.load(gi)||(e.useBrowserEstimation?vi():void 0)||pr,i=dt.load(yi)??(e.useBrowserEstimation?Ti():void 0)??0;if(this.throughput$=new s.ValueSubject(t),this.rtt$=new s.ValueSubject(i),this.rttAdjustedThroughput$=new s.ValueSubject(Ei(t,i,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(i,1,e),e.useBrowserEstimation){const r=()=>{const o=vi();o&&this.throughput.next(o);const c=Ti();s.isNonNullable(c)&&this.rtt.next(c)};lt&&"onchange"in lt&&this.subscription.add(s.fromEvent(lt,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{s.safeStorage.set(gi,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{s.safeStorage.set(yi,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(s.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(s.map(({throughput:r,rtt:n})=>Ei(r,n,e.rttPenaltyRequestSize)),s.filter(r=>{const n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=s.now();const r=new s.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(s.fromEvent(e,"progress").pipe(s.once()).subscribe(n=>{t=n.loaded,i=s.now()}));break;case 1:case 0:r.add(s.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=s.now()}));break}r.add(s.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,c=s.now(),l=o-t,u=c-i;this.addRawSpeed(l,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,n=s.now(),o=0,c=s.now();const l=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:h})=>{if(d)!t&&this.addRawSpeed(r,s.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(s.now()-c<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=h.byteLength;else{const f=c-n;f&&this.addRawSpeed(o,f,1,t),o=h.byteLength,n=s.now()}c=s.now()}else r+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&s.now()-c>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,s.now()-c,this.concurrentDownloads.size),o=0,c=s.now());await i?.read().then(u,l)}};this.concurrentDownloads.add(e),i?.read().then(u,l)}addRawSpeed(e,t,i=1,r=!1){if(dt.sanityCheck(e,t,r)){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 r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){const t=s.safeStorage.get(e);if(s.isNonNullable(t))return parseInt(t,10)??void 0}}const ki={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,backgroundVideoQualityLimit:s.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:s.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,crashOnStallTimeout:3e4,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:Re.VP9,androidPreferredFormat:ie.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},mr=a=>({...s.fillWithDefault(a,ki),configName:[...a.configName??[],...ki.configName]});var Ai=({seekState:a,position$:e})=>s.merge(a.stateChangeEnded$.pipe(s.map(({to:t})=>t.state===I.None?void 0:(t.position??NaN)/1e3),s.filter(s.isNonNullable)),e.pipe(s.filter(()=>a.getState().state===I.None))),Sr=a=>{const e=typeof a.container=="string"?document.getElementById(a.container):a.container;return s.assertNonNullable(e,`Wrong container or containerId {${a.container}}`),e};const br=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(s.filter(r=>r.length>0),s.once()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};class gr{subscription=new s.Subscription;domContainer;providerContainer;chromecastInitializer;logger=new s.Logger;abrLogger=this.logger.createComponentLog("ABR");config;tuning;throughputEstimator;isPlaybackStarted=!1;initedAt;hasLiveOffsetByPaused=new s.ValueSubject(!1);hasLiveOffsetByPausedTimer=0;desiredState={playbackState:new z(exports.PlaybackState.STOPPED),seekState:new z({state:I.None}),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),autoVideoTrackSwitching:new z(!0),autoVideoTrackLimits:new z({}),isLooped:new z(!1),playbackRate:new z(1),externalTextTracks:new z([]),internalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({}),cameraOrientation:new z({x:0,y:0})};info={playbackState$:new s.ValueSubject(exports.PlaybackState.STOPPED),position$:new s.ValueSubject(0),duration$:new s.ValueSubject(1/0),muted$:new s.ValueSubject(!1),volume$:new s.ValueSubject(1),availableQualities$:new s.ValueSubject([]),availableQualitiesFps$:new s.ValueSubject({}),availableAudioTracks$:new s.ValueSubject([]),isAudioAvailable$:new s.ValueSubject(!0),currentQuality$:new s.ValueSubject(void 0),isAutoQualityEnabled$:new s.ValueSubject(!0),autoQualityLimitingAvailable$:new s.ValueSubject(!1),autoQualityLimits$:new s.ValueSubject({}),currentPlaybackRate$:new s.ValueSubject(1),currentBuffer$:new s.ValueSubject({start:0,end:0}),isBuffering$:new s.ValueSubject(!0),isStalled$:new s.ValueSubject(!1),isEnded$:new s.ValueSubject(!1),isLooped$:new s.ValueSubject(!1),isLive$:new s.ValueSubject(void 0),canChangePlaybackSpeed$:new s.ValueSubject(void 0),atLiveEdge$:new s.ValueSubject(void 0),atLiveDurationEdge$:new s.ValueSubject(void 0),liveTime$:new s.ValueSubject(void 0),liveBufferTime$:new s.ValueSubject(void 0),currentFormat$:new s.ValueSubject(void 0),availableTextTracks$:new s.ValueSubject([]),currentTextTrack$:new s.ValueSubject(void 0),throughputEstimation$:new s.ValueSubject(void 0),rttEstimation$:new s.ValueSubject(void 0),videoBitrate$:new s.ValueSubject(void 0),hostname$:new s.ValueSubject(void 0),httpConnectionType$:new s.ValueSubject(void 0),httpConnectionReused$:new s.ValueSubject(void 0),surface$:new s.ValueSubject(exports.Surface.NONE),chromecastState$:new s.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new s.ValueSubject(void 0),intrinsicVideoSize$:new s.ValueSubject(void 0),availableSources$:new s.ValueSubject(void 0),is3DVideo$:new s.ValueSubject(!1),currentVideoSegmentLength$:new s.ValueSubject(0),currentAudioSegmentLength$:new s.ValueSubject(0)};events={inited$:new s.Subject,ready$:new s.Subject,started$:new s.Subject,playing$:new s.Subject,paused$:new s.Subject,stopped$:new s.Subject,willStart$:new s.Subject,willResume$:new s.Subject,willPause$:new s.Subject,willStop$:new s.Subject,willDestruct$:new s.Subject,watchCoverageRecord$:new s.Subject,watchCoverageLive$:new s.Subject,managedError$:new s.Subject,fatalError$:new s.Subject,ended$:new s.Subject,looped$:new s.Subject,seeked$:new s.Subject,willSeek$:new s.Subject,firstBytes$:new s.Subject,firstFrame$:new s.Subject,canplay$:new s.Subject,log$:new s.Subject};experimental={element$:new s.ValueSubject(void 0),tuningConfigName$:new s.ValueSubject([]),enableDebugTelemetry$:new s.ValueSubject(!1),dumpTelemetry:gs};constructor(e={configName:[]}){if(this.initLogs(),this.tuning=mr(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new dt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,r);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(c){const l=o.map(h=>JSON.stringify(h,(p,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),u=`Player.${String(i)}`,d=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:s.ErrorCategory.WTF,message:d,thrown:c}),c}}}})}initVideo(e){return this.config=e,this.domContainer=Sr(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new fr({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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),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&&!Ut()?s.fromEvent(document,"visibilitychange").pipe(s.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(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:I.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){s.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(s.filter(i=>i.length>0),s.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){s.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 br(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 r=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+n.x,y:r.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(s.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===I.None?void 0:t.position;return s.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:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(s.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(s.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(s.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(s.filter(({from:e})=>e===exports.PlaybackState.STOPPED),s.once()).subscribe(()=>{this.initedAt=s.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===I.Requested?this.desiredState.seekState.setState({...o,state:I.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:s.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===I.Applying&&(this.desiredState.seekState.setState({state:I.None}),this.events.seeked$.next())})).add(e.current$.pipe(s.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(s.map(o=>o.destination),s.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(s.map(o=>o.map(({quality:c})=>c).sort((c,l)=>s.isInvariantQuality(c)?1:s.isInvariantQuality(l)?-1:s.isHigher(l,c)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const c={};for(const l of o)l.fps&&(c[l.quality]=l.fps);this.info.availableQualitiesFps$.next(c)})).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.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(s.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(s.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(s.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(s.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(s.combine({hasLiveOffsetByPaused:s.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(s.map(o=>o.to),s.filterChanged(),s.map(o=>o===exports.PlaybackState.PAUSED)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:o,isLowLatency:c})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),o){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(c));return}this.hasLiveOffsetByPaused.next(!1)})).add(s.combine({atLiveEdge:s.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ai({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(s.map(({isLive:o,position:c,isLowLatency:l})=>{const u=this.getActiveLiveDelay(l);return o&&Math.abs(c)<u/1e3}),s.filterChanged(),s.tap(o=>o&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(s.map(({atLiveEdge:o,hasPausedTimeoutCase:c})=>o&&!c)).subscribe(this.info.atLiveEdge$)).add(s.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(s.map(({isLive:o,position:c,duration:l})=>o&&(Math.abs(l)-Math.abs(c))*1e3<this.tuning.live.activeLiveDelay),s.filterChanged(),s.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(s.map(o=>o.muted),s.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(s.map(o=>o.volume),s.filterChanged()).subscribe(this.info.volume$)).add(Ai({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(s.merge(e.providerOutput.endedEvent$.pipe(s.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(s.mapTo(!1))).pipe(s.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(s.map(o=>({id:o?`No${o}`:"NoProviders",category:s.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(s.once(),s.map(o=>o??s.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(s.once(),s.map(()=>s.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(s.once(),s.map(()=>s.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 s.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new s.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(s.filter(({to:o})=>o===exports.PlaybackState.PLAYING),s.once()).subscribe(()=>i.next(!1)));let r=0;const n=s.merge(e.providerOutput.isBuffering$,t,i).pipe(s.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),c=t.getValue()||i.getValue();return o&&!c}),s.filterChanged());this.subscription.add(n.subscribe(o=>{o?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(s.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 c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o?.size?.width,height:o?.size?.height},{width:c?.videoWidth,height:c?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(s.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),c=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue();let h;d===exports.ChromecastState.CONNECTED?h=exports.Surface.SECOND_SCREEN:l?u?o?h=exports.Surface.PIP:c?h=exports.Surface.FULLSCREEN:h=exports.Surface.INLINE:h=exports.Surface.INVISIBLE: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(s.map(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new s.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(s.filterChanged((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(s.filter(i=>i.length>0),s.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;const i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Lt(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(s.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(s.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(s.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(s.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;s.assertNonNullable(this.providerContainer),s.assertNonNullable(e),bs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ss(t)),this.providerContainer.current$.subscribe(({type:t})=>vt("provider",t)),e.duration$.subscribe(t=>vt("duration",t)),e.availableVideoTracks$.pipe(s.filter(t=>!!t.length),s.once()).subscribe(t=>vt("tracks",t)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(s.map(t=>t?.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(t=>this.subscription.add(t)),vt("codecs",or())}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(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:s.ErrorCategory.DOM,message:String(r)})})};this.subscription.add(s.merge(s.fromEvent(document,"visibilitychange"),s.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!e?.released;r&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}}const yr=`@vkontakte/videoplayer-core@${wi}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return s.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return s.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return s.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return s.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return s.VideoQuality}});exports.Player=gr;exports.SDK_VERSION=yr;exports.VERSION=wi;
|
|
56
|
+
|
|
57
|
+
varying vec2 v_texel; // [0..1, 0..1]
|
|
58
|
+
|
|
59
|
+
uniform sampler2D u_texture;
|
|
60
|
+
uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
|
|
61
|
+
|
|
62
|
+
void main(void) {
|
|
63
|
+
// center point of output projection
|
|
64
|
+
float lambda0 = u_focus.x / 360.0;
|
|
65
|
+
float phi0 = u_focus.y / 180.0;
|
|
66
|
+
|
|
67
|
+
float lambda = PI * 2.0 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
|
|
68
|
+
float phi = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
|
|
69
|
+
|
|
70
|
+
float p = sqrt(lambda * lambda + phi * phi); // rou
|
|
71
|
+
float c = atan(p);
|
|
72
|
+
float cos_c = cos(c);
|
|
73
|
+
float sin_c = sin(c);
|
|
74
|
+
|
|
75
|
+
// geo coordinates of projection
|
|
76
|
+
float x = lambda0 + atan(
|
|
77
|
+
lambda * sin_c,
|
|
78
|
+
p * cos(phi0) * cos_c - phi * sin(phi0) * sin_c
|
|
79
|
+
);
|
|
80
|
+
float y = asin(cos_c * sin(phi0) + (phi * sin_c * cos(phi0)) / p);
|
|
81
|
+
|
|
82
|
+
// reprojected texture coordinates
|
|
83
|
+
vec2 tc = vec2(
|
|
84
|
+
mod(x / (PI * 2.0) - 0.5, 1.0), // [0..1]
|
|
85
|
+
mod(y / PI - 0.5, 1.0) // [0..1]
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
// sample using new coordinates
|
|
89
|
+
gl_FragColor = texture2D(u_texture, tc);
|
|
90
|
+
}
|
|
91
|
+
`;var Ja=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new za(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ka(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();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),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(r,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(a,0),this.gl.uniform2f(s,-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(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Pf,this.gl.VERTEX_SHADER),r=this.createShader(kf,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),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(){let 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(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,l=t-a,u=e+r,c=t+a,d=e-r,f=t+a;return[s,n,o,l,u,c,d,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(){let 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}};var Gt=class{constructor(e){this.subscription=new D.Subscription;this.videoState=new H("stopped");this.elementSize$=new D.ValueSubject(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new Na;this.videoTracks$=new D.ValueSubject([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Va;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("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("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("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()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,D.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ja(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});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=be(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(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Qa({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Se(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:D.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.videoTracks$.pipe((0,D.map)(u=>u.map(({track:c})=>c)))}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,D.filter)(D.isNonNullable),(0,D.once)()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Je(this.video,t.isLooped,a)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,D.observeElementSize)(this.video),this.elementSize$),s($e(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){let c=[];this.audioTracks=[],this.textTracks=[];let d=this.player.getRepresentations();(0,D.assertNonNullable)(d,"Manifest not loaded or empty");let f=Array.from(d.audio).sort((g,T)=>T.bitrate-g.bitrate),h=Array.from(d.video).sort((g,T)=>T.bitrate-g.bitrate),b=Array.from(d.text);if(!this.params.tuning.isAudioDisabled)for(let g of f){let T=ff(g);T&&this.audioTracks.push({track:T,representation:g})}for(let g of h){let T=hf(g);if(T){c.push({track:T,representation:g});let y=!this.params.tuning.isAudioDisabled&&mf(f,h,g);y&&this.audioRepresentations.set(g.id,y)}}this.videoTracks$.next(c);for(let g of b){let T=bf(g);T&&this.textTracks.push({track:T,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));let I=this.selectVideoRepresentation();(0,D.assertNonNullable)(I),this.player.initRepresentations(I.id,this.audioRepresentations.get(I.id)?.id,this.params.sourceHls)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:D.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add((0,D.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,D.fromEvent)(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);let h=this.params.desiredState.autoVideoTrackSwitching.getState(),b=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let I=d.id;!this.params.output.elementVisible$.getValue()&&h&&(I=this.videoTracks$.getValue().map(T=>T.representation).sort((T,y)=>y.bitrate-T.bitrate).filter(T=>{let y=(0,D.videoSizeToQuality)(T),M=(0,D.videoSizeToQuality)(d);if(y&&M)return(0,D.isLowerOrEqual)(y,M)&&(0,D.isLowerOrEqual)(y,b)}).map(T=>T.id)[0]),this.player.switchRepresentation("video",I).catch(n);let g=this.audioRepresentations.get(d.id);g&&this.player.switchRepresentation("audio",g.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,D.filterChanged)(),(0,D.map)(u=>u&&this.videoTracks$.getValue().find(({representation:{id:c}})=>c===u)?.track)).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,D.map)(({to:u})=>u==="ready"),(0,D.filterChanged)());this.subscription.add((0,D.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,D.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,D.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,D.observableFrom)(["init"])).pipe((0,D.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,r=this.videoTracks$.getValue().find(({track:{id:d}})=>d===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),s=Pt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),l=Math.max(r&&!e?this.audioRepresentations.get(r.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),u=xt(this.videoTracks$.getValue().map(({track:d})=>d),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:l,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?u??r:r??u;return c&&this.videoTracks$.getValue().find(({track:d})=>d===c)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.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),ge(this.video)}};var ki=class extends Gt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Yt=require("@vkontakte/videoplayer-shared");var wi=class extends Gt{constructor(e){super(e),this.liveOffset=new nt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Yt.combine)({interval:(0,Yt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let s=e.position$.getValue()+(a-1);e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add((0,Yt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Yt.map)(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var wf=_e(Ma(),1);var q=require("@vkontakte/videoplayer-shared"),Ge={};var Sr=(i,e)=>new q.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ai=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("initializing");this.textTracksManager=new Le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,q.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,q.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,q.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,q.assertNever)(e)}break;default:(0,q.assertNever)(t)}};this.video=be(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(oe(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),ge(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:q.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,wf.default)(import("hls.js").then(a=>{e||(Ge.Hls=a.default,Ge.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,q.assertNonNullable)(Ge.Hls,"hls.js not loaded"),this.hls=new Ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,q.assertNonNullable)(Ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:q.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Se(this.video),s=(u,c)=>this.subscription.add(u.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Je(this.video,e.isLooped,r)),this.subscription.add(ve(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Re(this.video,e.playbackRate,a.playbackRateState$,r)),s($e(this.video),t.elementVisible$),this.subscription.add(Sr(this.hls,Ge.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:q.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Sr(this.hls,Ge.Events.MANIFEST_PARSED).pipe((0,q.map)(({levels:u})=>u.reduce((c,d)=>{let f=d.name||d.height.toString(10),{width:h,height:b}=d,I=Et(d.attrs.QUALITY??"")??(0,q.videoSizeToQuality)({width:h,height:b});if(!I)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:f.toString(),quality:I,bitrate:d.bitrate/1e3,size:{width:h,height:b},fps:g};return this.trackLevels.set(f,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Sr(this.hls,Ge.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let f=d.name,h=d.attrs.URI||"",b=d.lang,I="internal";c.push({id:f,url:h,language:b,type:I})}e.internalTextTracks.startTransitionTo(c)}}),s(Sr(this.hls,Ge.Events.LEVEL_LOADING).pipe((0,q.map)(({url:u})=>oe(u))),t.hostname$),s(Sr(this.hls,Ge.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(It(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=Sr(this.hls,Ge.Events.LEVEL_SWITCHED).pipe((0,q.map)(({level:u})=>n(this.hls.levels[u])));o.pipe((0,q.filter)(q.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(It(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if((0,q.isNullable)(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),f=this.hls.currentLevel,h=this.hls.levels[f];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=(0,q.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ye(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("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("stopped"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Af="X-Playback-Duration",Io=async i=>{let e=await lt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(Af)?parseInt(e.headers.get(Af),10):void 0};var _=require("@vkontakte/videoplayer-shared");var xo=_e(Ia(),1);var Xa=require("@vkontakte/videoplayer-shared");var KE=i=>{let e=null;if(i.QUALITY&&(e=Et(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,Xa.videoSizeToQuality)({width:t,height:r})}return e??null},JE=(i,e)=>{let t=i.split(`
|
|
92
|
+
`),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),l=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!l)){if(o){let u=(0,xo.default)(o[1].split(",").map(g=>g.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=KE(u),f;u.BANDWIDTH&&(f=parseInt(u.BANDWIDTH,10)/1e3||void 0),!f&&u["AVERAGE-BANDWIDTH"]&&(f=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,b;if(u.RESOLUTION){let[g,T]=u.RESOLUTION.split("x").map(y=>parseInt(y,10));g&&T&&(b={width:g,height:T})}let I=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:I,bandwidth:f,size:b,fps:h})}if(l){let u=(0,xo.default)(l[1].split(",").map(h=>h.split("=")).map(([h,b])=>[h,b.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,f=u.NAME;c&&d&&a.push({type:"internal",id:d,label:f,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},XE=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Eo=0,Rf=async(i,e=i,t)=>{let a=await(await lt(i)).text();Eo+=1;try{let{qualityManifests:s,textTracks:n}=JE(a,e);return{qualityManifests:s,textTracks:n}}catch{if(Eo<=t.manifestRetryMaxCount)return await XE((0,Xa.getExponentialDelay)(Eo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Rf(i,e,t)}return{qualityManifests:[],textTracks:[]}},Za=Rf;var Ri=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Le;this.manifests$=new _.ValueSubject([]);this.liveOffset=new nt;this.manifestStartTime$=new _.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("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("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):a?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("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 c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,_.assertNever)(t)}};this.params=e,this.video=be(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_.VideoQuality.INVARIANT,url:this.params.source.url},Za(de(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_.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(oe(this.params.source.url)),this.maxSeekBackTime$=new _.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:_.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),s($e(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,_.filterChanged)(),(0,_.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(0,_.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let f=this.manifests$.getValue().find(h=>h.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(oe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,_.combine)({startTime:this.manifestStartTime$.pipe((0,_.filter)(_.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe((0,_.map)(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:f})=>({id:l,quality:u,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,_.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,_.observableFrom)(["init"])).pipe((0,_.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){let e=this.selectManifest();if((0,_.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:l}=t?.to??r??{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=de(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Io(n).then(o=>{if(!(0,_.isNullable)(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if((0,_.isNullable)(l)||!isFinite(l))try{lt(n).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let d=new URL(c,n).toString();Io(d).then(f=>{(0,_.isNullable)(f)||this.maxSeekBackTime$.next(f)})}})}catch{}}})}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var G=require("@vkontakte/videoplayer-shared");var Li=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Le;this.manifests$=new G.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("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("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):a?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};this.params=e,this.video=be(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Za(de(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:G.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(0,G.isNonNullable)(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let f=this.manifests$.getValue().find(h=>h.id===d);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(oe(f.url));let h=this.params.desiredState.playbackRate.getState(),b=this.params.output.element$.getValue()?.playbackRate;if(h!==b){let I=this.params.output.element$.getValue();I&&(this.params.desiredState.playbackRate.setState(h),I.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,G.map)(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:f})=>({id:l,quality:u,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!(0,G.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,G.merge)((0,G.fromEvent)(o,"addtrack"),(0,G.fromEvent)(o,"removetrack"),(0,G.fromEvent)(o,"change"),(0,G.observableFrom)(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){let e=this.selectManifest();if((0,G.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var $i=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("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("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=be(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),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(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=Se(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,a.playbackRateState$,r)),s($e(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,J.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(l),c.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,J.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ge(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,J.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,J.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!(0,J.isInvariantQuality)(o.track.quality)&&(0,J.isLowerOrEqual)(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&(0,J.isHigherOrEqual)(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!(0,J.isInvariantQuality)(u.track.quality)&&(0,J.isHigher)(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=xt(a,{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:r})}};var Z=require("@vkontakte/videoplayer-shared");var $f=require("@vkontakte/videoplayer-shared"),Lf=["stun:videostun.mycdn.me:80"],ZE=1e3,ex=3,Po=()=>null,es=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Po;this.externalStopCallback=Po;this.externalErrorCallback=Po;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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{let 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{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Lf}]};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);let 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:$f.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){let 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){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))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(){let 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),ZE)}normalizeOptions(e={}){let t={stunServerList:Lf,maxRetryNumber:ex,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ci=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new Z.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("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("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,Z.assertNever)(e)}};this.subscription=new Z.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container),this.liveStreamClient=new es(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),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Z.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,Z.merge)(this.videoState.stateChangeStarted$.pipe((0,Z.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Z.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=Se(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s($e(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ve(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,Z.assertNever)(n.to)}},r)).add((0,Z.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,Z.observableFrom)(["init"])).pipe((0,Z.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(oe(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:Z.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("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:Z.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Z.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Di=class{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}};var S=require("@vkontakte/videoplayer-shared");var ht=require("@vkontakte/videoplayer-shared"),Cf=(0,ht.getCurrentBrowser)().device===ht.CurrentClientDevice.Android,ts=document.createElement("video"),ix='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ax='video/mp4; codecs="hev1.1.6.L93.B0"',Df='video/webm; codecs="vp09.00.10.08"',Mf='video/webm; codecs="av01.0.00M.08"',sx='audio/mp4; codecs="mp4a.40.2"',nx='audio/webm; codecs="opus"',Wt={mms:Wa(),mse:Tf(),hls:!!(ts.canPlayType?.("application/x-mpegurl")||ts.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},De={mp4:!!ts.canPlayType?.("video/mp4"),webm:!!ts.canPlayType?.("video/webm"),cmaf:!0},Ze={h264:!!pt()?.isTypeSupported?.(ix),h265:!!pt()?.isTypeSupported?.(ax),vp9:!!pt()?.isTypeSupported?.(Df),av1:!!pt()?.isTypeSupported?.(Mf),aac:!!pt()?.isTypeSupported?.(sx),opus:!!pt()?.isTypeSupported?.(nx)},Mi=(Ze.h264||Ze.h265)&&Ze.aac,Qt,ox=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Mf}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Df}})]);Qt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{ox()}catch(i){console.error(i)}var yr=Wt.hls&&De.mp4,Of=()=>Object.keys(Ze).filter(i=>Ze[i]),Bf=(i,e=!1,t=!1)=>{let r=Wt.mse||Wt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&De.mp4&&Mi;case"DASH_WEBM":return r&&De.webm&&Ze.vp9&&Ze.opus;case"DASH_WEBM_AV1":return r&&De.webm&&Ze.av1&&Ze.opus;case"DASH_LIVE":return Wt.mse&&De.mp4&&Mi;case"DASH_LIVE_CMAF":return r&&De.mp4&&Mi&&De.cmaf;case"DASH_ONDEMAND":return r&&De.mp4&&Mi;case"HLS":case"HLS_ONDEMAND":return yr||e&&Wt.mse&&De.mp4&&Mi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return yr;case"MPEG":return De.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Wt.webrtc&&Wt.ws&&Ze.h264&&(De.mp4||De.webm);default:return(0,ht.assertNever)(a)}})},wt=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Qt?Qt[t].smooth?[t,e]:Qt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Qt?Qt[t].powerEfficient?[t,e]:Qt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ht.assertNever)(i)}return[e,t]},Vf=({webmCodec:i,androidPreferredFormat:e})=>{if(Cf)switch(e){case"mpeg":return["MPEG",...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...wt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...wt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:(0,ht.assertNever)(e)}return yr?[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...wt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},_f=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o;if(Cf)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,ht.assertNever)(i)}else yr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ko=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];var ft=require("@vkontakte/videoplayer-shared"),Nf=i=>new ft.Observable(e=>{let t=new ft.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,ft.map)(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,ft.map)(({type:u})=>u!==void 0)),n=new ft.Subject,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var ux={chunkDuration:5e3,maxParallelRequests:5},Oi=class{constructor(e){this.current$=new S.ValueSubject({type:void 0});this.providerError$=new S.Subject;this.noAvailableProvidersError$=new S.Subject;this.providerOutput={position$:new S.ValueSubject(0),duration$:new S.ValueSubject(1/0),volume$:new S.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new S.ValueSubject(void 0),currentVideoSegmentLength$:new S.ValueSubject(0),currentAudioSegmentLength$:new S.ValueSubject(0),availableVideoTracks$:new S.ValueSubject([]),availableAudioTracks$:new S.ValueSubject([]),isAudioAvailable$:new S.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new S.ValueSubject(!1),autoVideoTrackLimits$:new S.ValueSubject(void 0),currentBuffer$:new S.ValueSubject(void 0),isBuffering$:new S.ValueSubject(!0),error$:new S.Subject,warning$:new S.Subject,willSeekEvent$:new S.Subject,seekedEvent$:new S.Subject,loopedEvent$:new S.Subject,endedEvent$:new S.Subject,firstBytesEvent$:new S.Subject,firstFrameEvent$:new S.Subject,canplay$:new S.Subject,isLive$:new S.ValueSubject(void 0),isLowLatency$:new S.ValueSubject(!1),canChangePlaybackSpeed$:new S.ValueSubject(!0),liveTime$:new S.ValueSubject(void 0),liveBufferTime$:new S.ValueSubject(void 0),availableTextTracks$:new S.ValueSubject([]),currentTextTrack$:new S.ValueSubject(void 0),hostname$:new S.ValueSubject(void 0),httpConnectionType$:new S.ValueSubject(void 0),httpConnectionReused$:new S.ValueSubject(void 0),inPiP$:new S.ValueSubject(!1),inFullscreen$:new S.ValueSubject(!1),element$:new S.ValueSubject(void 0),elementVisible$:new S.ValueSubject(!0),availableSources$:new S.ValueSubject(void 0),is3DVideo$:new S.ValueSubject(!1)};this.subscription=new S.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Bf([..._f(this.params.tuning),...Vf(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,S.isNonNullable)(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new Di(s);let n=[...ko(!0),...ko(!1)];this.chromecastFormatsIterator=new Di(n.filter(o=>(0,S.isNonNullable)(e.sources[o]))),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(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,S.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:S.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,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(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,S.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,S.assertNonNullable)(o),new ki({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new wi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),yr||!this.params.tuning.useHlsJs?new Li({...n,source:o}):new Ai({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ri({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new $i({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ph({...n,source:o,config:{...ux,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ci({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,S.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,S.assertNonNullable)(o),new jr({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,S.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,S.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,S.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,Ff.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new S.Subscription,t=!1,r=0;return e.add((0,S.merge)(this.providerOutput.error$,Nf({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,S.map)(a=>({id:`ProviderHangup:${a}`,category:S.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe((0,S.filter)(({to:s})=>s==="playing"),(0,S.once)()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===S.ErrorCategory.NETWORK,o=a.category===S.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}})),e}};var O=require("@vkontakte/videoplayer-shared");var lx=5e3,qf="one_video_throughput",Uf="one_video_rtt",Bi=window.navigator.connection,Hf=()=>{let i=Bi?.downlink;if((0,O.isNonNullable)(i)&&i!==10)return i*1e3},jf=()=>{let i=Bi?.rtt;if((0,O.isNonNullable)(i)&&i!==3e3)return i},Gf=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},wo=class i{constructor(e){this.subscription=new O.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(qf)||(e.useBrowserEstimation?Hf():void 0)||lx,r=i.load(Uf)??(e.useBrowserEstimation?jf():void 0)??0;if(this.throughput$=new O.ValueSubject(t),this.rtt$=new O.ValueSubject(r),this.rttAdjustedThroughput$=new O.ValueSubject(Gf(t,r,e.rttPenaltyRequestSize)),this.throughput=Ht.getSmoothedValue(t,-1,e),this.rtt=Ht.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Hf();n&&this.throughput.next(n);let o=jf();(0,O.isNonNullable)(o)&&this.rtt.next(o)};Bi&&"onchange"in Bi&&this.subscription.add((0,O.fromEvent)(Bi,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{O.safeStorage.set(qf,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{O.safeStorage.set(Uf,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,O.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,O.map)(({throughput:a,rtt:s})=>Gf(a,s,e.rttPenaltyRequestSize)),(0,O.filter)(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,O.now)(),a=new O.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,O.fromEvent)(e,"progress").pipe((0,O.once)()).subscribe(s=>{t=s.loaded,r=(0,O.now)()}));break;case 1:case 0:a.add((0,O.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,O.now)()}));break}a.add((0,O.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,O.now)(),l=n-t,u=o-r;this.addRawSpeed(l,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=(0,O.now)(),n=0,o=(0,O.now)(),l=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,(0,O.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if((0,O.now)()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=(0,O.now)()}o=(0,O.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,O.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,O.now)()-o,this.concurrentDownloads.size),n=0,o=(0,O.now)());await r?.read().then(u,l)}};this.concurrentDownloads.add(e),r?.read().then(u,l)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=O.safeStorage.get(e);if((0,O.isNonNullable)(t))return parseInt(t,10)??void 0}},Yf=wo;var Vi=require("@vkontakte/videoplayer-shared"),Wf={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,backgroundVideoQualityLimit:Vi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Vi.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,crashOnStallTimeout:3e4,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:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Qf=i=>({...(0,Vi.fillWithDefault)(i,Wf),configName:[...i.configName??[],...Wf.configName]});var p=require("@vkontakte/videoplayer-shared");var mt=require("@vkontakte/videoplayer-shared"),Ao=({seekState:i,position$:e})=>(0,mt.merge)(i.stateChangeEnded$.pipe((0,mt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,mt.filter)(mt.isNonNullable)),e.pipe((0,mt.filter)(()=>i.getState().state==="none")));var zf=require("@vkontakte/videoplayer-shared"),Kf=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,zf.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var rs=require("@vkontakte/videoplayer-shared"),Jf=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,rs.filter)(a=>a.length>0),(0,rs.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var _i=class{constructor(e={configName:[]}){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,firstBytes$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:Th};if(this.initLogs(),this.tuning=Qf(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Wi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Yf(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let l=n.map(d=>JSON.stringify(d,(f,h)=>{let b=typeof h;return["number","string","boolean"].includes(b)?h:h===null?null:`<${b}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:p.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Kf(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Oi({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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Kr()?(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){(0,p.assertNonNullable)(this.providerContainer);let 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((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,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){(0,p.assertNonNullable)(this.providerContainer);let 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 Jf(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){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(n=>n.destination),(0,p.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe((0,p.map)(n=>n.map(({quality:o})=>o).sort((o,l)=>(0,p.isInvariantQuality)(o)?1:(0,p.isInvariantQuality)(l)?-1:(0,p.isHigher)(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.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(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,p.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(n=>n.to),(0,p.filterChanged)(),(0,p.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ao({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(Ao({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.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((0,p.map)(n=>({id:n?`No${n}`:"NoProviders",category:p.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} 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((0,p.once)(),(0,p.map)(n=>n??(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.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$));let t=new p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,p.filterChanged)());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add((0,p.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,p.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":l?u?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,p.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=xt(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((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.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(){let e=this.providerContainer?.providerOutput;(0,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),yh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Sh(t)),this.providerContainer.current$.subscribe(({type:t})=>Yr("provider",t)),e.duration$.subscribe(t=>Yr("duration",t)),e.availableVideoTracks$.pipe((0,p.filter)(t=>!!t.length),(0,p.once)()).subscribe(t=>Yr("tracks",t)),this.events.fatalError$.subscribe(new pe("fatalError")),this.events.managedError$.subscribe(new pe("managedError")),e.position$.subscribe(new pe("position")),e.currentVideoTrack$.pipe((0,p.map)(t=>t?.quality)).subscribe(new pe("quality")),this.info.currentBuffer$.subscribe(new pe("buffer")),e.isBuffering$.subscribe(new pe("isBuffering"))].forEach(t=>this.subscription.add(t)),Yr("codecs",Of())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:p.ErrorCategory.DOM,message:String(a)})})};this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var et=require("@vkontakte/videoplayer-shared"),cx=`@vkontakte/videoplayer-core@${ls}`;
|