@vkontakte/videoplayer-core 2.0.106-dev.eacdae04.0 → 2.0.106
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 +23 -23
- package/es2015.esm.js +23 -23
- package/es2018.cjs.js +24 -24
- package/es2018.esm.js +24 -24
- package/esnext.cjs.js +22 -22
- package/esnext.esm.js +21 -21
- package/evergreen.esm.js +8 -8
- package/package.json +2 -2
- package/types/player/Player.d.ts +0 -1
- package/types/player/types.d.ts +0 -4
- package/types/providers/utils/guessNetworkErrorCause.d.ts +2 -0
- package/types/providers/utils/HTMLVideoElement/clear.d.ts +0 -1
package/es2015.cjs.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.106
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.106
|
|
3
|
+
* Mon, 12 Aug 2024 11:53:00 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-106/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var On=Object.create;var Kt=Object.defineProperty,_n=Object.defineProperties,Nn=Object.getOwnPropertyDescriptor,Fn=Object.getOwnPropertyDescriptors,Un=Object.getOwnPropertyNames,Ha=Object.getOwnPropertySymbols,Hn=Object.getPrototypeOf,Wa=Object.prototype.hasOwnProperty,Gn=Object.prototype.propertyIsEnumerable;var He=Math.pow,Ga=(n,e,t)=>e in n?Kt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,V=(n,e)=>{for(var t in e||(e={}))Wa.call(e,t)&&Ga(n,t,e[t]);if(Ha)for(var t of Ha(e))Gn.call(e,t)&&Ga(n,t,e[t]);return n},J=(n,e)=>_n(n,Fn(e));var Wn=(n,e)=>{for(var t in e)Kt(n,t,{get:e[t],enumerable:!0})},Qa=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Un(e))!Wa.call(n,r)&&r!==t&&Kt(n,r,{get:()=>e[r],enumerable:!(i=Nn(e,r))||i.enumerable});return n};var Qn=(n,e,t)=>(t=n!=null?On(Hn(n)):{},Qa(e||!n||!n.__esModule?Kt(t,"default",{value:n,enumerable:!0}):t,n)),Yn=n=>Qa(Kt({},"__esModule",{value:!0}),n);var R=(n,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(d){r(d)}},s=u=>{try{o(t.throw(u))}catch(d){r(d)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,s);o((t=t.apply(n,e)).next())}),jn=function(n,e){this[0]=n,this[1]=e},pe=(n,e,t)=>{var i=(s,o,u,d)=>{try{var l=t[s](o),c=(o=l.value)instanceof jn,p=l.done;Promise.resolve(c?o[0]:o).then(h=>c?i(s==="return"?s:"next",o[1]?{done:h.done,value:h.value}:h,u,d):u({value:h,done:p})).catch(h=>i("throw",h,u,d))}catch(h){d(h)}},r=s=>a[s]=o=>new Promise((u,d)=>i(s,o,u,d)),a={};return t=t.apply(n,e),a[Symbol.asyncIterator]=()=>a,r("next"),r("throw"),r("return"),a};var Jo={};Wn(Jo,{ChromecastState:()=>Jt,HttpConnectionType:()=>Ji,Observable:()=>Ye.Observable,PlaybackState:()=>be,Player:()=>Qi,SDK_VERSION:()=>Ko,Subject:()=>Ye.Subject,Subscription:()=>Ye.Subscription,Surface:()=>Xi,VERSION:()=>Gr,ValueSubject:()=>Ye.ValueSubject,VideoFormat:()=>je,VideoQuality:()=>Ye.VideoQuality});module.exports=Yn(Jo);var Gr="2.0.106-dev.eacdae04.0";var be=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(be||{}),je=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(je||{});var Jt=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Jt||{}),Ji=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ji||{});var Xi=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Xi||{});var N=require("@vkontakte/videoplayer-shared");var Ya=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Zi=class{constructor(e){this.connection$=new N.ValueSubject(void 0);this.castState$=new N.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new N.Subject;this.realCastState$=new N.ValueSubject("NOT_AVAILABLE");this.subscription=new N.Subscription;var a;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 i=(0,N.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},r||Ya("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:N.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,N.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,N.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),i=cast.framework.CastContext.getInstance();this.subscription.add((0,N.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,s;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(s=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:s.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,N.assertNever)(r.sessionState)}})).add((0,N.merge)((0,N.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,N.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,N.map)(r=>r.castState)),(0,N.observableFrom)([i.getCastState()])).pipe((0,N.filterChanged)(),(0,N.map)(qn),(0,N.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o;let a=r==="CONNECTED",s=(0,N.isNonNullable)(this.connection$.getValue());if(a&&!s){let u=i.getCurrentSession();(0,N.assertNonNullable)(u);let d=u.getCastDevice(),l=(o=u.getMediaSession())==null?void 0:o.media.contentId;((0,N.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,N.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:N.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},qn=n=>{switch(n){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,N.assertNever)(n)}};var Wr=require("@vkontakte/videoplayer-shared");var fe=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Wr.assertNever)(t)}return n},Qr=(n,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(n);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(n);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Wr.assertNever)(e)}};var A=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};var Ge=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new Ge.Subject;this.transitionEnded$=new Ge.Subject;this.transitionUpdated$=new Ge.Subject;this.forceChanged$=new Ge.Subject;this.stateChangeStarted$=(0,Ge.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ge.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let 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){let t=this.transition,i=this.state;i===e||(0,Ge.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}};var ja=require("@vkontakte/videoplayer-shared"),qa=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":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,ja.assertNever)(n)}};var w=require("@vkontakte/videoplayer-shared");var zn=5,Kn=5,Jn=500,za=7e3,Xt=class{constructor(e){this.subscription=new w.Subscription;this.loadMediaTimeoutSubscription=new w.Subscription;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=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(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,w.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,w.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,w.assertNever)(e)}break}default:(0,w.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(qa(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 w.Subscription;this.subscription.add(e),this.subscription.add((0,w.merge)(this.videoState.stateChangeStarted$.pipe((0,w.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,w.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new w.Subject;e.add(r.pipe((0,w.debounce)(Jn)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>zn)&&r.next(o),a=o})),e.add((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t((0,w.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((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Kn&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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,w.assertNever)(s)}}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,w.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,w.observableFrom)(["init"])).pipe((0,w.debounce)(0));t(i,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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let 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:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var d;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];(0,w.assertNonNullable)(l);let c=(0,w.getHighestQuality)(Object.keys(l));(0,w.assertNonNullable)(c);let p=l[c];(0,w.assertNonNullable)(p),i=p,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,w.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,w.assertNonNullable)(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,w.assertNonNullable)(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,w.assertNonNullable)(l),i=fe(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:w.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,w.assertNever)(e)}let s=new chrome.cast.media.MediaInfo((d=this.params.meta.videoId)!=null?d:i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,w.isNonNullable)(o)&&(s.metadata.title=o),(0,w.isNonNullable)(u)&&(s.metadata.subtitle=u),s}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add((0,w.timeout)(za).subscribe(()=>a(`timeout(${za})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:w.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Zt=n=>{n.removeAttribute("src"),n.load()};var Ka=n=>{try{n.pause(),n.playbackRate=0,Zt(n),n.remove()}catch(e){console.error(e)}};var er=require("@vkontakte/videoplayer-shared"),Yr=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)}},jr=window.WeakMap?new WeakMap:new Yr,qr=window.WeakMap?new WeakMap:new Map,Xn=(n,e=20)=>{let t=0;return(0,er.fromEvent)(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ye=(n,{audioVideoSyncRate:e})=>{let t=n.querySelector("video"),i=!!t;t?Zt(t):(t=document.createElement("video"),n.appendChild(t)),jr.set(t,i);let r=new er.Subscription;return r.add(Xn(t,e)),qr.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Te=n=>{let e=qr.get(n);e==null||e.unsubscribe(),qr.delete(n);let t=jr.get(n);jr.delete(n),t?Zt(n):Ka(n)};var $=require("@vkontakte/videoplayer-shared");var ut=require("@vkontakte/videoplayer-shared"),tr=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=(0,ut.isNullable)(r),d=new ut.Subscription;return r&&d.add(r.subscribe(l=>{let c=n.getState();i(l,c)&&n.setState(l)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),u&&n.setState(l.to)},a)),d},We=(n,e,t)=>tr(e,()=>n.loop,i=>{(0,ut.isNonNullable)(i)&&(n.loop=i)},{onError:t}),Ie=(n,e,t,i)=>tr(e,()=>({muted:n.muted,volume:n.volume}),r=>{(0,ut.isNonNullable)(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Re=(n,e,t,i)=>tr(e,()=>n.playbackRate,r=>{(0,ut.isNonNullable)(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),dt=tr;var Zn=n=>["__",n.language,n.label].join("|"),eo=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},zr=class n{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};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(dt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{(0,$.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,s)=>(0,$.isNonNullable)(a)&&(0,$.isNonNullable)(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe((0,$.map)(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(dt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{(0,$.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,s)=>(0,$.isNonNullable)(a)&&(0,$.isNonNullable)(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe((0,$.map)(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(dt(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(dt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,$.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,$.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,$.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(i=>{var a,s;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var d,l,c,p,h;let u=(l=(d=o.target)==null?void 0:d.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(s=i.track)==null||s.addEventListener("cuechange",r)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,$.isNonNullable)(t.align)&&(r.align=t.align),(0,$.isNonNullable)(t.position)&&(r.position=t.position),(0,$.isNonNullable)(t.size)&&(r.size=t.size),(0,$.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:i}=e,r=e.id?e.id:Zn(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:(o=this.externalTracks.get(r))==null?void 0:o.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:(u=this.internalTracks.get(r))==null?void 0:u.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){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!eo(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,$.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,$.assertNonNullable)(this.video);let 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)}},De=zr;var ze=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 Ja=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Kr=n=>{let e=Ja(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Xa=n=>{let e=Ja(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};var P=require("@vkontakte/videoplayer-shared");var to=3,Za=(n,e,t=to)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var Ee=n=>{let e=v=>(0,P.fromEvent)(n,v).pipe((0,P.mapTo)(void 0)),i=(0,P.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>(0,P.fromEvent)(n,v))).pipe((0,P.map)(v=>v.type==="ended"?n.readyState<2:n.readyState<3),(0,P.debounce)(100),(0,P.filterChanged)()),r=(0,P.merge)((0,P.fromEvent)(n,"progress"),(0,P.fromEvent)(n,"timeupdate")).pipe((0,P.map)(()=>Za(n.buffered,n.currentTime))),s=(0,P.getCurrentBrowser)().browser===P.CurrentClientBrowser.Safari?(0,P.combine)({play:e("play").pipe((0,P.once)()),playing:e("playing")}).pipe((0,P.mapTo)(void 0)):e("playing"),o=(0,P.fromEvent)(n,"volumechange").pipe((0,P.map)(()=>({muted:n.muted,volume:n.volume}))),u=(0,P.fromEvent)(n,"ratechange").pipe((0,P.map)(()=>n.playbackRate)),d=(0,P.fromEvent)(n,"error").pipe((0,P.filter)(()=>!!(n.error||n.played.length)),(0,P.map)(()=>{var T;let v=n.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:P.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(T=n.error)!=null?T:void 0}})),l=(0,P.fromEvent)(n,"timeupdate").pipe((0,P.map)(()=>n.currentTime)),c=new P.Subject,p=.3,h;l.subscribe(v=>{n.loop&&(0,P.isNonNullable)(h)&&(0,P.isNonNullable)(v)&&h>=n.duration-p&&v<=p&&c.next(h),h=v});let f=e("pause").pipe((0,P.filter)(()=>!n.error&&h!==n.duration)),b=(0,P.fromEvent)(n,"enterpictureinpicture"),y=(0,P.fromEvent)(n,"leavepictureinpicture"),x=new P.ValueSubject(Xa(n));b.subscribe(()=>x.next(!0)),y.subscribe(()=>x.next(!1));let O=new P.ValueSubject(Kr(n));return(0,P.fromEvent)(n,"fullscreenchange").pipe((0,P.map)(()=>Kr(n))).subscribe(O),{playing$:s,pause$:f,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,P.fromEvent)(n,"durationchange").pipe((0,P.map)(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:x,inFullscreen$:O}};var Ke=require("@vkontakte/videoplayer-shared"),lt=n=>{switch(n){case"mobile":return Ke.VideoQuality.Q_144P;case"lowest":return Ke.VideoQuality.Q_240P;case"low":return Ke.VideoQuality.Q_360P;case"sd":case"medium":return Ke.VideoQuality.Q_480P;case"hd":case"high":return Ke.VideoQuality.Q_720P;case"fullhd":case"full":return Ke.VideoQuality.Q_1080P;case"quadhd":case"quad":return Ke.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Ke.VideoQuality.Q_2160P}};var Q=require("@vkontakte/videoplayer-shared");var Jr=!1,Je={},es=n=>{Jr=n},ts=()=>{Je={}},is=n=>{n(Je)},ei=(n,e)=>{var t;Jr&&(Je.meta=(t=Je.meta)!=null?t:{},Je.meta[n]=e)},ge=class{constructor(e){this.name=e}next(e){var i,r;if(!Jr)return;Je.series=(i=Je.series)!=null?i:{};let t=(r=Je.series[this.name])!=null?r:[];t.push([Date.now(),e]),Je.series[this.name]=t}};var io=new ge("best_bitrate"),ro=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t,ir=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,Q.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ao='Assertion "ABR Tracks is empty array" failed',so=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var X,_,L,Z,oe;(0,Q.assertNotEmptyArray)(n,ao);let p=i.usePixelRatio&&(X=window.devicePixelRatio)!=null?X:1,h=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},f=h&&(0,Q.videoSizeToQuality)(h),b=i.considerPlaybackRate&&(0,Q.isNonNullable)(o)?o:1,y=n.filter(C=>!(0,Q.isInvariantQuality)(C.quality)).sort((C,k)=>(0,Q.isHigher)(C.quality,k.quality)?-1:1),x=(_=y.at(-1))==null?void 0:_.quality,O=(L=y.at(0))==null?void 0:L.quality,E=(0,Q.isNullable)(r)||(0,Q.isNonNullable)(r.min)&&(0,Q.isNonNullable)(r.max)&&(0,Q.isLower)(r.max,r.min)||(0,Q.isNonNullable)(r.min)&&O&&(0,Q.isHigher)(r.min,O)||(0,Q.isNonNullable)(r.max)&&x&&(0,Q.isLower)(r.max,x),v=b*ro(s!=null?s:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),T={},Y=y.filter(C=>(f?(0,Q.isLower)(C.quality,f):!0)?((0,Q.isNonNullable)(t)&&isFinite(t)&&(0,Q.isNonNullable)(C.bitrate)?t-a>=C.bitrate*v:!0)?i.lazyQualitySwitch&&(0,Q.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,Q.isInvariantQuality)(u.quality)&&(s!=null?s:0)<i.minBufferToSwitchUp&&(0,Q.isHigher)(C.quality,u.quality)?(T[C.quality]="Buffer",!1):!!l&&(0,Q.isHigherOrEqual)(C.quality,l)?(T[C.quality]="DroppedFramesLimit",!1):E||((0,Q.isNullable)(r.max)||(0,Q.isLowerOrEqual)(C.quality,r.max))&&((0,Q.isNullable)(r.min)||(0,Q.isHigherOrEqual)(C.quality,r.min))?!0:(T[C.quality]="FitsQualityLimits",!1):(T[C.quality]="FitsThroughput",!1):(T[C.quality]="FitsContainer",!1))[0];Y&&Y.bitrate&&io.next(Y.bitrate);let U=(Z=Y!=null?Y:y[Math.ceil((y.length-1)/2)])!=null?Z:n[0];U.quality!==((oe=d==null?void 0:d.last)==null?void 0:oe.quality)&&c({message:`
|
|
6
|
+
"use strict";var Xb=Object.create;var Yr=Object.defineProperty,Zb=Object.defineProperties,eg=Object.getOwnPropertyDescriptor,tg=Object.getOwnPropertyDescriptors,rg=Object.getOwnPropertyNames,Gu=Object.getOwnPropertySymbols,ig=Object.getPrototypeOf,Wu=Object.prototype.hasOwnProperty,ag=Object.prototype.propertyIsEnumerable;var it=Math.pow,Yu=(i,e,t)=>e in i?Yr(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,V=(i,e)=>{for(var t in e||(e={}))Wu.call(e,t)&&Yu(i,t,e[t]);if(Gu)for(var t of Gu(e))ag.call(e,t)&&Yu(i,t,e[t]);return i},X=(i,e)=>Zb(i,tg(e));var b=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),sg=(i,e)=>{for(var t in e)Yr(i,t,{get:e[t],enumerable:!0})},Qu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of rg(e))!Wu.call(i,a)&&a!==t&&Yr(i,a,{get:()=>e[a],enumerable:!(r=eg(e,a))||r.enumerable});return i};var Qe=(i,e,t)=>(t=i!=null?Xb(ig(i)):{},Qu(e||!i||!i.__esModule?Yr(t,"default",{value:i,enumerable:!0}):t,i)),ng=i=>Qu(Yr({},"__esModule",{value:!0}),i);var D=(i,e,t)=>new Promise((r,a)=>{var s=u=>{try{o(t.next(u))}catch(l){a(l)}},n=u=>{try{o(t.throw(u))}catch(l){a(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(i,e)).next())}),og=function(i,e){this[0]=i,this[1]=e},fe=(i,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof og,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},a=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(i,e),s[Symbol.asyncIterator]=()=>s,a("next"),a("throw"),a("return"),s};var Oe=b((PA,Ku)=>{"use strict";Ku.exports=function(i){try{return!!i()}catch(e){return!0}}});var Qr=b((AA,Ju)=>{"use strict";var lg=Oe();Ju.exports=!lg(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var xe=b((wA,el)=>{"use strict";var Xu=Qr(),Zu=Function.prototype,Ks=Zu.call,cg=Xu&&Zu.bind.bind(Ks,Ks);el.exports=Xu?cg:function(i){return function(){return Ks.apply(i,arguments)}}});var hr=b((kA,rl)=>{"use strict";var tl=xe(),dg=tl({}.toString),pg=tl("".slice);rl.exports=function(i){return pg(dg(i),8,-1)}});var al=b((RA,il)=>{"use strict";var hg=xe(),fg=Oe(),mg=hr(),Js=Object,bg=hg("".split);il.exports=fg(function(){return!Js("z").propertyIsEnumerable(0)})?function(i){return mg(i)=="String"?bg(i,""):Js(i)}:Js});var fr=b((LA,sl)=>{"use strict";sl.exports=function(i){return i==null}});var Sa=b(($A,nl)=>{"use strict";var gg=fr(),Sg=TypeError;nl.exports=function(i){if(gg(i))throw Sg("Can't call method on "+i);return i}});var mr=b((CA,ol)=>{"use strict";var vg=al(),yg=Sa();ol.exports=function(i){return vg(yg(i))}});var Xs=b((MA,ul)=>{"use strict";ul.exports=function(){}});var Ht=b((DA,ll)=>{"use strict";ll.exports={}});var me=b((cl,dl)=>{"use strict";var va=function(i){return i&&i.Math==Math&&i};dl.exports=va(typeof globalThis=="object"&&globalThis)||va(typeof window=="object"&&window)||va(typeof self=="object"&&self)||va(typeof global=="object"&&global)||function(){return this}()||cl||Function("return this")()});var en=b((OA,pl)=>{"use strict";var Zs=typeof document=="object"&&document.all,Tg=typeof Zs=="undefined"&&Zs!==void 0;pl.exports={all:Zs,IS_HTMLDDA:Tg}});var oe=b((BA,fl)=>{"use strict";var hl=en(),Ig=hl.all;fl.exports=hl.IS_HTMLDDA?function(i){return typeof i=="function"||i===Ig}:function(i){return typeof i=="function"}});var gl=b((VA,bl)=>{"use strict";var Eg=me(),xg=oe(),ml=Eg.WeakMap;bl.exports=xg(ml)&&/native code/.test(String(ml))});var at=b((_A,yl)=>{"use strict";var Sl=oe(),vl=en(),Pg=vl.all;yl.exports=vl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Sl(i)||i===Pg}:function(i){return typeof i=="object"?i!==null:Sl(i)}});var st=b((NA,Tl)=>{"use strict";var Ag=Oe();Tl.exports=!Ag(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var ya=b((FA,El)=>{"use strict";var wg=me(),Il=at(),tn=wg.document,kg=Il(tn)&&Il(tn.createElement);El.exports=function(i){return kg?tn.createElement(i):{}}});var rn=b((qA,xl)=>{"use strict";var Rg=st(),Lg=Oe(),$g=ya();xl.exports=!Rg&&!Lg(function(){return Object.defineProperty($g("div"),"a",{get:function(){return 7}}).a!=7})});var an=b((UA,Pl)=>{"use strict";var Cg=st(),Mg=Oe();Pl.exports=Cg&&Mg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var ze=b((HA,Al)=>{"use strict";var Dg=at(),Og=String,Bg=TypeError;Al.exports=function(i){if(Dg(i))return i;throw Bg(Og(i)+" is not an object")}});var Pe=b((jA,wl)=>{"use strict";var Vg=Qr(),Ta=Function.prototype.call;wl.exports=Vg?Ta.bind(Ta):function(){return Ta.apply(Ta,arguments)}});var Ia=b((GA,kl)=>{"use strict";kl.exports={}});var dt=b((YA,Ll)=>{"use strict";var sn=Ia(),nn=me(),_g=oe(),Rl=function(i){return _g(i)?i:void 0};Ll.exports=function(i,e){return arguments.length<2?Rl(sn[i])||Rl(nn[i]):sn[i]&&sn[i][e]||nn[i]&&nn[i][e]}});var zr=b((WA,$l)=>{"use strict";var Ng=xe();$l.exports=Ng({}.isPrototypeOf)});var Kr=b((QA,Cl)=>{"use strict";Cl.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var un=b((zA,_l)=>{"use strict";var Vl=me(),on=Kr(),Ml=Vl.process,Dl=Vl.Deno,Ol=Ml&&Ml.versions||Dl&&Dl.version,Bl=Ol&&Ol.v8,Ke,Ea;Bl&&(Ke=Bl.split("."),Ea=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!Ea&&on&&(Ke=on.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=on.match(/Chrome\/(\d+)/),Ke&&(Ea=+Ke[1])));_l.exports=Ea});var ln=b((KA,Fl)=>{"use strict";var Nl=un(),Fg=Oe(),qg=me(),Ug=qg.String;Fl.exports=!!Object.getOwnPropertySymbols&&!Fg(function(){var i=Symbol();return!Ug(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Nl&&Nl<41})});var cn=b((JA,ql)=>{"use strict";var Hg=ln();ql.exports=Hg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var dn=b((XA,Ul)=>{"use strict";var jg=dt(),Gg=oe(),Yg=zr(),Wg=cn(),Qg=Object;Ul.exports=Wg?function(i){return typeof i=="symbol"}:function(i){var e=jg("Symbol");return Gg(e)&&Yg(e.prototype,Qg(i))}});var Jr=b((ZA,Hl)=>{"use strict";var zg=String;Hl.exports=function(i){try{return zg(i)}catch(e){return"Object"}}});var pt=b((ew,jl)=>{"use strict";var Kg=oe(),Jg=Jr(),Xg=TypeError;jl.exports=function(i){if(Kg(i))return i;throw Xg(Jg(i)+" is not a function")}});var Xr=b((tw,Gl)=>{"use strict";var Zg=pt(),eS=fr();Gl.exports=function(i,e){var t=i[e];return eS(t)?void 0:Zg(t)}});var Wl=b((rw,Yl)=>{"use strict";var pn=Pe(),hn=oe(),fn=at(),tS=TypeError;Yl.exports=function(i,e){var t,r;if(e==="string"&&hn(t=i.toString)&&!fn(r=pn(t,i))||hn(t=i.valueOf)&&!fn(r=pn(t,i))||e!=="string"&&hn(t=i.toString)&&!fn(r=pn(t,i)))return r;throw tS("Can't convert object to primitive value")}});var Je=b((iw,Ql)=>{"use strict";Ql.exports=!0});var Jl=b((aw,Kl)=>{"use strict";var zl=me(),rS=Object.defineProperty;Kl.exports=function(i,e){try{rS(zl,i,{value:e,configurable:!0,writable:!0})}catch(t){zl[i]=e}return e}});var xa=b((sw,Zl)=>{"use strict";var iS=me(),aS=Jl(),Xl="__core-js_shared__",sS=iS[Xl]||aS(Xl,{});Zl.exports=sS});var mn=b((nw,tc)=>{"use strict";var nS=Je(),ec=xa();(tc.exports=function(i,e){return ec[i]||(ec[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:nS?"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 Zr=b((ow,rc)=>{"use strict";var oS=Sa(),uS=Object;rc.exports=function(i){return uS(oS(i))}});var Xe=b((uw,ic)=>{"use strict";var lS=xe(),cS=Zr(),dS=lS({}.hasOwnProperty);ic.exports=Object.hasOwn||function(e,t){return dS(cS(e),t)}});var bn=b((lw,ac)=>{"use strict";var pS=xe(),hS=0,fS=Math.random(),mS=pS(1 .toString);ac.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+mS(++hS+fS,36)}});var Se=b((cw,nc)=>{"use strict";var bS=me(),gS=mn(),sc=Xe(),SS=bn(),vS=ln(),yS=cn(),br=bS.Symbol,gn=gS("wks"),TS=yS?br.for||br:br&&br.withoutSetter||SS;nc.exports=function(i){return sc(gn,i)||(gn[i]=vS&&sc(br,i)?br[i]:TS("Symbol."+i)),gn[i]}});var cc=b((dw,lc)=>{"use strict";var IS=Pe(),oc=at(),uc=dn(),ES=Xr(),xS=Wl(),PS=Se(),AS=TypeError,wS=PS("toPrimitive");lc.exports=function(i,e){if(!oc(i)||uc(i))return i;var t=ES(i,wS),r;if(t){if(e===void 0&&(e="default"),r=IS(t,i,e),!oc(r)||uc(r))return r;throw AS("Can't convert object to primitive value")}return e===void 0&&(e="number"),xS(i,e)}});var Pa=b((pw,dc)=>{"use strict";var kS=cc(),RS=dn();dc.exports=function(i){var e=kS(i,"string");return RS(e)?e:e+""}});var jt=b(hc=>{"use strict";var LS=st(),$S=rn(),CS=an(),Aa=ze(),pc=Pa(),MS=TypeError,Sn=Object.defineProperty,DS=Object.getOwnPropertyDescriptor,vn="enumerable",yn="configurable",Tn="writable";hc.f=LS?CS?function(e,t,r){if(Aa(e),t=pc(t),Aa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Tn in r&&!r[Tn]){var a=DS(e,t);a&&a[Tn]&&(e[t]=r.value,r={configurable:yn in r?r[yn]:a[yn],enumerable:vn in r?r[vn]:a[vn],writable:!1})}return Sn(e,t,r)}:Sn:function(e,t,r){if(Aa(e),t=pc(t),Aa(r),$S)try{return Sn(e,t,r)}catch(a){}if("get"in r||"set"in r)throw MS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ei=b((fw,fc)=>{"use strict";fc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Gt=b((mw,mc)=>{"use strict";var OS=st(),BS=jt(),VS=ei();mc.exports=OS?function(i,e,t){return BS.f(i,e,VS(1,t))}:function(i,e,t){return i[e]=t,i}});var wa=b((bw,gc)=>{"use strict";var _S=mn(),NS=bn(),bc=_S("keys");gc.exports=function(i){return bc[i]||(bc[i]=NS(i))}});var ka=b((gw,Sc)=>{"use strict";Sc.exports={}});var Pn=b((Sw,Tc)=>{"use strict";var FS=gl(),yc=me(),qS=at(),US=Gt(),In=Xe(),En=xa(),HS=wa(),jS=ka(),vc="Object already initialized",xn=yc.TypeError,GS=yc.WeakMap,Ra,ti,La,YS=function(i){return La(i)?ti(i):Ra(i,{})},WS=function(i){return function(e){var t;if(!qS(e)||(t=ti(e)).type!==i)throw xn("Incompatible receiver, "+i+" required");return t}};FS||En.state?(Ze=En.state||(En.state=new GS),Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,Ra=function(i,e){if(Ze.has(i))throw xn(vc);return e.facade=i,Ze.set(i,e),e},ti=function(i){return Ze.get(i)||{}},La=function(i){return Ze.has(i)}):(Yt=HS("state"),jS[Yt]=!0,Ra=function(i,e){if(In(i,Yt))throw xn(vc);return e.facade=i,US(i,Yt,e),e},ti=function(i){return In(i,Yt)?i[Yt]:{}},La=function(i){return In(i,Yt)});var Ze,Yt;Tc.exports={set:Ra,get:ti,has:La,enforce:YS,getterFor:WS}});var An=b((vw,Pc)=>{"use strict";var QS=Qr(),xc=Function.prototype,Ic=xc.apply,Ec=xc.call;Pc.exports=typeof Reflect=="object"&&Reflect.apply||(QS?Ec.bind(Ic):function(){return Ec.apply(Ic,arguments)})});var wn=b((yw,Ac)=>{"use strict";var zS=hr(),KS=xe();Ac.exports=function(i){if(zS(i)==="Function")return KS(i)}});var Lc=b(Rc=>{"use strict";var wc={}.propertyIsEnumerable,kc=Object.getOwnPropertyDescriptor,JS=kc&&!wc.call({1:2},1);Rc.f=JS?function(e){var t=kc(this,e);return!!t&&t.enumerable}:wc});var kn=b(Cc=>{"use strict";var XS=st(),ZS=Pe(),ev=Lc(),tv=ei(),rv=mr(),iv=Pa(),av=Xe(),sv=rn(),$c=Object.getOwnPropertyDescriptor;Cc.f=XS?$c:function(e,t){if(e=rv(e),t=iv(t),sv)try{return $c(e,t)}catch(r){}if(av(e,t))return tv(!ZS(ev.f,e,t),e[t])}});var Rn=b((Ew,Mc)=>{"use strict";var nv=Oe(),ov=oe(),uv=/#|\.prototype\./,ri=function(i,e){var t=cv[lv(i)];return t==pv?!0:t==dv?!1:ov(e)?nv(e):!!e},lv=ri.normalize=function(i){return String(i).replace(uv,".").toLowerCase()},cv=ri.data={},dv=ri.NATIVE="N",pv=ri.POLYFILL="P";Mc.exports=ri});var ii=b((xw,Oc)=>{"use strict";var Dc=wn(),hv=pt(),fv=Qr(),mv=Dc(Dc.bind);Oc.exports=function(i,e){return hv(i),e===void 0?i:fv?mv(i,e):function(){return i.apply(e,arguments)}}});var Fe=b((Pw,Vc)=>{"use strict";var $a=me(),bv=An(),gv=wn(),Sv=oe(),vv=kn().f,yv=Rn(),gr=Ia(),Tv=ii(),Sr=Gt(),Bc=Xe(),Iv=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 bv(i,this,arguments)};return e.prototype=i.prototype,e};Vc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?$a:a?$a[t]:($a[t]||{}).prototype,o=r?gr:gr[t]||Sr(gr,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,S,T;for(p in e)l=yv(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&Bc(n,p),m=o[p],c&&(i.dontCallGetSet?(T=vv(n,p),g=T&&T.value):g=n[p]),h=c&&g?g:e[p],!(c&&typeof m==typeof h)&&(i.bind&&c?S=Tv(h,$a):i.wrap&&c?S=Iv(h):s&&Sv(h)?S=gv(h):S=h,(i.sham||h&&h.sham||m&&m.sham)&&Sr(S,"sham",!0),Sr(o,p,S),s&&(d=t+"Prototype",Bc(gr,d)||Sr(gr,d,{}),Sr(gr[d],p,h),i.real&&u&&(l||!u[p])&&Sr(u,p,h)))}});var Fc=b((Aw,Nc)=>{"use strict";var Ln=st(),Ev=Xe(),_c=Function.prototype,xv=Ln&&Object.getOwnPropertyDescriptor,$n=Ev(_c,"name"),Pv=$n&&function(){}.name==="something",Av=$n&&(!Ln||Ln&&xv(_c,"name").configurable);Nc.exports={EXISTS:$n,PROPER:Pv,CONFIGURABLE:Av}});var Uc=b((ww,qc)=>{"use strict";var wv=Math.ceil,kv=Math.floor;qc.exports=Math.trunc||function(e){var t=+e;return(t>0?kv:wv)(t)}});var Ca=b((kw,Hc)=>{"use strict";var Rv=Uc();Hc.exports=function(i){var e=+i;return e!==e||e===0?0:Rv(e)}});var Gc=b((Rw,jc)=>{"use strict";var Lv=Ca(),$v=Math.max,Cv=Math.min;jc.exports=function(i,e){var t=Lv(i);return t<0?$v(t+e,0):Cv(t,e)}});var Wc=b((Lw,Yc)=>{"use strict";var Mv=Ca(),Dv=Math.min;Yc.exports=function(i){return i>0?Dv(Mv(i),9007199254740991):0}});var Ma=b(($w,Qc)=>{"use strict";var Ov=Wc();Qc.exports=function(i){return Ov(i.length)}});var Jc=b((Cw,Kc)=>{"use strict";var Bv=mr(),Vv=Gc(),_v=Ma(),zc=function(i){return function(e,t,r){var a=Bv(e),s=_v(a),n=Vv(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}};Kc.exports={includes:zc(!0),indexOf:zc(!1)}});var ed=b((Mw,Zc)=>{"use strict";var Nv=xe(),Cn=Xe(),Fv=mr(),qv=Jc().indexOf,Uv=ka(),Xc=Nv([].push);Zc.exports=function(i,e){var t=Fv(i),r=0,a=[],s;for(s in t)!Cn(Uv,s)&&Cn(t,s)&&Xc(a,s);for(;e.length>r;)Cn(t,s=e[r++])&&(~qv(a,s)||Xc(a,s));return a}});var Mn=b((Dw,td)=>{"use strict";td.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var id=b((Ow,rd)=>{"use strict";var Hv=ed(),jv=Mn();rd.exports=Object.keys||function(e){return Hv(e,jv)}});var sd=b(ad=>{"use strict";var Gv=st(),Yv=an(),Wv=jt(),Qv=ze(),zv=mr(),Kv=id();ad.f=Gv&&!Yv?Object.defineProperties:function(e,t){Qv(e);for(var r=zv(t),a=Kv(t),s=a.length,n=0,o;s>n;)Wv.f(e,o=a[n++],r[o]);return e}});var Dn=b((Vw,nd)=>{"use strict";var Jv=dt();nd.exports=Jv("document","documentElement")});var _n=b((_w,hd)=>{"use strict";var Xv=ze(),Zv=sd(),od=Mn(),ey=ka(),ty=Dn(),ry=ya(),iy=wa(),ud=">",ld="<",Bn="prototype",Vn="script",dd=iy("IE_PROTO"),On=function(){},pd=function(i){return ld+Vn+ud+i+ld+"/"+Vn+ud},cd=function(i){i.write(pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},ay=function(){var i=ry("iframe"),e="java"+Vn+":",t;return i.style.display="none",ty.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pd("document.F=Object")),t.close(),t.F},Da,Oa=function(){try{Da=new ActiveXObject("htmlfile")}catch(e){}Oa=typeof document!="undefined"?document.domain&&Da?cd(Da):ay():cd(Da);for(var i=od.length;i--;)delete Oa[Bn][od[i]];return Oa()};ey[dd]=!0;hd.exports=Object.create||function(e,t){var r;return e!==null?(On[Bn]=Xv(e),r=new On,On[Bn]=null,r[dd]=e):r=Oa(),t===void 0?r:Zv.f(r,t)}});var md=b((Nw,fd)=>{"use strict";var sy=Oe();fd.exports=!sy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Fn=b((Fw,gd)=>{"use strict";var ny=Xe(),oy=oe(),uy=Zr(),ly=wa(),cy=md(),bd=ly("IE_PROTO"),Nn=Object,dy=Nn.prototype;gd.exports=cy?Nn.getPrototypeOf:function(i){var e=uy(i);if(ny(e,bd))return e[bd];var t=e.constructor;return oy(t)&&e instanceof t?t.prototype:e instanceof Nn?dy:null}});var vr=b((qw,Sd)=>{"use strict";var py=Gt();Sd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:py(i,e,t),i}});var jn=b((Uw,Td)=>{"use strict";var hy=Oe(),fy=oe(),my=at(),by=_n(),vd=Fn(),gy=vr(),Sy=Se(),vy=Je(),Hn=Sy("iterator"),yd=!1,ht,qn,Un;[].keys&&(Un=[].keys(),"next"in Un?(qn=vd(vd(Un)),qn!==Object.prototype&&(ht=qn)):yd=!0);var yy=!my(ht)||hy(function(){var i={};return ht[Hn].call(i)!==i});yy?ht={}:vy&&(ht=by(ht));fy(ht[Hn])||gy(ht,Hn,function(){return this});Td.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:yd}});var Ba=b((Hw,Ed)=>{"use strict";var Ty=Se(),Iy=Ty("toStringTag"),Id={};Id[Iy]="z";Ed.exports=String(Id)==="[object z]"});var yr=b((jw,xd)=>{"use strict";var Ey=Ba(),xy=oe(),Va=hr(),Py=Se(),Ay=Py("toStringTag"),wy=Object,ky=Va(function(){return arguments}())=="Arguments",Ry=function(i,e){try{return i[e]}catch(t){}};xd.exports=Ey?Va:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Ry(e=wy(i),Ay))=="string"?t:ky?Va(e):(r=Va(e))=="Object"&&xy(e.callee)?"Arguments":r}});var Ad=b((Gw,Pd)=>{"use strict";var Ly=Ba(),$y=yr();Pd.exports=Ly?{}.toString:function(){return"[object "+$y(this)+"]"}});var _a=b((Yw,kd)=>{"use strict";var Cy=Ba(),My=jt().f,Dy=Gt(),Oy=Xe(),By=Ad(),Vy=Se(),wd=Vy("toStringTag");kd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;Oy(a,wd)||My(a,wd,{configurable:!0,value:e}),r&&!Cy&&Dy(a,"toString",By)}}});var Ld=b((Ww,Rd)=>{"use strict";var _y=jn().IteratorPrototype,Ny=_n(),Fy=ei(),qy=_a(),Uy=Ht(),Hy=function(){return this};Rd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Ny(_y,{next:Fy(+!r,t)}),qy(i,a,!1,!0),Uy[a]=Hy,i}});var Cd=b((Qw,$d)=>{"use strict";var jy=xe(),Gy=pt();$d.exports=function(i,e,t){try{return jy(Gy(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var Dd=b((zw,Md)=>{"use strict";var Yy=oe(),Wy=String,Qy=TypeError;Md.exports=function(i){if(typeof i=="object"||Yy(i))return i;throw Qy("Can't set "+Wy(i)+" as a prototype")}});var Gn=b((Kw,Od)=>{"use strict";var zy=Cd(),Ky=ze(),Jy=Dd();Od.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=zy(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return Ky(a),Jy(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var Yd=b((Jw,Gd)=>{"use strict";var Xy=Fe(),Zy=Pe(),Na=Je(),Hd=Fc(),eT=oe(),tT=Ld(),Bd=Fn(),Vd=Gn(),rT=_a(),iT=Gt(),Yn=vr(),aT=Se(),_d=Ht(),jd=jn(),sT=Hd.PROPER,nT=Hd.CONFIGURABLE,Nd=jd.IteratorPrototype,Fa=jd.BUGGY_SAFARI_ITERATORS,ai=aT("iterator"),Fd="keys",si="values",qd="entries",Ud=function(){return this};Gd.exports=function(i,e,t,r,a,s,n){tT(t,e,r);var o=function(T){if(T===a&&p)return p;if(!Fa&&T in c)return c[T];switch(T){case Fd:return function(){return new t(this,T)};case si:return function(){return new t(this,T)};case qd:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[ai]||c["@@iterator"]||a&&c[a],p=!Fa&&d||o(a),h=e=="Array"&&c.entries||d,m,g,S;if(h&&(m=Bd(h.call(new i)),m!==Object.prototype&&m.next&&(!Na&&Bd(m)!==Nd&&(Vd?Vd(m,Nd):eT(m[ai])||Yn(m,ai,Ud)),rT(m,u,!0,!0),Na&&(_d[u]=Ud))),sT&&a==si&&d&&d.name!==si&&(!Na&&nT?iT(c,"name",si):(l=!0,p=function(){return Zy(d,this)})),a)if(g={values:o(si),keys:s?p:o(Fd),entries:o(qd)},n)for(S in g)(Fa||l||!(S in c))&&Yn(c,S,g[S]);else Xy({target:e,proto:!0,forced:Fa||l},g);return(!Na||n)&&c[ai]!==p&&Yn(c,ai,p,{name:a}),_d[e]=p,g}});var Qd=b((Xw,Wd)=>{"use strict";Wd.exports=function(i,e){return{value:i,done:e}}});var Qn=b((Zw,Zd)=>{"use strict";var oT=mr(),Wn=Xs(),zd=Ht(),Jd=Pn(),uT=jt().f,lT=Yd(),qa=Qd(),cT=Je(),dT=st(),Xd="Array Iterator",pT=Jd.set,hT=Jd.getterFor(Xd);Zd.exports=lT(Array,"Array",function(i,e){pT(this,{type:Xd,target:oT(i),index:0,kind:e})},function(){var i=hT(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,qa(void 0,!0)):t=="keys"?qa(r,!1):t=="values"?qa(e[r],!1):qa([r,e[r]],!1)},"values");var Kd=zd.Arguments=zd.Array;Wn("keys");Wn("values");Wn("entries");if(!cT&&dT&&Kd.name!=="values")try{uT(Kd,"name",{value:"values"})}catch(i){}});var tp=b((ek,ep)=>{"use strict";var fT=Se(),mT=Ht(),bT=fT("iterator"),gT=Array.prototype;ep.exports=function(i){return i!==void 0&&(mT.Array===i||gT[bT]===i)}});var zn=b((tk,ip)=>{"use strict";var ST=yr(),rp=Xr(),vT=fr(),yT=Ht(),TT=Se(),IT=TT("iterator");ip.exports=function(i){if(!vT(i))return rp(i,IT)||rp(i,"@@iterator")||yT[ST(i)]}});var sp=b((rk,ap)=>{"use strict";var ET=Pe(),xT=pt(),PT=ze(),AT=Jr(),wT=zn(),kT=TypeError;ap.exports=function(i,e){var t=arguments.length<2?wT(i):e;if(xT(t))return PT(ET(t,i));throw kT(AT(i)+" is not iterable")}});var up=b((ik,op)=>{"use strict";var RT=Pe(),np=ze(),LT=Xr();op.exports=function(i,e,t){var r,a;np(i);try{if(r=LT(i,"return"),!r){if(e==="throw")throw t;return t}r=RT(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return np(r),t}});var Ha=b((ak,pp)=>{"use strict";var $T=ii(),CT=Pe(),MT=ze(),DT=Jr(),OT=tp(),BT=Ma(),lp=zr(),VT=sp(),_T=zn(),cp=up(),NT=TypeError,Ua=function(i,e){this.stopped=i,this.result=e},dp=Ua.prototype;pp.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),u=$T(e,r),l,c,d,p,h,m,g,S=function(A){return l&&cp(l,"normal",A),new Ua(!0,A)},T=function(A){return a?(MT(A),o?u(A[0],A[1],S):u(A[0],A[1])):o?u(A,S):u(A)};if(s)l=i.iterator;else if(n)l=i;else{if(c=_T(i),!c)throw NT(DT(i)+" is not iterable");if(OT(c)){for(d=0,p=BT(i);p>d;d++)if(h=T(i[d]),h&&lp(dp,h))return h;return new Ua(!1)}l=VT(i,c)}for(m=s?i.next:l.next;!(g=CT(m,l)).done;){try{h=T(g.value)}catch(A){cp(l,"throw",A)}if(typeof h=="object"&&h&&lp(dp,h))return h}return new Ua(!1)}});var fp=b((sk,hp)=>{"use strict";var FT=Pa(),qT=jt(),UT=ei();hp.exports=function(i,e,t){var r=FT(e);r in i?qT.f(i,r,UT(0,t)):i[r]=t}});var mp=b(()=>{"use strict";var HT=Fe(),jT=Ha(),GT=fp();HT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return jT(e,function(r,a){GT(t,r,a)},{AS_ENTRIES:!0}),t}})});var gp=b((uk,bp)=>{"use strict";Qn();mp();var YT=Ia();bp.exports=YT.Object.fromEntries});var vp=b((lk,Sp)=>{"use strict";Sp.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 Ip=b(()=>{"use strict";Qn();var WT=vp(),QT=me(),zT=yr(),KT=Gt(),yp=Ht(),JT=Se(),Tp=JT("toStringTag");for(ja in WT)Kn=QT[ja],Ga=Kn&&Kn.prototype,Ga&&zT(Ga)!==Tp&&KT(Ga,Tp,ja),yp[ja]=yp.Array;var Kn,Ga,ja});var xp=b((pk,Ep)=>{"use strict";var XT=gp();Ip();Ep.exports=XT});var Jn=b((hk,Pp)=>{"use strict";var ZT=xp();Pp.exports=ZT});var Ap=b(()=>{"use strict"});var ni=b((bk,wp)=>{"use strict";var eI=hr();wp.exports=typeof process!="undefined"&&eI(process)=="process"});var Rp=b((gk,kp)=>{"use strict";var tI=jt();kp.exports=function(i,e,t){return tI.f(i,e,t)}});var Cp=b((Sk,$p)=>{"use strict";var rI=dt(),iI=Rp(),aI=Se(),sI=st(),Lp=aI("species");$p.exports=function(i){var e=rI(i);sI&&e&&!e[Lp]&&iI(e,Lp,{configurable:!0,get:function(){return this}})}});var Dp=b((vk,Mp)=>{"use strict";var nI=zr(),oI=TypeError;Mp.exports=function(i,e){if(nI(e,i))return i;throw oI("Incorrect invocation")}});var Zn=b((yk,Op)=>{"use strict";var uI=xe(),lI=oe(),Xn=xa(),cI=uI(Function.toString);lI(Xn.inspectSource)||(Xn.inspectSource=function(i){return cI(i)});Op.exports=Xn.inspectSource});var qp=b((Tk,Fp)=>{"use strict";var dI=xe(),pI=Oe(),Bp=oe(),hI=yr(),fI=dt(),mI=Zn(),Vp=function(){},bI=[],_p=fI("Reflect","construct"),eo=/^\s*(?:class|function)\b/,gI=dI(eo.exec),SI=!eo.exec(Vp),oi=function(e){if(!Bp(e))return!1;try{return _p(Vp,bI,e),!0}catch(t){return!1}},Np=function(e){if(!Bp(e))return!1;switch(hI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return SI||!!gI(eo,mI(e))}catch(t){return!0}};Np.sham=!0;Fp.exports=!_p||pI(function(){var i;return oi(oi.call)||!oi(Object)||!oi(function(){i=!0})||i})?Np:oi});var Hp=b((Ik,Up)=>{"use strict";var vI=qp(),yI=Jr(),TI=TypeError;Up.exports=function(i){if(vI(i))return i;throw TI(yI(i)+" is not a constructor")}});var to=b((Ek,Gp)=>{"use strict";var jp=ze(),II=Hp(),EI=fr(),xI=Se(),PI=xI("species");Gp.exports=function(i,e){var t=jp(i).constructor,r;return t===void 0||EI(r=jp(t)[PI])?e:II(r)}});var Wp=b((xk,Yp)=>{"use strict";var AI=xe();Yp.exports=AI([].slice)});var zp=b((Pk,Qp)=>{"use strict";var wI=TypeError;Qp.exports=function(i,e){if(i<e)throw wI("Not enough arguments");return i}});var ro=b((Ak,Kp)=>{"use strict";var kI=Kr();Kp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(kI)});var po=b((wk,sh)=>{"use strict";var Be=me(),RI=An(),LI=ii(),Jp=oe(),$I=Xe(),ah=Oe(),Xp=Dn(),CI=Wp(),Zp=ya(),MI=zp(),DI=ro(),OI=ni(),uo=Be.setImmediate,lo=Be.clearImmediate,BI=Be.process,io=Be.Dispatch,VI=Be.Function,eh=Be.MessageChannel,_I=Be.String,ao=0,ui={},th="onreadystatechange",li,Wt,so,no;ah(function(){li=Be.location});var co=function(i){if($I(ui,i)){var e=ui[i];delete ui[i],e()}},oo=function(i){return function(){co(i)}},rh=function(i){co(i.data)},ih=function(i){Be.postMessage(_I(i),li.protocol+"//"+li.host)};(!uo||!lo)&&(uo=function(e){MI(arguments.length,1);var t=Jp(e)?e:VI(e),r=CI(arguments,1);return ui[++ao]=function(){RI(t,void 0,r)},Wt(ao),ao},lo=function(e){delete ui[e]},OI?Wt=function(i){BI.nextTick(oo(i))}:io&&io.now?Wt=function(i){io.now(oo(i))}:eh&&!DI?(so=new eh,no=so.port2,so.port1.onmessage=rh,Wt=LI(no.postMessage,no)):Be.addEventListener&&Jp(Be.postMessage)&&!Be.importScripts&&li&&li.protocol!=="file:"&&!ah(ih)?(Wt=ih,Be.addEventListener("message",rh,!1)):th in Zp("script")?Wt=function(i){Xp.appendChild(Zp("script"))[th]=function(){Xp.removeChild(this),co(i)}}:Wt=function(i){setTimeout(oo(i),0)});sh.exports={set:uo,clear:lo}});var ho=b((kk,oh)=>{"use strict";var nh=function(){this.head=null,this.tail=null};nh.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}}};oh.exports=nh});var lh=b((Rk,uh)=>{"use strict";var NI=Kr();uh.exports=/ipad|iphone|ipod/i.test(NI)&&typeof Pebble!="undefined"});var dh=b((Lk,ch)=>{"use strict";var FI=Kr();ch.exports=/web0s(?!.*chrome)/i.test(FI)});var vh=b(($k,Sh)=>{"use strict";var Qt=me(),ph=ii(),qI=kn().f,fo=po().set,UI=ho(),HI=ro(),jI=lh(),GI=dh(),mo=ni(),hh=Qt.MutationObserver||Qt.WebKitMutationObserver,fh=Qt.document,mh=Qt.process,Ya=Qt.Promise,bh=qI(Qt,"queueMicrotask"),So=bh&&bh.value,Tr,bo,go,Wa,gh;So||(ci=new UI,di=function(){var i,e;for(mo&&(i=mh.domain)&&i.exit();e=ci.get();)try{e()}catch(t){throw ci.head&&Tr(),t}i&&i.enter()},!HI&&!mo&&!GI&&hh&&fh?(bo=!0,go=fh.createTextNode(""),new hh(di).observe(go,{characterData:!0}),Tr=function(){go.data=bo=!bo}):!jI&&Ya&&Ya.resolve?(Wa=Ya.resolve(void 0),Wa.constructor=Ya,gh=ph(Wa.then,Wa),Tr=function(){gh(di)}):mo?Tr=function(){mh.nextTick(di)}:(fo=ph(fo,Qt),Tr=function(){fo(di)}),So=function(i){ci.head||Tr(),ci.add(i)});var ci,di;Sh.exports=So});var Th=b((Ck,yh)=>{"use strict";yh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var Qa=b((Mk,Ih)=>{"use strict";Ih.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var zt=b((Dk,Eh)=>{"use strict";var YI=me();Eh.exports=YI.Promise});var vo=b((Ok,xh)=>{"use strict";xh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Ah=b((Bk,Ph)=>{"use strict";var WI=vo(),QI=ni();Ph.exports=!WI&&!QI&&typeof window=="object"&&typeof document=="object"});var Ir=b((Vk,Rh)=>{"use strict";var zI=me(),pi=zt(),KI=oe(),JI=Rn(),XI=Zn(),ZI=Se(),eE=Ah(),tE=vo(),rE=Je(),yo=un(),wh=pi&&pi.prototype,iE=ZI("species"),To=!1,kh=KI(zI.PromiseRejectionEvent),aE=JI("Promise",function(){var i=XI(pi),e=i!==String(pi);if(!e&&yo===66||rE&&!(wh.catch&&wh.finally))return!0;if(!yo||yo<51||!/native code/.test(i)){var t=new pi(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[iE]=r,To=t.then(function(){})instanceof r,!To)return!0}return!e&&(eE||tE)&&!kh});Rh.exports={CONSTRUCTOR:aE,REJECTION_EVENT:kh,SUBCLASSING:To}});var Er=b((_k,$h)=>{"use strict";var Lh=pt(),sE=TypeError,nE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw sE("Bad Promise constructor");e=r,t=a}),this.resolve=Lh(e),this.reject=Lh(t)};$h.exports.f=function(i){return new nE(i)}});var Kh=b(()=>{"use strict";var oE=Fe(),uE=Je(),Xa=ni(),Lt=me(),wr=Pe(),Ch=vr(),Mh=Gn(),lE=_a(),cE=Cp(),dE=pt(),Ja=oe(),pE=at(),hE=Dp(),fE=to(),_h=po().set,Ao=vh(),mE=Th(),bE=Qa(),gE=ho(),Nh=Pn(),Za=zt(),wo=Ir(),Fh=Er(),es="Promise",qh=wo.CONSTRUCTOR,SE=wo.REJECTION_EVENT,vE=wo.SUBCLASSING,Io=Nh.getterFor(es),yE=Nh.set,xr=Za&&Za.prototype,Kt=Za,za=xr,Uh=Lt.TypeError,Eo=Lt.document,ko=Lt.process,xo=Fh.f,TE=xo,IE=!!(Eo&&Eo.createEvent&&Lt.dispatchEvent),Hh="unhandledrejection",EE="rejectionhandled",Dh=0,jh=1,xE=2,Ro=1,Gh=2,Ka,Oh,PE,Bh,Yh=function(i){var e;return pE(i)&&Ja(e=i.then)?e:!1},Wh=function(i,e){var t=e.value,r=e.state==jh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===Gh&&wE(e),e.rejection=Ro),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(Uh("Promise-chain cycle")):(l=Yh(u))?wr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Qh=function(i,e){i.notified||(i.notified=!0,Ao(function(){for(var t=i.reactions,r;r=t.get();)Wh(r,i);i.notified=!1,e&&!i.rejection&&AE(i)}))},zh=function(i,e,t){var r,a;IE?(r=Eo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Lt.dispatchEvent(r)):r={promise:e,reason:t},!SE&&(a=Lt["on"+i])?a(r):i===Hh&&mE("Unhandled promise rejection",t)},AE=function(i){wr(_h,Lt,function(){var e=i.facade,t=i.value,r=Vh(i),a;if(r&&(a=bE(function(){Xa?ko.emit("unhandledRejection",t,e):zh(Hh,e,t)}),i.rejection=Xa||Vh(i)?Gh:Ro,a.error))throw a.value})},Vh=function(i){return i.rejection!==Ro&&!i.parent},wE=function(i){wr(_h,Lt,function(){var e=i.facade;Xa?ko.emit("rejectionHandled",e):zh(EE,e,i.value)})},Pr=function(i,e,t){return function(r){i(e,r,t)}},Ar=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=xE,Qh(i,!0))},Po=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Uh("Promise can't be resolved itself");var r=Yh(e);r?Ao(function(){var a={done:!1};try{wr(r,e,Pr(Po,a,i),Pr(Ar,a,i))}catch(s){Ar(a,s,i)}}):(i.value=e,i.state=jh,Qh(i,!1))}catch(a){Ar({done:!1},a,i)}}};if(qh&&(Kt=function(e){hE(this,za),dE(e),wr(Ka,this);var t=Io(this);try{e(Pr(Po,t),Pr(Ar,t))}catch(r){Ar(t,r)}},za=Kt.prototype,Ka=function(e){yE(this,{type:es,done:!1,notified:!1,parent:!1,reactions:new gE,rejection:!1,state:Dh,value:void 0})},Ka.prototype=Ch(za,"then",function(e,t){var r=Io(this),a=xo(fE(this,Kt));return r.parent=!0,a.ok=Ja(e)?e:!0,a.fail=Ja(t)&&t,a.domain=Xa?ko.domain:void 0,r.state==Dh?r.reactions.add(a):Ao(function(){Wh(a,r)}),a.promise}),Oh=function(){var i=new Ka,e=Io(i);this.promise=i,this.resolve=Pr(Po,e),this.reject=Pr(Ar,e)},Fh.f=xo=function(i){return i===Kt||i===PE?new Oh(i):TE(i)},!uE&&Ja(Za)&&xr!==Object.prototype)){Bh=xr.then,vE||Ch(xr,"then",function(e,t){var r=this;return new Kt(function(a,s){wr(Bh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete xr.constructor}catch(i){}Mh&&Mh(xr,za)}oE({global:!0,constructor:!0,wrap:!0,forced:qh},{Promise:Kt});lE(Kt,es,!1,!0);cE(es)});var tf=b((qk,ef)=>{"use strict";var kE=Se(),Xh=kE("iterator"),Zh=!1;try{Jh=0,Lo={next:function(){return{done:!!Jh++}},return:function(){Zh=!0}},Lo[Xh]=function(){return this},Array.from(Lo,function(){throw 2})}catch(i){}var Jh,Lo;ef.exports=function(i,e){if(!e&&!Zh)return!1;var t=!1;try{var r={};r[Xh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var $o=b((Uk,rf)=>{"use strict";var RE=zt(),LE=tf(),$E=Ir().CONSTRUCTOR;rf.exports=$E||!LE(function(i){RE.all(i).then(void 0,function(){})})});var af=b(()=>{"use strict";var CE=Fe(),ME=Pe(),DE=pt(),OE=Er(),BE=Qa(),VE=Ha(),_E=$o();CE({target:"Promise",stat:!0,forced:_E},{all:function(e){var t=this,r=OE.f(t),a=r.resolve,s=r.reject,n=BE(function(){var o=DE(t.resolve),u=[],l=0,c=1;VE(e,function(d){var p=l++,h=!1;c++,ME(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var nf=b(()=>{"use strict";var NE=Fe(),FE=Je(),qE=Ir().CONSTRUCTOR,Mo=zt(),UE=dt(),HE=oe(),jE=vr(),sf=Mo&&Mo.prototype;NE({target:"Promise",proto:!0,forced:qE,real:!0},{catch:function(i){return this.then(void 0,i)}});!FE&&HE(Mo)&&(Co=UE("Promise").prototype.catch,sf.catch!==Co&&jE(sf,"catch",Co,{unsafe:!0}));var Co});var of=b(()=>{"use strict";var GE=Fe(),YE=Pe(),WE=pt(),QE=Er(),zE=Qa(),KE=Ha(),JE=$o();GE({target:"Promise",stat:!0,forced:JE},{race:function(e){var t=this,r=QE.f(t),a=r.reject,s=zE(function(){var n=WE(t.resolve);KE(e,function(o){YE(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var uf=b(()=>{"use strict";var XE=Fe(),ZE=Pe(),ex=Er(),tx=Ir().CONSTRUCTOR;XE({target:"Promise",stat:!0,forced:tx},{reject:function(e){var t=ex.f(this);return ZE(t.reject,void 0,e),t.promise}})});var Do=b((Jk,lf)=>{"use strict";var rx=ze(),ix=at(),ax=Er();lf.exports=function(i,e){if(rx(i),ix(e)&&e.constructor===i)return e;var t=ax.f(i),r=t.resolve;return r(e),t.promise}});var pf=b(()=>{"use strict";var sx=Fe(),nx=dt(),cf=Je(),ox=zt(),df=Ir().CONSTRUCTOR,ux=Do(),lx=nx("Promise"),cx=cf&&!df;sx({target:"Promise",stat:!0,forced:cf||df},{resolve:function(e){return ux(cx&&this===lx?ox:this,e)}})});var hf=b(()=>{"use strict";Kh();af();nf();of();uf();pf()});var gf=b(()=>{"use strict";var dx=Fe(),px=Je(),ts=zt(),hx=Oe(),mf=dt(),bf=oe(),fx=to(),ff=Do(),mx=vr(),Bo=ts&&ts.prototype,bx=!!ts&&hx(function(){Bo.finally.call({then:function(){}},function(){})});dx({target:"Promise",proto:!0,real:!0,forced:bx},{finally:function(i){var e=fx(this,mf("Promise")),t=bf(i);return this.then(t?function(r){return ff(e,i()).then(function(){return r})}:i,t?function(r){return ff(e,i()).then(function(){throw r})}:i)}});!px&&bf(ts)&&(Oo=mf("Promise").prototype.finally,Bo.finally!==Oo&&mx(Bo,"finally",Oo,{unsafe:!0}));var Oo});var rs=b((aR,Sf)=>{"use strict";var gx=dt();Sf.exports=gx});var yf=b((sR,vf)=>{"use strict";Ap();hf();gf();var Sx=rs();vf.exports=Sx("Promise","finally")});var If=b((nR,Tf)=>{"use strict";var vx=yf();Tf.exports=vx});var is=b((oR,Ef)=>{"use strict";var yx=If();Ef.exports=yx});var Mf=b(()=>{"use strict";var kx=Fe(),Rx=Zr(),Lx=Ma(),$x=Ca(),Cx=Xs();kx({target:"Array",proto:!0},{at:function(e){var t=Rx(this),r=Lx(t),a=$x(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});Cx("at")});var Of=b((sL,Df)=>{"use strict";Mf();var Mx=rs();Df.exports=Mx("Array","at")});var Vf=b((nL,Bf)=>{"use strict";var Dx=Of();Bf.exports=Dx});var fi=b((oL,_f)=>{"use strict";var Ox=Vf();_f.exports=Ox});var km=b(()=>{"use strict"});var Rm=b(()=>{"use strict"});var $m=b((iD,Lm)=>{"use strict";var SP=at(),vP=hr(),yP=Se(),TP=yP("match");Lm.exports=function(i){var e;return SP(i)&&((e=i[TP])!==void 0?!!e:vP(i)=="RegExp")}});var Mm=b((aD,Cm)=>{"use strict";var IP=yr(),EP=String;Cm.exports=function(i){if(IP(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return EP(i)}});var Om=b((sD,Dm)=>{"use strict";var xP=ze();Dm.exports=function(){var i=xP(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 _m=b((nD,Vm)=>{"use strict";var PP=Pe(),AP=Xe(),wP=zr(),kP=Om(),Bm=RegExp.prototype;Vm.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Bm)&&!AP(i,"flags")&&wP(Bm,i)?PP(kP,i):e}});var Fm=b((oD,Nm)=>{"use strict";var nu=xe(),RP=Zr(),LP=Math.floor,au=nu("".charAt),$P=nu("".replace),su=nu("".slice),CP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,MP=/\$([$&'`]|\d{1,2})/g;Nm.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=MP;return a!==void 0&&(a=RP(a),u=CP),$P(s,u,function(l,c){var d;switch(au(c,0)){case"$":return"$";case"&":return i;case"`":return su(e,0,t);case"'":return su(e,n);case"<":d=a[su(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=LP(p/10);return h===0?l:h<=o?r[h-1]===void 0?au(c,1):r[h-1]+au(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Gm=b(()=>{"use strict";var DP=Fe(),OP=Pe(),ou=xe(),qm=Sa(),BP=oe(),VP=fr(),_P=$m(),Br=Mm(),NP=Xr(),FP=_m(),qP=Fm(),UP=Se(),HP=Je(),jP=UP("replace"),GP=TypeError,jm=ou("".indexOf),YP=ou("".replace),Um=ou("".slice),WP=Math.max,Hm=function(i,e,t){return t>i.length?-1:e===""?t:jm(i,e,t)};DP({target:"String",proto:!0},{replaceAll:function(e,t){var r=qm(this),a,s,n,o,u,l,c,d,p,h=0,m=0,g="";if(!VP(e)){if(a=_P(e),a&&(s=Br(qm(FP(e))),!~jm(s,"g")))throw GP("`.replaceAll` does not allow non-global regexes");if(n=NP(e,jP),n)return OP(n,e,r,t);if(HP&&a)return YP(Br(r),e,t)}for(o=Br(r),u=Br(e),l=BP(t),l||(t=Br(t)),c=u.length,d=WP(1,c),h=Hm(o,u,0);h!==-1;)p=l?Br(t(u,h,o)):qP(u,o,h,[],void 0,t),g+=Um(o,m,h)+p,m=h+c,h=Hm(o,u,h+d);return m<o.length&&(g+=Um(o,m)),g}})});var Wm=b((cD,Ym)=>{"use strict";km();Rm();Gm();var QP=rs();Ym.exports=QP("String","replaceAll")});var zm=b((dD,Qm)=>{"use strict";var zP=Wm();Qm.exports=zP});var Jm=b((pD,Km)=>{"use strict";var KP=zm();Km.exports=KP});var dA={};sg(dA,{ChromecastState:()=>Wr,HttpConnectionType:()=>ma,Observable:()=>lt.Observable,PlaybackState:()=>ye,Player:()=>la,SDK_VERSION:()=>cA,Subject:()=>lt.Subject,Subscription:()=>lt.Subscription,Surface:()=>ba,VERSION:()=>zs,ValueSubject:()=>lt.ValueSubject,VideoFormat:()=>ct,VideoQuality:()=>lt.VideoQuality});module.exports=ng(dA);var zs="2.0.106";var ye=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ye||{}),ct=(P=>(P.MPEG="MPEG",P.DASH="DASH",P.DASH_SEP="DASH_SEP",P.DASH_SEP_VK="DASH_SEP",P.DASH_WEBM="DASH_WEBM",P.DASH_WEBM_AV1="DASH_WEBM_AV1",P.DASH_STREAMS="DASH_STREAMS",P.DASH_WEBM_VK="DASH_WEBM",P.DASH_ONDEMAND="DASH_ONDEMAND",P.DASH_ONDEMAND_VK="DASH_ONDEMAND",P.DASH_LIVE="DASH_LIVE",P.DASH_LIVE_CMAF="DASH_LIVE_CMAF",P.DASH_LIVE_WEBM="DASH_LIVE_WEBM",P.HLS="HLS",P.HLS_ONDEMAND="HLS_ONDEMAND",P.HLS_JS="HLS",P.HLS_LIVE="HLS_LIVE",P.HLS_LIVE_CMAF="HLS_LIVE_CMAF",P.WEB_RTC_LIVE="WEB_RTC_LIVE",P))(ct||{});var Wr=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Wr||{}),ma=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ma||{});var ba=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ba||{});var F=require("@vkontakte/videoplayer-shared");var zu=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 ga=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;var s;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,F.isNonNullable)((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||zu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,a,s;(s=(a=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:a.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.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,F.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var s,n;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.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,F.assertNever)(a.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),(0,F.map)(a=>a.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(ug),(0,F.tap)(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();(0,F.assertNonNullable)(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;((0,F.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){var a;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(s){return}try{e.setOptions({receiverApplicationId:(a=this.params.receiverApplicationId)!=null?a:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},ug=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,F.assertNever)(i)}};var vb=Qe(Jn(),1);var wf=Qe(is(),1);var Vo=require("@vkontakte/videoplayer-shared");var ve=(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,Vo.assertNever)(t)}return i},_o=(i,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,Vo.assertNever)(e)}};var w=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};var nt=require("@vkontakte/videoplayer-shared"),H=class{constructor(e){this.transitionStarted$=new nt.Subject;this.transitionEnded$=new nt.Subject;this.transitionUpdated$=new nt.Subject;this.forceChanged$=new nt.Subject;this.stateChangeStarted$=(0,nt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,nt.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,nt.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 xf=require("@vkontakte/videoplayer-shared"),Pf=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":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,xf.assertNever)(i)}};var L=require("@vkontakte/videoplayer-shared");var Tx=5,Ix=5,Ex=500,Af=7e3,hi=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.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==null?void 0: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,L.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,L.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,L.assertNever)(e)}break}default:(0,L.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(Pf(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 L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe((0,L.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 L.Subject;e.add(a.pipe((0,L.debounce)(Ex)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.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)>Tx)&&a.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.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,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.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(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Ix&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(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(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var a,s;let t=this.params.output.volume$.getValue(),r={volume:(a=e.volume)!=null?a:t.volume,muted:(s=e.muted)!=null?s: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){var l;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];(0,L.assertNonNullable)(c);let d=(0,L.getHighestQuality)(Object.keys(c));(0,L.assertNonNullable)(d);let p=c[d];(0,L.assertNonNullable)(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,L.assertNonNullable)(c),r=c.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":case"DASH_STREAMS":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=ve(c.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(u)&&(n.metadata.subtitle=u),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,L.timeout)(Af).subscribe(()=>s(`timeout(${Af})`)))});(0,wf.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:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Uo=require("@vkontakte/videoplayer-shared");var kf=require("@vkontakte/videoplayer-shared"),Rf=i=>{try{i.pause(),i.playbackRate=0,(0,kf.clearVideoElement)(i),i.remove()}catch(e){console.error(e)}};var as=require("@vkontakte/videoplayer-shared"),No=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)}},Fo=window.WeakMap?new WeakMap:new No,qo=window.WeakMap?new WeakMap:new Map,xx=(i,e=20)=>{let t=0;return(0,as.fromEvent)(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},Ae=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?(0,Uo.clearVideoElement)(t):(t=document.createElement("video"),i.appendChild(t)),Fo.set(t,r);let a=new as.Subscription;return a.add(xx(t,e)),qo.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},we=i=>{let e=qo.get(i);e==null||e.unsubscribe(),qo.delete(i);let t=Fo.get(i);Fo.delete(i),t?(0,Uo.clearVideoElement)(i):Rf(i)};var $=require("@vkontakte/videoplayer-shared");var $t=require("@vkontakte/videoplayer-shared"),ss=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=(0,$t.isNullable)(a),l=new $t.Subscription;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},ot=(i,e,t)=>ss(e,()=>i.loop,r=>{(0,$t.isNonNullable)(r)&&(i.loop=r)},{onError:t}),ke=(i,e,t,r)=>ss(e,()=>({muted:i.muted,volume:i.volume}),a=>{(0,$t.isNonNullable)(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||(a==null?void 0:a.muted)===(s==null?void 0:s.muted)&&(a==null?void 0:a.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),qe=(i,e,t,r)=>ss(e,()=>i.playbackRate,a=>{(0,$t.isNonNullable)(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),Ct=ss;var Px=i=>["__",i.language,i.label].join("|"),Ax=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Ho=class i{constructor(){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.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:$.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(Ct(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(Ct(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(Ct(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(Ct(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).subscribe(this.current$));let t=r=>{var a,s;return this.applyCueSettings((s=(a=r.target)==null?void 0:a.activeCues)!=null?s:null)};this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",a))};(n=r.track)==null||n.addEventListener("cuechange",a)})),this.subscription.add((0,$.fromEvent)(e,"removetrack").subscribe(r=>{var a;(a=r.track)==null||a.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,$.isNonNullable)(t.align)&&(a.align=t.align),(0,$.isNonNullable)(t.position)&&(a.position=t.position),(0,$.isNonNullable)(t.size)&&(a.size=t.size),(0,$.isNonNullable)(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,a=e.id?e.id:Px(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(a))==null?void 0:o.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(a))==null?void 0:u.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,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!Ax(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,$.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,$.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)}},Ue=Ho;var mt=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 Lf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},jo=i=>{let e=Lf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},$f=i=>{let e=Lf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var R=require("@vkontakte/videoplayer-shared");var wx=3,Cf=(i,e,t=wx)=>{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 u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var Re=i=>{let e=I=>(0,R.fromEvent)(i,I).pipe((0,R.mapTo)(void 0)),r=(0,R.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,R.fromEvent)(i,I))).pipe((0,R.map)(I=>I.type==="ended"?i.readyState<2:i.readyState<3),(0,R.filterChanged)()),a=(0,R.merge)((0,R.fromEvent)(i,"progress"),(0,R.fromEvent)(i,"timeupdate")).pipe((0,R.map)(()=>Cf(i.buffered,i.currentTime))),n=(0,R.getCurrentBrowser)().browser===R.CurrentClientBrowser.Safari?(0,R.combine)({play:e("play").pipe((0,R.once)()),playing:e("playing")}).pipe((0,R.mapTo)(void 0)):e("playing"),o=(0,R.fromEvent)(i,"volumechange").pipe((0,R.map)(()=>({muted:i.muted,volume:i.volume}))),u=(0,R.fromEvent)(i,"ratechange").pipe((0,R.map)(()=>i.playbackRate)),l=(0,R.fromEvent)(i,"error").pipe((0,R.filter)(()=>!!(i.error||i.played.length)),(0,R.map)(()=>{var E;let I=i.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:R.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(E=i.error)!=null?E:void 0}})),c=(0,R.fromEvent)(i,"timeupdate").pipe((0,R.map)(()=>i.currentTime)),d=new R.Subject,p=.3,h;c.subscribe(I=>{i.loop&&(0,R.isNonNullable)(h)&&(0,R.isNonNullable)(I)&&h>=i.duration-p&&I<=p&&d.next(h),h=I});let m=e("pause").pipe((0,R.filter)(()=>!i.error&&h!==i.duration)),g=(0,R.fromEvent)(i,"enterpictureinpicture"),S=(0,R.fromEvent)(i,"leavepictureinpicture"),T=new R.ValueSubject($f(i));g.subscribe(()=>T.next(!0)),S.subscribe(()=>T.next(!1));let A=new R.ValueSubject(jo(i));return(0,R.fromEvent)(i,"fullscreenchange").pipe((0,R.map)(()=>jo(i))).subscribe(A),{playing$:n,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,R.fromEvent)(i,"durationchange").pipe((0,R.map)(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:A}};var bt=require("@vkontakte/videoplayer-shared"),Mt=i=>{switch(i){case"mobile":return bt.VideoQuality.Q_144P;case"lowest":return bt.VideoQuality.Q_240P;case"low":return bt.VideoQuality.Q_360P;case"sd":case"medium":return bt.VideoQuality.Q_480P;case"hd":case"high":return bt.VideoQuality.Q_720P;case"fullhd":case"full":return bt.VideoQuality.Q_1080P;case"quadhd":case"quad":return bt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return bt.VideoQuality.Q_2160P}};var Yo=Qe(fi(),1),Y=require("@vkontakte/videoplayer-shared");var Go=!1,gt={},Nf=i=>{Go=i},Ff=()=>{gt={}},qf=i=>{i(gt)},mi=(i,e)=>{var t;Go&&(gt.meta=(t=gt.meta)!=null?t:{},gt.meta[i]=e)},Te=class{constructor(e){this.name=e}next(e){var r,a;if(!Go)return;gt.series=(r=gt.series)!=null?r:{};let t=(a=gt.series[this.name])!=null?a:[];t.push([Date.now(),e]),gt.series[this.name]=t}};var Bx=new Te("best_bitrate"),Vx=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,ns=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,Y.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},_x='Assertion "ABR Tracks is empty array" failed',Nx=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var Z,N,C,ee,le;(0,Y.assertNotEmptyArray)(i,_x);let p=r.usePixelRatio&&(Z=window.devicePixelRatio)!=null?Z:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},m=h&&(0,Y.videoSizeToQuality)(h),g=r.considerPlaybackRate&&(0,Y.isNonNullable)(o)?o:1,S=i.filter(B=>!(0,Y.isInvariantQuality)(B.quality)).sort((B,k)=>(0,Y.isHigher)(B.quality,k.quality)?-1:1),T=(N=(0,Yo.default)(S,-1))==null?void 0:N.quality,A=(C=(0,Yo.default)(S,0))==null?void 0:C.quality,P=(0,Y.isNullable)(a)||(0,Y.isNonNullable)(a.min)&&(0,Y.isNonNullable)(a.max)&&(0,Y.isLower)(a.max,a.min)||(0,Y.isNonNullable)(a.min)&&A&&(0,Y.isHigher)(a.min,A)||(0,Y.isNonNullable)(a.max)&&T&&(0,Y.isLower)(a.max,T),I=g*Vx(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},W=S.filter(B=>(m?(0,Y.isLower)(B.quality,m):!0)?((0,Y.isNonNullable)(t)&&isFinite(t)&&(0,Y.isNonNullable)(B.bitrate)?t-s>=B.bitrate*I:!0)?r.lazyQualitySwitch&&(0,Y.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,Y.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,Y.isHigher)(B.quality,u.quality)?(E[B.quality]="Buffer",!1):!!c&&(0,Y.isHigherOrEqual)(B.quality,c)?(E[B.quality]="DroppedFramesLimit",!1):P||((0,Y.isNullable)(a.max)||(0,Y.isLowerOrEqual)(B.quality,a.max))&&((0,Y.isNullable)(a.min)||(0,Y.isHigherOrEqual)(B.quality,a.min))?!0:(E[B.quality]="FitsQualityLimits",!1):(E[B.quality]="FitsThroughput",!1):(E[B.quality]="FitsContainer",!1))[0];W&&W.bitrate&&Bx.next(W.bitrate);let U=(ee=W!=null?W:S[Math.ceil((S.length-1)/2)])!=null?ee:i[0];U.quality!==((le=l==null?void 0:l.last)==null?void 0:le.quality)&&d({message:`
|
|
7
7
|
[available tracks]
|
|
8
|
-
${
|
|
8
|
+
${i.map(B=>`{ id: ${B.id}, quality: ${B.quality}, bitrate: ${B.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(
|
|
12
|
+
${Object.entries(r!=null?r:{}).map(([B,k])=>`${B}: ${k}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${m},
|
|
17
17
|
throughput: ${t},
|
|
18
|
-
reserve: ${
|
|
18
|
+
reserve: ${s},
|
|
19
19
|
playbackRate: ${o},
|
|
20
|
-
playbackRateFactor: ${
|
|
21
|
-
forwardBufferHealth: ${
|
|
22
|
-
bitrateFactor: ${
|
|
23
|
-
minBufferToSwitchUp: ${
|
|
24
|
-
droppedVideoMaxQualityLimit: ${
|
|
25
|
-
limitsAreInvalid: ${
|
|
26
|
-
maxQualityLimit: ${
|
|
27
|
-
minQualityLimit: ${
|
|
20
|
+
playbackRateFactor: ${g},
|
|
21
|
+
forwardBufferHealth: ${n},
|
|
22
|
+
bitrateFactor: ${I},
|
|
23
|
+
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
24
|
+
droppedVideoMaxQualityLimit: ${c},
|
|
25
|
+
limitsAreInvalid: ${P},
|
|
26
|
+
maxQualityLimit: ${a==null?void 0:a.max},
|
|
27
|
+
minQualityLimit: ${a==null?void 0:a.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
30
|
+
${Object.entries(E).map(([B,k])=>`${B}: ${k}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
|
-
[best track] ${
|
|
33
|
+
[best track] ${W==null?void 0:W.quality}
|
|
34
34
|
[selected track] ${U==null?void 0:U.quality}
|
|
35
|
-
`});let
|
|
36
|
-
[last selected] ${
|
|
37
|
-
`}),C}return d==null||d.recordSwitch(U),U},ct=so;var he=n=>new URL(n).hostname;var D=require("@vkontakte/videoplayer-shared");var rs=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},xe=n=>R(void 0,null,function*(){let e=n.muted;try{yield n.play()}catch(t){if(!rs(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{yield n.play()}catch(i){return rs(i)&&(n.muted=!1,console.warn(i)),!1}}return!0});var $e=require("@vkontakte/videoplayer-shared");var Qe=require("@vkontakte/videoplayer-shared");function me(){return(0,Qe.now)()}function Xr(n){return me()-n}function Zr(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function as(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Bt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,l,c,p=!1,h="arraybuffer",f=7e3,b=2e3,y=()=>{if(u)return;(0,Qe.assertNonNullable)(l);let L=Xr(l),Z;if(L<b){Z=b-L,setTimeout(y,Z);return}b*=2,b>f&&(b=f),s&&s.abort(),s=new r,z()},x=L=>(a=L,_),O=L=>(c=L,_),E=()=>(h="json",_),v=()=>{if(!u){if(--d>=0){y(),i&&i();return}u=!0,c&&c(),t&&t()}},T=L=>(p=L,_),z=()=>{l=me(),s=new r,s.open("get",n);let L=0,Z,oe=0,C=()=>((0,Qe.assertNonNullable)(l),Math.max(l,Math.max(Z||0,oe||0)));if(a&&s.addEventListener("progress",k=>{let K=me();a.updateChunk&&k.loaded>L&&(a.updateChunk(C(),k.loaded-L),L=k.loaded,Z=K)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>v())),s.addEventListener("load",()=>{if(u)return;(0,Qe.assertNonNullable)(s);let k=s.status;if(k>=200&&k<300){if(s.response.byteLength&&a){let K=s.response.byteLength-L;K&&a.updateChunk&&a.updateChunk(C(),K)}s.responseType==="json"&&!Object.values(s.response).length?v():(c&&c(),e(s.response))}else v()}),s.addEventListener("error",()=>{v()}),p){let k=()=>{(0,Qe.assertNonNullable)(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(oe=me(),s.removeEventListener("readystatechange",k))};s.addEventListener("readystatechange",k)}return s.responseType=h,s.send(),_},_={withBitrateReporting:x,withParallel:T,withJSONResponse:E,withRetryCount:L=>(d=L,_),withRetryInterval:(L,Z)=>((0,Qe.isNonNullable)(L)&&(b=L),(0,Qe.isNonNullable)(Z)&&(f=Z),_),withTimeout:L=>(o=L,_),withFinally:O,send:z,abort:()=>{s&&(s.abort(),s=void 0),u=!0,c&&c()}};return _}var ti=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,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;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(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>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 ii=class{constructor(e,t,i,r,a){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=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}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 i=me(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=me()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Bt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=me()}_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=me();if(Object.keys(this.activeRequests).length>=e)return!1;let 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();){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,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._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(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var rr=1e4,ea=3;var oo=6e4,uo=10,lo=1,co=500,ri=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 ti(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Zr(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;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=Zr(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,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(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let 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(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,$e.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=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())});let s=()=>{as(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ii(ea,rr,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,d=null,l=!1,c=()=>{let v=a&&(!l||l===this.rep);return v||t("Not running!"),v},p=(v,T,z)=>{u&&u.abort(),u=Bt(this.urlResolver.resolve(v,!1),T,z,()=>this._retryCallback()).withTimeout(rr).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ea).withFinally(()=>{u=null}).send()},h=(v,T,z)=>{(0,$e.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),T,z,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=v=>{let T=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${T}=>${v}`),i.playbackRate=v)},b=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let z=me()-1e4,Y=0;for(let j=0;j<this.bufferStates.length;j++){let X=this.bufferStates[j];v=Math.min(v,X.buf),X.ts<z&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${v} drop=${Y} jitter=${this.sourceJitter}`);let U=v-lo;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?f(1.15):U>1?f(1.1):U>.3?f(1.05):f(1)}},x=v=>{let T,z=()=>T&&T.start?T.start.length:0,Y=k=>T.start[k]/1e3,U=k=>T.dur[k]/1e3,j=k=>T.fragIndex+k,X=(k,K)=>({chunkIdx:j(k),startTS:Y(k),dur:U(k),discontinuity:K}),_=()=>{let k=0;if(T&&T.dur){let K=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,re=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ue=K;this.sourceJitter>1&&(ue+=this.sourceJitter-1);let W=T.dur.length-1;for(;W>=0&&(ue-=T.dur[W],!(ue<=0));--W);k=Math.min(W,T.dur.length-1-re),k=Math.max(k,0)}return X(k,!0)},L=k=>{let K=z();if(!(K<=0)){if((0,$e.isNonNullable)(k)){for(let re=0;re<K;re++)if(Y(re)>k)return X(re)}return _()}},Z=k=>{let K=z(),re=k?k.chunkIdx+1:0,ue=re-T.fragIndex;if(!(K<=0)){if(!k||ue<0||ue-K>uo)return t(`Resync: offset=${ue} bChunks=${K} chunk=`+JSON.stringify(k)),_();if(!(ue>=K))return X(re-T.fragIndex,!1)}},oe=(k,K,re)=>{d&&d.abort(),d=Bt(this.urlResolver.resolve(k,!0,this.lowLatency),K,re,()=>this._retryCallback()).withTimeout(rr).withRetryCount(ea).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,K)=>{oe(v,re=>{if(!c())return;T=re;let ue=!!T.lowLatency;ue!==this.lowLatency&&b(ue);let W=0;for(let Oe=0;Oe<T.dur.length;++Oe)W+=T.dur[Oe];W>0&&((0,$e.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(W/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,k(L(K))},()=>this._handleNetworkError())},nextChunk:Z}},O=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),(0,$e.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:v=>{let{videoElement:T,logger:z}=this.params,Y=x(e.jidxUrl),U,j,X,_,L=0,Z,oe,C,k=()=>{Z&&(clearTimeout(Z),Z=void 0);let ee=Math.max(co,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=L+ee,we=me(),Me=Math.min(1e4,Se-we);L=we;let st=()=>{d||c()&&Y.seek(()=>{c()&&(L=me(),K(),k())})};Me>0?Z=window.setTimeout(()=>{this.paused?k():st()},Me):st()},K=()=>{let ee;for(;ee=Y.nextChunk(_);)_=ee,ht(ee);let Se=Y.nextChunk(X);if(Se){if(X&&Se.discontinuity){z("Detected discontinuity; restarting playback"),this.paused?k():(O(),this._initPlayerWith(e));return}Oe(Se)}else k()},re=(ee,Se)=>{if(!c()||!this.sourceBuffer)return;let we,Me,st,Mt=nt=>{window.setTimeout(()=>{c()&&re(ee,Se)},nt)};if(this.sourceBuffer.updating)z("Source buffer is updating; delaying appendBuffer"),Mt(100);else{let nt=me(),mt=T.currentTime;!this.paused&&T.buffered.length>1&&oe===mt&&nt-C>500&&(z("Stall suspected; trying to fix"),this._fixupStall()),oe!==mt&&(oe=mt,C=nt);let Rt=this._getBufferSizeSec();if(Rt>30)z(`Buffered ${Rt} seconds; delaying appendBuffer`),Mt(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:nt,buf:Rt}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(Qt){if(Qt.name==="QuotaExceededError")z("QuotaExceededError; delaying appendBuffer"),st=this.sourceBuffer.buffered.length,st!==0&&(we=this.sourceBuffer.buffered.start(0),Me=mt,Me-we>4&&this.sourceBuffer.remove(we,Me-3)),Mt(1e3);else throw Qt}}},ue=()=>{j&&U&&(z([`Appending chunk, sz=${j.byteLength}:`,JSON.stringify(X)]),re(j,function(){j=null,K()}))},W=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Oe=ee=>{c()&&h(W(ee),(Se,we)=>{if(c()){if(we/=1e3,j=Se,X=ee,s=ee.startTS,we){let Me=Math.min(10,ee.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Me:Me}ue()}},()=>this._handleNetworkError())},ht=ee=>{c()&&((0,$e.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(W(ee),!1)))},at=ee=>{c()&&(e.cachedHeader=ee,re(ee,()=>{U=!0,ue()}))};a=!0,Y.seek(ee=>{if(c()){if(L=me(),!ee){k();return}_=ee,!(0,$e.isNullable)(v)||ee.startTS>v?Oe(ee):(X=ee,K())}},v),e.cachedHeader?at(e.cachedHeader):p(e.headerUrl,at,()=>this._handleNetworkError())},stop:O,getTimestampSec:()=>s},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,$e.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,(0,$e.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,$e.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(p,h)=>{let f=me();if(this.chunkRateEstimator.addInterval(p,f,h)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:y}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),s=-1/0,o,u=!0,d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Xr(s)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=a.updateChunk(c,p);return h&&d(),h},notifySwitch:c=>{let p=me();c<o&&(s=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Bt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(rr).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;xe(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s!=null&&s.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(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))},oo))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ne=require("@vkontakte/videoplayer-shared"),ta=class{constructor(){this.onDroopedVideoFramesLimit$=new ne.Subject;this.subscription=new ne.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ne.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ne.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var s;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,ne.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((s=this.limitCounts[this.currentQuality])!=null?s: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.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ne.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ne.interval)(this.droppedFramesChecker.checkTime).pipe((0,ne.filter)(()=>this.playing),(0,ne.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ne.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ne.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[s])=>(0,ne.isLower)(a,s)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?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}},ar=ta;var sr=require("@vkontakte/videoplayer-shared"),ss=require("@vkontakte/videoplayer-shared");var ai=()=>{var n;return!!((n=window.documentPictureInPicture)!=null&&n.window)||!!document.pictureInPictureElement};var po=(n,e)=>new sr.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||ai()))},V(V({},i),e));r.observe(n);let a=(0,ss.fromEvent)(document,"visibilitychange").pipe((0,sr.map)(s=>!document.hidden||ai())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),Ce=po;var ho=["paused","playing","ready"],mo=["paused","playing","ready"],si=class{constructor(e){this.subscription=new D.Subscription;this.videoState=new H("stopped");this.representations$=new D.ValueSubject([]);this.textTracksManager=new De;this.droppedFramesManager=new ar;this.maxSeekBackTime$=new D.ValueSubject(1/0);this.zeroTime$=new D.ValueSubject(void 0);this.liveOffset=new ze;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let s=e.isBuffering;this.params.output.isBuffering$.next(s);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:D.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let s=e.manifest,o=[];for(let u of s){let d=(t=u.name)!=null?t:u.index.toString(10),l=(i=lt(u.name))!=null?i:(0,D.videoSizeToQuality)(u.video),c=u.bitrate/1e3,p=V({},u.video);if(!l)continue;let h={id:d,quality:l,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let s=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===s))==null?void 0:a.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),(0,D.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:s,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(s,o);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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="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 s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(mo.includes(e)&&(s||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&ho.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(fe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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 u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(fe(this.params.source.url,u))}return;default:return(0,D.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:D.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,D.merge)(this.videoState.stateChangeStarted$.pipe((0,D.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,D.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ye(e.container,e.tuning),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(he(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 i=Ee(this.video);this.subscription.add(this.representations$.pipe((0,D.map)(r=>r.map(({track:a})=>a)),(0,D.filter)(r=>!!r.length),(0,D.once)()).subscribe(r=>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:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,D.filterChanged)(),(0,D.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,D.combine)({zeroTime:this.zeroTime$.pipe((0,D.filter)(D.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(We(this.video,this.params.desiredState.isLooped,t)).add(Ie(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(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(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&(0,D.videoQualityToHeight)(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.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":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.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,D.assertNever)(r.to)}},t)).add((0,D.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,D.observableFrom)(["init"])).pipe((0,D.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),Te(this.video)}createLiveDashPlayer(){let e=new ri({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(){var d,l,c,p,h,f;let e=this.representations$.getValue(),t=(l=(d=this.params.desiredState.videoTrack.getTransition())==null?void 0:d.to)!=null?l:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,D.isNonNullable)(t)?t:ct(e.map(({track:b})=>b),{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}),a=r==null?void 0:r.id,s=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let b=(f=e.find(({track:y})=>y.id===a))==null?void 0:f.representation;(0,D.assertNonNullable)(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,D.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(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var ns=si;var Xe=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var M=require("@vkontakte/videoplayer-shared");var Ze=()=>window.ManagedMediaSource||window.MediaSource,nr=()=>{var n,e;return!!(window.ManagedMediaSource&&((e=(n=window.ManagedSourceBuffer)==null?void 0:n.prototype)!=null&&e.appendBuffer))},os=()=>{var n,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(n=window.SourceBuffer)==null?void 0:n.prototype)!=null&&e.appendBuffer))},us=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Pe=require("@vkontakte/videoplayer-shared");var vs=(0,Pe.isAndroid)(),Ve=document.createElement("video"),go='video/mp4; codecs="avc1.42000a,mp4a.40.2"',So='video/mp4; codecs="hev1.1.6.L93.B0"',ys='video/webm; codecs="vp09.00.10.08"',Ts='video/webm; codecs="av01.0.00M.08"',vo='audio/mp4; codecs="mp4a.40.2"',yo='audio/webm; codecs="opus"',ds,ls,yt={mms:nr(),mse:os(),hls:!!((ds=Ve.canPlayType)!=null&&ds.call(Ve,"application/x-mpegurl")||(ls=Ve.canPlayType)!=null&&ls.call(Ve,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},cs,ps,Ae={mp4:!!((cs=Ve.canPlayType)!=null&&cs.call(Ve,"video/mp4")),webm:!!((ps=Ve.canPlayType)!=null&&ps.call(Ve,"video/webm")),cmaf:!0},ur,hs,dr,ms,lr,fs,cr,bs,pr,gs,hr,Ss,ke={h264:!!((hs=(ur=Ze())==null?void 0:ur.isTypeSupported)!=null&&hs.call(ur,go)),h265:!!((ms=(dr=Ze())==null?void 0:dr.isTypeSupported)!=null&&ms.call(dr,So)),vp9:!!((fs=(lr=Ze())==null?void 0:lr.isTypeSupported)!=null&&fs.call(lr,ys)),av1:!!((bs=(cr=Ze())==null?void 0:cr.isTypeSupported)!=null&&bs.call(cr,Ts)),aac:!!((gs=(pr=Ze())==null?void 0:pr.isTypeSupported)!=null&&gs.call(pr,vo)),opus:!!((Ss=(hr=Ze())==null?void 0:hr.isTypeSupported)!=null&&Ss.call(hr,yo))},Ot=(ke.h264||ke.h265)&&ke.aac,Tt,To=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(J(V({},n),{video:J(V({},n.video),{contentType:Ts})})),window.navigator.mediaCapabilities.decodingInfo(J(V({},n),{video:J(V({},n.video),{contentType:ys})}))]);Tt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{To()}catch(n){console.error(n)}var _t=yt.hls&&Ae.mp4,Is=()=>Object.keys(ke).filter(n=>ke[n]),Es=(n,e=!1,t=!1)=>{let i=yt.mse||yt.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&Ae.mp4&&Ot;case"DASH_WEBM":return i&&Ae.webm&&ke.vp9&&ke.opus;case"DASH_WEBM_AV1":return i&&Ae.webm&&ke.av1&&ke.opus;case"DASH_STREAMS":return i&&(Ae.mp4&&Ot||Ae.webm&&(ke.vp9||ke.av1)&&(ke.opus||ke.aac));case"DASH_LIVE":return yt.mse&&Ae.mp4&&Ot;case"DASH_LIVE_CMAF":return i&&Ae.mp4&&Ot&&Ae.cmaf;case"DASH_ONDEMAND":return i&&Ae.mp4&&Ot;case"HLS":case"HLS_ONDEMAND":return _t||e&&yt.mse&&Ae.mp4&&Ot;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _t;case"MPEG":return Ae.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return yt.webrtc&&yt.ws&&ke.h264&&(Ae.mp4||Ae.webm);default:return(0,Pe.assertNever)(r)}})},or=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Tt?Tt[t].smooth?[t,e]:Tt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Tt?Tt[t].powerEfficient?[t,e]:Tt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Pe.assertNever)(n)}return[e,t]},xs=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...or(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(vs)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...or(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...or(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...or(n),...r,"HLS","HLS_ONDEMAND"];default:(0,Pe.assertNever)(e)}return _t?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},As=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=(0,Pe.getCurrentBrowser)().device===Pe.CurrentClientDevice.Mac&&(0,Pe.getCurrentBrowser)().browser===Pe.CurrentClientBrowser.Safari;if(vs)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:(0,Pe.assertNever)(n)}else _t&&!u?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ia=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ks=n=>{if(n.size!==0){if(n.size===1)return n.values().next().value.split(".").at(0);for(let e of n){let t=e.split(".").at(0);if(t==="opus"||t==="vp09"||t==="av01")return t}return n.values().next().value.split(".").at(0)}};var ni=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};var Ps=()=>window.matchMedia("(dynamic-range: high)").matches,ra=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};var g=require("@vkontakte/videoplayer-shared");var Be=require("@vkontakte/videoplayer-shared");var Io=16,Ls=!1,ws,$s;try{Ls=(0,Be.getCurrentBrowser)().browser===Be.CurrentClientBrowser.Safari&&parseInt(($s=(ws=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:ws[1])!=null?$s:"",10)<=Io}catch(n){console.error(n)}var aa=class{constructor(e){this.bufferFull$=new Be.Subject;this.error$=new Be.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Be.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return R(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let i;Ls&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{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}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.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:Be.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,Be.assertNever)(t)}}},Ms=aa;var sa=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared");var te=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),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 r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 Nt=class extends te{};var oi=class extends te{};var ui=class extends te{constructor(t,i){super(t,i);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var di=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var li=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends te{constructor(t,i){super(t,i);this.data=this.content}};var de=class extends te{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var It=class extends de{constructor(t,i){super(t,i);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 r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,o=a<<1>>>1,u=this.readUint32();a=this.readUint32();let d=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:o,subsegmentDuration:u,SAPType:d,SAPDeltaTime:l})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var pi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends de{constructor(t,i){super(t,i);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 fi=class extends de{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var bi=class extends de{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var gi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends de{constructor(t,i){super(t,i);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 vi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends de{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var Ii=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends de{constructor(t,i){super(t,i);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 xi=class extends de{constructor(t,i){super(t,i);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 Ai=class extends de{constructor(t,i){super(t,i);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 r=0;r<this.sampleCount;r++)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 xo={ftyp:ui,moov:di,moof:li,mdat:ci,sidx:It,trak:pi,mdia:gi,mfhd:Ti,tkhd:Si,traf:Ii,tfhd:Ei,tfdt:xi,trun:Ai,minf:vi,sv3d:hi,st3d:mi,prhd:fi,proj:yi,equi:bi,uuid:oi,unknown:Nt},Et=class n{constructor(e={}){this.options=V({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch(r){break}return t}createBox(e,t){let i=xo[e];return i?new i(t,new n):new Nt(t,new n)}};var Ft=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 ko=new TextDecoder("ascii"),Po=n=>ko.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",wo=n=>{let e=new It(n,new Et),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},$o=(n,e)=>{let i=new Et().parse(n),r=new Ft(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,c)},Lo=(n,e)=>{let i=new Et().parse(n),a=new Ft(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,p)=>c+p,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},Mo=n=>{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}}},i=new Et().parse(n),r=new Ft(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Rs={validateData:Po,parseInit:Mo,getIndexRange:()=>{},parseSegments:wo,parseFeedableSegmentChunk:$o,getSegmentEndTime:Lo};var et=require("@vkontakte/videoplayer-shared");var Cs=require("@vkontakte/videoplayer-shared");var Ds={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"}},Vs=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ki(n,t),r=i in Ds,a=r?Ds[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,l=ki(u),c=d*He(2,(o-1)*8)+l,p=t+o,h;return p+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},ki=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*He(2,16)+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*He(2,32)+n.getUint32(1);case 6:return n.getUint16(0)*He(2,32)+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ne=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ki(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:(0,Cs.assertNever)(e)}},xt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Vs(i);if(!e(r))return;r.type==="master"&&xt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Bs=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Vs(n);return xt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=Ne(o,s):a===17026?t=Ne(o,s):a===17029&&(i=Ne(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Os=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ro=[231,22612,22743,167,171,163,160,175],Do=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,l=!1,c=0;return xt(n,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let y=Ne(f,h);d=ki(y)}else p!==21420&&(d=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=Ne(f,h):p===17545?r=Ne(f,h):p===21420&&d===475249515?u=Ne(f,h):p===374648427?xt(f,({tag:y,type:x,value:O})=>y===30321?(l=Ne(O,x)===1,!1):!0):a&&s&&Os.includes(p)&&(o=!0),!o}),(0,et.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,et.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,et.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?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:u,is3dVideo:l,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Co=n=>{if((0,et.isNullable)(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Vo=(n,e)=>{let t=!1,i=!1,r=o=>(0,et.isNonNullable)(o.time)&&(0,et.isNonNullable)(o.position),a=[],s;return xt(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Ne(d,u));break;case 183:break;case 241:s&&(s.position=Ne(d,u));break;default:t&&Os.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:l}=o,c=a[u+1];return{status:"none",time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Bo=n=>{let e=0,t=!1;try{xt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ro.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},_s={validateData:Bs,parseInit:Do,getIndexRange:Co,parseSegments:Vo,parseFeedableSegmentChunk:Bo};var Ut=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return _s;case"mp4":return Rs}}throw new ReferenceError(`Unsupported mime type ${n}`)};var Ht=require("@vkontakte/videoplayer-shared");var Ns=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Fs=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},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(n),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},At=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>(0,Ht.isNullable)(a)?o:(0,Ht.isNullable)(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Hs=(n,e)=>{var v,T,z,Y,U,j,X,_,L,Z,oe,C,k,K,re,ue,W,Oe,ht,at,ee,Se,we,Me,st,Mt,nt,mt,Rt,Qt,Sa,va,ya,Ta,Ia,Ea,xa,Aa,ka,Pa,wa,$a,La,Ma,Ra,Da,Ca,Va,Ba,Oa;let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=(z=(T=(v=a.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:T.trim())!=null?z:"",u=s.children,d=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),f=s.getAttribute("duration"),b=a.getElementsByTagName("vk:Attrs")[0],y=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Fs(h);else if(f){let ve=Fs(f);(0,Ht.isNonNullable)(ve)&&(p=ve)}else y&&(p=parseInt(y,10));let x=0,O=(U=(Y=a.getAttribute("profiles"))==null?void 0:Y.split(","))!=null?U:[];for(let ve of u){let bn=(j=ve.getAttribute("id"))!=null?j:"id"+(x++).toString(10),Yt=(X=ve.getAttribute("mimeType"))!=null?X:"",Lr=(_=ve.getAttribute("codecs"))!=null?_:"",Mr=(L=ve.getAttribute("contentType"))!=null?L:Yt==null?void 0:Yt.split("/")[0],gn=(oe=(Z=ve.getAttribute("profiles"))==null?void 0:Z.split(","))!=null?oe:[],Sn=(C=ve.getAttribute("lang"))!=null?C:void 0,vn=(re=(K=(k=ve.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:K.trim())!=null?re:void 0,yn=ve.querySelectorAll("Representation"),Tn=ve.querySelector("SegmentTemplate"),In=(W=(ue=ve.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?W:void 0,jt=Mr,ce={id:bn,language:Sn,isDefault:In==="main",label:vn,codecs:Lr,hdr:jt==="video"&&ra(Lr),mime:Yt,representations:[]};for(let le of yn){let En=(Oe=le.getAttribute("lang"))!=null?Oe:void 0,xn=(ht=le.getAttribute("label"))!=null?ht:void 0,An=(Se=(ee=(at=le.querySelector("BaseURL"))==null?void 0:at.textContent)==null?void 0:ee.trim())!=null?Se:"",Rr=new URL(An||o,e).toString(),Dt=(we=le.getAttribute("mimeType"))!=null?we:Yt,Yi=(st=(Me=le.getAttribute("codecs"))!=null?Me:Lr)!=null?st:"",Dr;if(Mr==="text"){let ft=le.getAttribute("id")||"",Cr=ft.includes("_auto");Dr={id:ft,isAuto:Cr,kind:"text",url:Rr}}else{let ft=(nt=(Mt=le.getAttribute("contentType"))!=null?Mt:Dt==null?void 0:Dt.split("/")[0])!=null?nt:Mr,Cr=(Rt=(mt=ve.getAttribute("profiles"))==null?void 0:mt.split(","))!=null?Rt:[],kn=parseInt((Qt=le.getAttribute("width"))!=null?Qt:"",10),_a=parseInt((Sa=le.getAttribute("height"))!=null?Sa:"",10),Na=parseInt((va=le.getAttribute("bandwidth"))!=null?va:"",10)/1e3,Fa=(ya=le.getAttribute("frameRate"))!=null?ya:"",Pn=(Ta=le.getAttribute("quality"))!=null?Ta:void 0,wn=Fa?Ns(Fa):void 0,$n=(Ia=le.getAttribute("id"))!=null?Ia:"id"+(x++).toString(10),Ln=ft==="video"?`${_a}p`:ft==="audio"?`${Na}Kbps`:Yi,Mn=`${$n}@${Ln}`,Rn=[...O,...gn,...Cr],Vr,Dn=le.querySelector("SegmentBase"),bt=(Ea=le.querySelector("SegmentTemplate"))!=null?Ea:Tn;if(Dn){let gt=(Aa=(xa=le.querySelector("SegmentBase Initialization"))==null?void 0:xa.getAttribute("range"))!=null?Aa:"",[St,Or]=gt.split("-").map(Ct=>parseInt(Ct,10)),ot={from:St,to:Or},qt=(ka=le.querySelector("SegmentBase"))==null?void 0:ka.getAttribute("indexRange"),[_r,ji]=qt?qt.split("-").map(Ct=>parseInt(Ct,10)):[],zt=qt?{from:_r,to:ji}:void 0;Vr={type:"byteRange",url:Rr,initRange:ot,indexRange:zt}}else if(bt){let gt={representationId:(Pa=le.getAttribute("id"))!=null?Pa:void 0,bandwidth:(wa=le.getAttribute("bandwidth"))!=null?wa:void 0},St=parseInt(($a=bt.getAttribute("timescale"))!=null?$a:"",10),Or=(La=bt.getAttribute("initialization"))!=null?La:"",ot=bt.getAttribute("media"),qt=(Ra=parseInt((Ma=bt.getAttribute("startNumber"))!=null?Ma:"",10))!=null?Ra:1,_r=At(Or,gt);if(!ot)throw new ReferenceError("No media attribute in SegmentTemplate");let ji=(Da=bt.querySelectorAll("SegmentTimeline S"))!=null?Da:[],zt=[],Ct=0,Nr="",Fr=0;if(ji.length){let qi=qt,_e=0;for(let Vt of ji){let Ue=parseInt((Ca=Vt.getAttribute("d"))!=null?Ca:"",10),vt=parseInt((Va=Vt.getAttribute("r"))!=null?Va:"",10)||0,zi=parseInt((Ba=Vt.getAttribute("t"))!=null?Ba:"",10);_e=Number.isFinite(zi)?zi:_e;let Ur=Ue/St*1e3,Hr=_e/St*1e3;for(let Ki=0;Ki<vt+1;Ki++){let Vn=At(ot,J(V({},gt),{segmentNumber:qi.toString(10),segmentTime:(_e+Ki*Ue).toString(10)})),Ua=(Hr!=null?Hr:0)+Ki*Ur,Bn=Ua+Ur;qi++,zt.push({time:{from:Ua,to:Bn},url:Vn})}_e+=(vt+1)*Ue,Ct+=(vt+1)*Ur}Fr=_e/St*1e3,Nr=At(ot,J(V({},gt),{segmentNumber:qi.toString(10),segmentTime:_e.toString(10)}))}else if((0,Ht.isNonNullable)(p)){let _e=parseInt((Oa=bt.getAttribute("duration"))!=null?Oa:"",10)/St*1e3,Vt=Math.ceil(p/_e),Ue=0;for(let vt=1;vt<Vt;vt++){let zi=At(ot,J(V({},gt),{segmentNumber:vt.toString(10),segmentTime:Ue.toString(10)}));zt.push({time:{from:Ue,to:Ue+_e},url:zi}),Ue+=_e}Fr=Ue,Nr=At(ot,J(V({},gt),{segmentNumber:Vt.toString(10),segmentTime:Ue.toString(10)}))}let Cn={time:{from:Fr,to:1/0},url:Nr};Vr={type:"template",baseUrl:Rr,segmentTemplateUrl:ot,initUrl:_r,totalSegmentsDurationMs:Ct,segments:zt,nextSegmentBeyondManifest:Cn,timescale:St}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ft||!Dt)continue;let Br={video:"video",audio:"audio",text:"text"}[ft];if(!Br)continue;jt||(jt=Br),Dr={id:Mn,kind:Br,segmentReference:Vr,profiles:Rn,duration:p,bitrate:Na,mime:Dt,codecs:Yi,width:kn,height:_a,fps:wn,quality:Pn}}ce.language||(ce.language=En),ce.label||(ce.label=xn),ce.mime||(ce.mime=Dt),ce.codecs||(ce.codecs=Yi),ce.hdr||(ce.hdr=jt==="video"&&ra(Yi)),ce.representations.push(Dr)}jt&&r[jt].push(ce)}return{dynamic:d,liveAvailabilityStartTime:c,duration:p,streams:r}};var Gs=require("@vkontakte/videoplayer-shared"),Ws=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var o;let s=(o=a?lt(a):void 0)!=null?o:(0,Gs.videoSizeToQuality)({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},Qs=({id:n,bitrate:e})=>({id:n,bitrate:e}),mr=(n,e,t)=>{var r;let i=e.indexOf(n);return(r=t.at(Math.round(t.length*i/e.length)))!=null?r:t.at(-1)},Ys=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),ua=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),da=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),fr=n=>"url"in n,kt=n=>n.type==="template",Pi=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var wi=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:d}){this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.destroyAbortController=new AbortController;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,I.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){let t=this.representations.get(e);(0,I.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 Ms(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>this.error$.next({id:"SegmentEjection",category:I.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:s}))),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,sa(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=Xe(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,d<l)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,I.assertNonNullable)(i,"No init buffer for starting representation"),(0,I.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(a))})}.bind(this));this.switchTo=(0,I.abortable)(this.destroyAbortController.signal,function(e,t=!1){return pe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,I.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if((0,I.isNullable)(a)||(0,I.isNullable)(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),(0,I.assertNonNullable)(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();(0,I.isNonNullable)(s)&&(this.isLive||(r.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,I.abortable)(this.destroyAbortController.signal,function(e){return pe(this,null,function*(){var u,d;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let c=t.find(f=>f.id===l);c&&this.representations.set(l,c);let p=this.representations.get(l);if(!p||!kt(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(d=this.switchingToRepresentationId)!=null?d:this.downloadingRepresentationId,r=this.representations.get(i);(0,I.assertNonNullable)(r);let a=this.segments.get(i);(0,I.assertNonNullable)(a,"No segments for starting representation");let s=this.initData.get(i);if((0,I.assertNonNullable)(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!(d!=null&&d.dynamic),this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),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 AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var d,l;if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||!(0,I.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((d=r==null?void 0:r.time.to)!=null?d:0)-((l=r==null?void 0:r.time.from)!=null?l:0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Xe(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(a=h)}if(isFinite(this.bufferLimit)&&sa(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Xe(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))c="high";else{let p=o.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Xe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=i.at(-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;(0,I.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,s;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?i:[];for(let o of t){if(!o||!kt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>J(V({},p),{status:"none",size:void 0})),d=(r=this.segments.get(o.id))!=null?r:[],l=(s=(a=d.at(-1))==null?void 0:a.time.to)!=null?s:0,c=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(c+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!kt(r))return;let a=(t=this.segments.get(i.id))!=null?t:[],s=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),d=At(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}}findSegmentStartTime(e){var a,s,o;let t=(s=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?s:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.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(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}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){let 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){let r=e.findIndex(({status:c,time:{from:p,to:h}},f)=>{let b=p<=i&&h>=i,y=p>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),O=this.preloadOnly&&p<=i+x||h<=i+x;return(c==="none"||c==="partially_ejected"&&y&&O&&this.sourceBuffer&&!ni(this.sourceBuffer.buffered,i))&&y&&O});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=d||o<=l);c++){let p=a[c];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,i="auto"){return R(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return R(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,I.abortable)(o,function(){return pe(this,null,function*(){let l=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;let c=new DataView(l);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=Ut(t.mime);r.segment.time.to=h.getSegmentEndTime(c,p)}u&&r.feedingBytes&&d?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Pi(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,i="auto"){return R(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(yield(0,I.abortable)(s,function(){return pe(this,null,function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Pi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(kt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!kt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!a.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(s){return R(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Ut(o.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(d.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,d=e.byteLength;for(let l of this.activeSegments){let{segment:c}=l,p=u==="byteRange",h=p?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!p||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let b=p?c.byte.from-i:0,y=p?c.byte.to-i:e.byteLength,x=b<r,O=y<=r;if(c.status==="downloading"&&x&&O){c.status="downloaded";let E=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(E,a).then(v=>v&&!a.aborted?this.onSegmentFullyAppended(l,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&x&&(l.loadedBytes=Math.min(h,r-b),l.loadedBytes>l.feedingBytes)){let E=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===h?E:Ut(o.mime).parseFeedableSegmentChunk(E);v!=null&&v.byteLength&&(c.status="partially_fed",l.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,a).then(T=>{if(a.aborted)s();else if(T)l.fedBytes+=v.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;s()}}))}}}onSomeByteRangesDataLoadedNew(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let d of this.activeSegments){let{segment:l}=d;if(d.representationId!==t)continue;if(a.aborted){s();continue}let c=l.byte.from-i,p=l.byte.to-i,h=p-c+1,f=c<r,b=p<=r;if(f){if(l.status==="downloading"&&b){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+c,h);(yield this.sourceBufferTaskQueue.append(y,a))&&!a.aborted?this.onSegmentFullyAppended(d,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(d.loadedBytes=Math.min(h,r-c),d.loadedBytes>d.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+c+d.feedingBytes,d.loadedBytes-d.feedingBytes),x=d.loadedBytes===h?y:Ut(u.mime).parseFeedableSegmentChunk(y);x!=null&&x.byteLength&&(l.status="partially_fed",d.feedingBytes+=x.byteLength,(yield this.sourceBufferTaskQueue.append(x,a))&&!a.aborted?(d.fedBytes+=x.byteLength,d.fedBytes===h&&this.onSegmentFullyAppended(d,t)):s())}}}})}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",fr(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),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 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(let[r,a]of this.initData.entries()){let s=a instanceof Promise;t||(t=s),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return R(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?(0,I.abortable)(this.destroyAbortController.signal,function(){return pe(this,null,function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ut(e.mime),r)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let p=l;this.isLive&&kt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:I.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return R(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)})}pruneBufferNew(e,t,i=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((l,c)=>l.from-c.from);let d=[u[0]];for(let l=1;l<u.length;l++){let{from:c,to:p}=u[l],h=d[d.length-1];h.to>=c?h.to=Math.max(h.to,p):d.push(u[l])}return d},o=u=>{var l;if(a>=t)return r;r.push(u.time),r=s(r);let d=fr(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&d.status==="fed"&&o(d)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:d,to:l},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+u&&l.status==="fed"&&o(l)}return r.length?(yield Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||l,!1):!1})}pruneBufferOld(e,t,i=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,u=d=>{var c;a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let l=fr(d)?(c=d.size)!=null?c:0:d.byte.to-d.byte.from;r+=l};for(let d of this.segments.values())for(let l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(a)&&isFinite(s),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)){a=l,s=c;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>e+d&&c.status==="fed"&&u(c)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!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 i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||(0,I.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=1;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=s&&l.to+t>=o),d=e.filter(l=>s>=l.from-t&&s<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var $i=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var js=n=>{var a;let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};var ae=require("@vkontakte/videoplayer-shared");var br=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new ae.ValueSubject(void 0);this.lastConnectionReused$=new ae.ValueSubject(void 0);this.lastRequestFirstBytes$=new ae.ValueSubject(void 0);this.abortAllController=new AbortController;this.subscription=new ae.Subscription;this.fetchManifest=(0,ae.abortable)(this.abortAllController.signal,function(e){return pe(this,null,function*(){let t=e;this.requestQuic&&(t=$i(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(Li);return i?(this.onHeadersReceived(i.headers),i.text()):null})}.bind(this));this.fetch=(0,ae.abortable)(this.abortAllController.signal,function(d){return pe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){var j,X;let l=e,c=new Headers;if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${i.from}-${i.to}`),l=_.toString();break}default:(0,ae.assertNever)(t)}this.requestQuic&&(l=$i(l));let p=this.abortAllController.signal,h;if(s){let _=new AbortController;if(h=(0,ae.merge)((0,ae.fromEvent)(this.abortAllController.signal,"abort"),(0,ae.fromEvent)(s,"abort")).subscribe(()=>{try{_.abort()}catch(L){Li(L)}}),this.abortAllController.signal.aborted||s.aborted)try{_.abort()}catch(L){Li(L)}p=_.signal}let f=(0,ae.now)(),b=yield fetch(l,{priority:a,headers:c,signal:p}).catch(Li),y=(0,ae.now)();if(!b)return h==null||h.unsubscribe(),null;if((j=this.throughputEstimator)==null||j.addRawRtt(y-f),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!r&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[x,O]=b.body.tee(),E=x.getReader();o&&((X=this.throughputEstimator)==null||X.trackStream(O,u));let v=0,T=new Uint8Array(0),z=!1,Y=_=>{h==null||h.unsubscribe(),z=!0,Li(_)},U=(0,ae.abortable)(p,function(Z){return pe(this,arguments,function*({done:_,value:L}){if(v===0&&this.lastRequestFirstBytes$.next((0,ae.now)()-f),p.aborted){h==null||h.unsubscribe();return}if(!_&&L){let oe=new Uint8Array(T.length+L.length);oe.set(T),oe.set(L,T.length),T=oe,v+=L.byteLength,r==null||r(new DataView(T.buffer),v),yield E==null?void 0:E.read().then(U,Y)}})}.bind(this));return yield E==null?void 0:E.read().then(U,Y),h==null||h.unsubscribe(),z?null:T.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,ae.abortable)(this.abortAllController.signal,function(e,t,i){return pe(this,null,function*(){var x;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(l,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(x=e.indexRange)!=null?x:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-s,f.to-f.from+1);else{let O=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!O)return null;b=new DataView(O)}let y=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:y}})}.bind(this));this.fetchTemplateRepresentation=(0,ae.abortable)(this.abortAllController.signal,function(e,t){return pe(this,null,function*(){if(e.type!=="template")return null;let 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(s=>J(V({},s),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){let{type:t,reused:i}=js(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return R(this,null,function*(){var a,s;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(s=yield this.fetchTemplateRepresentation(e,i))!=null?s:null;default:(0,ae.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Li=n=>{if(!Pi(n))throw n};var Pt=(n,e,t)=>t*e+(1-t)*n,la=(n,e)=>n.reduce((t,i)=>t+i,0)/e,qs=(n,e,t,i)=>{let r=0,a=t,s=la(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};var Mi=require("@vkontakte/videoplayer-shared");var pt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mi.ValueSubject(e.initial),this.debounced$=new Mi.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ge(`raw_${t}`),this.smoothedSeries$=new ge(`smoothed_${t}`),this.reportedSeries$=new ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=He(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=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>a||this.smoothed<s)&&((0,Mi.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 gr=class extends pt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Pt(this.slow,t,this.params.emaAlphaSlow),this.fast=Pt(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var Sr=class extends pt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=la(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Pt(this.emaSmoothed,t,this.params.emaAlpha);let r=qs(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var vr=class extends pt{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?Pt(this.smoothed,t,this.params.emaAlpha):t}};var wt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new gr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Sr({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 vr(V({initial:e,label:"liveEdgeDelay"},t))}};var ca=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var Ks=["timeupdate","progress","play","seeked","stalled","waiting"];var yr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new g.Subscription;this.representationSubscription=new g.Subscription;this.state$=new H("none");this.currentVideoRepresentation$=new g.ValueSubject(void 0);this.currentVideoRepresentationInit$=new g.ValueSubject(void 0);this.currentAudioRepresentation$=new g.ValueSubject(void 0);this.currentVideoSegmentLength$=new g.ValueSubject(0);this.currentAudioSegmentLength$=new g.ValueSubject(0);this.error$=new g.Subject;this.lastConnectionType$=new g.ValueSubject(void 0);this.lastConnectionReused$=new g.ValueSubject(void 0);this.lastRequestFirstBytes$=new g.ValueSubject(void 0);this.isLive$=new g.ValueSubject(!1);this.liveDuration$=new g.ValueSubject(0);this.liveAvailabilityStartTime$=new g.ValueSubject(void 0);this.bufferLength$=new g.ValueSubject(0);this.liveLoadBufferLength$=new g.ValueSubject(0);this.livePositionFromPlayer$=new g.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new g.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new g.Subject;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=(0,g.abortable)(this.destroyController.signal,function(e,t,i){return pe(this,null,function*(){var r;this.element=e,this.manifestUrlString=fe(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:g.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,g.abortable)(this.destroyController.signal,function(){return pe(this,null,function*(){var a;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:g.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Hs(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:g.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let i=(s,o,u)=>{var d,l,c,p;return!!((l=(d=this.element)==null?void 0:d.canPlayType)!=null&&l.call(d,o)&&((p=(c=Ze())==null?void 0:c.isTypeSupported)!=null&&p.call(c,`${o}; codecs="${u}"`))||s==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((a=t.duration)!=null?a:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let u=t.streams[s].filter(({mime:c,codecs:p})=>i(s,c,p)),d=new Set(u.map(({codecs:c})=>c)),l=ks(d);if(l&&(r[s]=u.filter(({codecs:c})=>c.startsWith(l))),s==="video"){let c=Ps(),p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);c&&p&&h?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}return J(V({},t),{streams:r})})}.bind(this));this.initRepresentations=(0,g.abortable)(this.destroyController.signal,function(e,t,i){return pe(this,null,function*(){var c;(0,g.assertNonNullable)(this.manifest),(0,g.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,g.fromEvent)(p,"error").pipe((0,g.filter)(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:g.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?us():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&nr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new wi("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],(0,g.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new wi("audio",this.source,p,s),this.bufferManagers.push(this.audioBufferManager)}if(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,g.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=Qr(this.manifestUrlString,2);this.manifestUrlString=fe(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add((0,g.merge)(...Ks.filter(p=>p!=="waiting").map(p=>(0,g.fromEvent)(this.element,p))).pipe((0,g.map)(p=>this.element?Xe(this.element.buffered,this.element.currentTime*1e3):0),(0,g.filterChanged)(),(0,g.filter)(p=>!!p),(0,g.tap)(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,g.filterChanged)()).subscribe(h=>ca(this.element,1))),this.representationSubscription.add((0,g.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,g.filter)(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,g.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,O=h-b,E=1;Math.abs(O)>y&&(E=1+Math.sign(O)*x),ca(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,y;let f=0;if(h){let x=((y=(b=this.element)==null?void 0:b.currentTime)!=null?y:0)*1e3;f=Math.min(...this.bufferManagers.map(E=>{var v,T;return(T=(v=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:v.to)!=null?T:x}))-x}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add((0,g.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,g.throttle)(1e3)).subscribe(b=>R(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if((0,g.assertNonNullable)(this.element),this.isUpdatingLive)return;let y=this.element.playbackRate,x=Qr(this.manifestUrlString,2),O=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(O,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,z=isFinite(h)?h:f,Y=this.isActiveLowLatency$.getValue(),U=O<=this.tuning.live.activeLiveDelay&&x===0;this.isActiveLowLatency$.next(Y&&U);let j="none";if(Y?j="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(X=>X.proceedLowLatencyLive()),j="active_low_latency"):x!==0&&z<E?j="live_forward_buffering":z<E+T&&(j="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),j==="live_forward_buffering"||j==="live_with_target_offset"){let X=p-(E+v),_=this.normolizeLiveOffset(Math.trunc(x+X/y)),L=Math.abs(_-x),Z;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?Z=x:_>0&&L>this.tuning.dashCmafLive.offsetCalculationError?Z=_:Z=0,this.manifestUrlString=fe(this.manifestUrlString,Z,2)}j!=="none"&&j!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=(0,g.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,g.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=(0,g.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,g.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,g.merge)(this.forceEnded$,(0,g.combine)({allBuffersFull:u,someBufferEnded:d}).pipe((0,g.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:g.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,g.merge)(...this.bufferManagers.map(p=>p.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.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(c=this.manifest.duration)!=null?c:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&(0,g.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=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,g.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),r=>{this.error$.next({id:"GapWatchdog",category:g.ErrorCategory.WTF,message:"Error handling gaps",thrown:r})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new br({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=wt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,V({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return R(this,null,function*(){var i,r,a,s;(0,g.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=fe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive((i=this.manifest)==null?void 0:i.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive((a=this.manifest)==null?void 0:a.streams.audio))})}initBuffer(){(0,g.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,g.merge)(...Ks.map(e=>(0,g.fromEvent)(this.element,e)),(0,g.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:g.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,g.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,g.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ni(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var i,r;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let a=this.element.currentTime*1e3;(i=this.videoBufferManager)==null||i.maintain(a),(r=this.audioBufferManager)==null||r.maintain(a)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,g.interval)(1e3).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:g.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return R(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)})}seek(e,t){var r,a,s,o,u;(0,g.assertNonNullable)(this.element),(0,g.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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(s=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?s:e),ni(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3}stop(){var e,t,i;(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.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$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,i=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let a of this.bufferManagers)for(let s of a.gaps)a.playingRepresentation$.getValue()===s.representation&&s.from-r<=t&&s.to+r>t&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?i.push(1/0):i.push(s.to));if(i.length){let a=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,a===1/0?this.forceEnded$.next():this.element.currentTime=a/1e3}}};var Tr=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ir=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/He(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);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=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:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?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){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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=V({},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,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){let r=-this.fadeCorrection*He(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 Js=`attribute vec2 a_vertex;
|
|
35
|
+
`});let Q=U&&l&&l.history[U.id]&&(0,Y.now)()-l.history[U.id]<=r.trackCooldown&&(!l.last||U.id!==l.last.id);if(U!=null&&U.id&&l&&!Q&&l.recordSelection(U),Q&&(l!=null&&l.last)){let B=l.last;return l==null||l.recordSwitch(B),d({message:`
|
|
36
|
+
[last selected] ${B==null?void 0:B.quality}
|
|
37
|
+
`}),B}return l==null||l.recordSwitch(U),U},Dt=Nx;var be=i=>new URL(i).hostname;var O=require("@vkontakte/videoplayer-shared");var Uf=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"))},Le=i=>D(void 0,null,function*(){let e=i.muted;try{yield i.play()}catch(t){if(!Uf(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return Uf(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});var Ve=require("@vkontakte/videoplayer-shared");var ut=require("@vkontakte/videoplayer-shared");function ge(){return(0,ut.now)()}function Wo(i){return ge()-i}function Qo(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,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Hf(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function kr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ut.assertNonNullable)(c);let C=Wo(c),ee;if(C<g){ee=g-C,setTimeout(S,ee);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new a,K()},T=C=>(s=C,N),A=C=>(d=C,N),P=()=>(h="json",N),I=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},E=C=>(p=C,N),K=()=>{c=ge(),n=new a,n.open("get",i);let C=0,ee,le=0,B=()=>((0,ut.assertNonNullable)(c),Math.max(c,Math.max(ee||0,le||0)));if(s&&n.addEventListener("progress",k=>{let J=ge();s.updateChunk&&k.loaded>C&&(s.updateChunk(B(),k.loaded-C),C=k.loaded,ee=J)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;(0,ut.assertNonNullable)(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let J=n.response.byteLength-C;J&&s.updateChunk&&s.updateChunk(B(),J)}n.responseType==="json"&&!Object.values(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),p){let k=()=>{(0,ut.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(le=ge(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),N},N={withBitrateReporting:T,withParallel:E,withJSONResponse:P,withRetryCount:C=>(l=C,N),withRetryInterval:(C,ee)=>((0,ut.isNonNullable)(C)&&(g=C),(0,ut.isNonNullable)(ee)&&(m=ee),N),withTimeout:C=>(o=C,N),withFinally:A,send:K,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var bi=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 u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}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 gi=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=ge(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ge()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=kr(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=ge()}_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=ge();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 os=1e4,zo=3;var qx=6e4,Ux=10,Hx=1,jx=500,Si=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 bi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Qo(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=Qo(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",()=>{var a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(a=e.error)==null?void 0:a.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,Ve.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=()=>{Hf(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 gi(zo,os,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,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},p=(I,E,K)=>{u&&u.abort(),u=kr(this.urlResolver.resolve(I,!1),E,K,()=>this._retryCallback()).withTimeout(os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(zo).withFinally(()=>{u=null}).send()},h=(I,E,K)=>{(0,Ve.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,K,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},g=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let K=ge()-1e4,W=0;for(let Q=0;Q<this.bufferStates.length;Q++){let Z=this.bufferStates[Q];I=Math.min(I,Z.buf),Z.ts<K&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${I} drop=${W} jitter=${this.sourceJitter}`);let U=I-Hx;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?m(1.15):U>1?m(1.1):U>.3?m(1.05):m(1)}},T=I=>{let E,K=()=>E&&E.start?E.start.length:0,W=k=>E.start[k]/1e3,U=k=>E.dur[k]/1e3,Q=k=>E.fragIndex+k,Z=(k,J)=>({chunkIdx:Q(k),startTS:W(k),dur:U(k),discontinuity:J}),N=()=>{let k=0;if(E&&E.dur){let J=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ae=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ce=J;this.sourceJitter>1&&(ce+=this.sourceJitter-1);let G=E.dur.length-1;for(;G>=0&&(ce-=E.dur[G],!(ce<=0));--G);k=Math.min(G,E.dur.length-1-ae),k=Math.max(k,0)}return Z(k,!0)},C=k=>{let J=K();if(!(J<=0)){if((0,Ve.isNonNullable)(k)){for(let ae=0;ae<J;ae++)if(W(ae)>k)return Z(ae)}return N()}},ee=k=>{let J=K(),ae=k?k.chunkIdx+1:0,ce=ae-E.fragIndex;if(!(J<=0)){if(!k||ce<0||ce-J>Ux)return t(`Resync: offset=${ce} bChunks=${J} chunk=`+JSON.stringify(k)),N();if(!(ce>=J))return Z(ae-E.fragIndex,!1)}},le=(k,J,ae)=>{l&&l.abort(),l=kr(this.urlResolver.resolve(k,!0,this.lowLatency),J,ae,()=>this._retryCallback()).withTimeout(os).withRetryCount(zo).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,J)=>{le(I,ae=>{if(!d())return;E=ae;let ce=!!E.lowLatency;ce!==this.lowLatency&&g(ce);let G=0;for(let Ye=0;Ye<E.dur.length;++Ye)G+=E.dur[Ye];G>0&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(G/E.dur.length)),a({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,k(C(J))},()=>this._handleNetworkError())},nextChunk:ee}},A=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:K}=this.params,W=T(e.jidxUrl),U,Q,Z,N,C=0,ee,le,B,k=()=>{ee&&(clearTimeout(ee),ee=void 0);let te=Math.max(jx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ie=C+te,De=ge(),Ne=Math.min(1e4,Ie-De);C=De;let wt=()=>{l||d()&&W.seek(()=>{d()&&(C=ge(),J(),k())})};Ne>0?ee=window.setTimeout(()=>{this.paused?k():wt()},Ne):wt()},J=()=>{let te;for(;te=W.nextChunk(N);)N=te,Bt(te);let Ie=W.nextChunk(Z);if(Ie){if(Z&&Ie.discontinuity){K("Detected discontinuity; restarting playback"),this.paused?k():(A(),this._initPlayerWith(e));return}Ye(Ie)}else k()},ae=(te,Ie)=>{if(!d()||!this.sourceBuffer)return;let De,Ne,wt,ur=kt=>{window.setTimeout(()=>{d()&&ae(te,Ie)},kt)};if(this.sourceBuffer.updating)K("Source buffer is updating; delaying appendBuffer"),ur(100);else{let kt=ge(),Vt=E.currentTime;!this.paused&&E.buffered.length>1&&le===Vt&&kt-B>500&&(K("Stall suspected; trying to fix"),this._fixupStall()),le!==Vt&&(le=Vt,B=kt);let lr=this._getBufferSizeSec();if(lr>30)K(`Buffered ${lr} seconds; delaying appendBuffer`),ur(2e3);else try{this.sourceBuffer.appendBuffer(te),this.videoPlayStarted?(this.bufferStates.push({ts:kt,buf:lr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ie&&Ie()}catch(qr){if(qr.name==="QuotaExceededError")K("QuotaExceededError; delaying appendBuffer"),wt=this.sourceBuffer.buffered.length,wt!==0&&(De=this.sourceBuffer.buffered.start(0),Ne=Vt,Ne-De>4&&this.sourceBuffer.remove(De,Ne-3)),ur(1e3);else throw qr}}},ce=()=>{Q&&U&&(K([`Appending chunk, sz=${Q.byteLength}:`,JSON.stringify(Z)]),ae(Q,function(){Q=null,J()}))},G=te=>e.fragUrlTemplate.replace("%%id%%",te.chunkIdx),Ye=te=>{d()&&h(G(te),(Ie,De)=>{if(d()){if(De/=1e3,Q=Ie,Z=te,n=te.startTS,De){let Ne=Math.min(10,te.dur/De);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ne:Ne}ce()}},()=>this._handleNetworkError())},Bt=te=>{d()&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(G(te),!1)))},At=te=>{d()&&(e.cachedHeader=te,ae(te,()=>{U=!0,ce()}))};s=!0,W.seek(te=>{if(d()){if(C=ge(),!te){k();return}N=te,!(0,Ve.isNullable)(I)||te.startTS>I?Ye(te):(Z=te,J())}},I),e.cachedHeader?At(e.cachedHeader):p(e.headerUrl,At,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),(0,Ve.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,Ve.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ve.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,h)=>{let m=ge();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Wo(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ge();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=kr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(os).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;Le(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!=null&&n.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.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))},qx))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ue=require("@vkontakte/videoplayer-shared"),Ko=class{constructor(){this.onDroopedVideoFramesLimit$=new ue.Subject;this.subscription=new ue.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ue.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ue.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;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,ue.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n: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.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ue.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ue.interval)(this.droppedFramesChecker.checkTime).pipe((0,ue.filter)(()=>this.playing),(0,ue.filter)(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe((0,ue.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ue.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){var r,a;let t=(a=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ue.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:a[0];return e!=null?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}},us=Ko;var ls=require("@vkontakte/videoplayer-shared"),jf=require("@vkontakte/videoplayer-shared");var vi=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var Gx=(i,e)=>new ls.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||vi()))},V(V({},r),e));a.observe(i);let s=(0,jf.fromEvent)(document,"visibilitychange").pipe((0,ls.map)(n=>!document.hidden||vi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),He=Gx;var Yx=["paused","playing","ready"],Wx=["paused","playing","ready"],yi=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new H("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new Ue;this.droppedFramesManager=new us;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new mt;this._dashCb=e=>{var t,r,a,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Mt(u.name))!=null?r:(0,O.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=V({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((a=this.videoState.getTransition())==null?void 0:a.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);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(Wx.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&Yx.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ve(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 u=a==null?void 0:a.from;u&&u==="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 u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ve(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=Ae(e.container,e.tuning),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(be(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=Re(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(a=>a.map(({track:s})=>s)),(0,O.filter)(a=>!!a.length),(0,O.once)()).subscribe(a=>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:a}))),this.subscription.add(r.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())==null?void 0:a.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,O.filterChanged)(),(0,O.map)(a=>-a/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(ke(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(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(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&(0,O.videoQualityToHeight)(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var s;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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.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,O.assertNever)(a.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.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),we(this.video)}createLiveDashPlayer(){let e=new Si({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(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&(0,O.isNonNullable)(t)?t:Dt(e.map(({track:g})=>g),{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==null?void 0:a.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;(0,O.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(ve(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Gf=yi;var St=(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 M=require("@vkontakte/videoplayer-shared");var cs=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}},Rr=class extends cs{constructor(){super(),this.listeners||cs.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)}},Ti=class{constructor(){Object.defineProperty(this,"signal",{value:new Rr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?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=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(a){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ti.prototype[Symbol.toStringTag]="AbortController",Rr.prototype[Symbol.toStringTag]="AbortSignal");function ds(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 Jo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!ds({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(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ii=ds({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Yf=Ii?Jo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,vt=Ii?Yf.fetch:window.fetch,P$=Ii?Yf.Request:window.Request,yt=Ii?Ti:window.AbortController,A$=Ii?Rr:window.AbortSignal;var sm=Qe(fi(),1);var Tt=()=>window.ManagedMediaSource||window.MediaSource,ps=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Wf=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Qf=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Me=require("@vkontakte/videoplayer-shared");var nm=(0,Me.isAndroid)(),je=document.createElement("video"),Kx='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Jx='video/mp4; codecs="hev1.1.6.L93.B0"',om='video/webm; codecs="vp09.00.10.08"',um='video/webm; codecs="av01.0.00M.08"',Xx='audio/mp4; codecs="mp4a.40.2"',Zx='audio/webm; codecs="opus"',zf,Kf,Jt={mms:ps(),mse:Wf(),hls:!!((zf=je.canPlayType)!=null&&zf.call(je,"application/x-mpegurl")||(Kf=je.canPlayType)!=null&&Kf.call(je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Jf,Xf,$e={mp4:!!((Jf=je.canPlayType)!=null&&Jf.call(je,"video/mp4")),webm:!!((Xf=je.canPlayType)!=null&&Xf.call(je,"video/webm")),cmaf:!0},fs,Zf,ms,em,bs,tm,gs,rm,Ss,im,vs,am,Ce={h264:!!((Zf=(fs=Tt())==null?void 0:fs.isTypeSupported)!=null&&Zf.call(fs,Kx)),h265:!!((em=(ms=Tt())==null?void 0:ms.isTypeSupported)!=null&&em.call(ms,Jx)),vp9:!!((tm=(bs=Tt())==null?void 0:bs.isTypeSupported)!=null&&tm.call(bs,om)),av1:!!((rm=(gs=Tt())==null?void 0:gs.isTypeSupported)!=null&&rm.call(gs,um)),aac:!!((im=(Ss=Tt())==null?void 0:Ss.isTypeSupported)!=null&&im.call(Ss,Xx)),opus:!!((am=(vs=Tt())==null?void 0:vs.isTypeSupported)!=null&&am.call(vs,Zx))},Lr=(Ce.h264||Ce.h265)&&Ce.aac,Xt,eP=()=>D(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(X(V({},i),{video:X(V({},i.video),{contentType:um})})),window.navigator.mediaCapabilities.decodingInfo(X(V({},i),{video:X(V({},i.video),{contentType:om})}))]);Xt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{eP()}catch(i){console.error(i)}var $r=Jt.hls&&$e.mp4,lm=()=>Object.keys(Ce).filter(i=>Ce[i]),cm=(i,e=!1,t=!1)=>{let r=Jt.mse||Jt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&$e.mp4&&Lr;case"DASH_WEBM":return r&&$e.webm&&Ce.vp9&&Ce.opus;case"DASH_WEBM_AV1":return r&&$e.webm&&Ce.av1&&Ce.opus;case"DASH_STREAMS":return r&&($e.mp4&&Lr||$e.webm&&(Ce.vp9||Ce.av1)&&(Ce.opus||Ce.aac));case"DASH_LIVE":return Jt.mse&&$e.mp4&&Lr;case"DASH_LIVE_CMAF":return r&&$e.mp4&&Lr&&$e.cmaf;case"DASH_ONDEMAND":return r&&$e.mp4&&Lr;case"HLS":case"HLS_ONDEMAND":return $r||e&&Jt.mse&&$e.mp4&&Lr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return $r;case"MPEG":return $e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Jt.webrtc&&Jt.ws&&Ce.h264&&($e.mp4||$e.webm);default:return(0,Me.assertNever)(a)}})},hs=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 Xt?Xt[t].smooth?[t,e]:Xt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Xt?Xt[t].powerEfficient?[t,e]:Xt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Me.assertNever)(i)}return[e,t]},dm=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...hs(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(nm)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...hs(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...hs(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...hs(i),...a,"HLS","HLS_ONDEMAND"];default:(0,Me.assertNever)(e)}return $r?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},pm=({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,u=(0,Me.getCurrentBrowser)().device===Me.CurrentClientDevice.Mac&&(0,Me.getCurrentBrowser)().browser===Me.CurrentClientBrowser.Safari;if(nm)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,Me.assertNever)(i)}else $r&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Xo=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],hm=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,sm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};var Cr=require("@vkontakte/videoplayer-shared"),fm=i=>{if(!i)return{id:"EmptyResponse",category:Cr.ErrorCategory.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Cr.ErrorCategory.NETWORK,message:`UV Error ${i}`};let e=i.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Cr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Cr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Cr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};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 mm=()=>window.matchMedia("(dynamic-range: high)").matches,Zo=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var v=require("@vkontakte/videoplayer-shared");var _r=Qe(fi(),1);var tP=(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)},rP=i=>window.clearTimeout(i),bm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",eu=bm?tP:window.requestIdleCallback,F$=bm?rP:window.cancelIdleCallback;var nb=Qe(is(),1);var Ge=require("@vkontakte/videoplayer-shared");var iP=16,vm=!1,gm,Sm;try{vm=(0,Ge.getCurrentBrowser)().browser===Ge.CurrentClientBrowser.Safari&&parseInt((Sm=(gm=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:gm[1])!=null?Sm:"",10)<=iP}catch(i){console.error(i)}var tu=class{constructor(e){this.bufferFull$=new Ge.Subject;this.error$=new Ge.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ge.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return D(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})})}remove(e,t,r){return D(this,null,function*(){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()})})}abort(e){return D(this,null,function*(){return new Promise(t=>{let r;vm&&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(){var a;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((a=e.signal)!=null&&a.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ge.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){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,Ge.assertNever)(t)}}},ym=tu;var ru=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 re=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 Mr=class extends re{};var xi=class extends re{};var Pi=class extends re{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 Ai=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends re{constructor(t,r){super(t,r);this.data=this.content}};var de=class extends re{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Zt=class extends de{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,u=this.readUint32();s=this.readUint32();let l=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:u,SAPType:l,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var Ri=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends de{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 Ci=class extends de{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Mi=class extends de{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 re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Oi=class extends de{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 Bi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends de{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var Ni=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends de{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 qi=class extends de{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 Ui=class extends de{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 sP={ftyp:Pi,moov:Ai,moof:wi,mdat:ki,sidx:Zt,trak:Ri,mdia:Di,mfhd:_i,tkhd:Oi,traf:Ni,tfhd:Fi,tfdt:qi,trun:Ui,minf:Bi,sv3d:Li,st3d:$i,prhd:Ci,proj:Vi,equi:Mi,uuid:xi,unknown:Mr},er=class i{constructor(e={}){this.options=V({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(a){break}return t}createBox(e,t){let r=sP[e];return r?new r(t,new i):new Mr(t,new i)}};var Dr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,a,s;(s=(r=this.index)[a=t.type])!=null||(r[a]=[]),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 oP=new TextDecoder("ascii"),uP=i=>oP.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",lP=i=>{let e=new Zt(i,new er),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})},cP=(i,e)=>{let r=new er().parse(i),a=new Dr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},dP=(i,e)=>{let r=new er().parse(i),s=new Dr(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"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},pP=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 er().parse(i),a=new Dr(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 u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Tm={validateData:uP,parseInit:pP,getIndexRange:()=>{},parseSegments:lP,parseFeedableSegmentChunk:cP,getSegmentEndTime:dP};var It=require("@vkontakte/videoplayer-shared");var Em=require("@vkontakte/videoplayer-shared");var Im={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"}},xm=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=Hi(i,t),a=r in Im,s=a?Im[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 u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=Hi(u),d=l*it(2,(o-1)*8)+c,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Hi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*it(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*it(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*it(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},et=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Hi(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,Em.assertNever)(e)}},tr=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=xm(r);if(!e(a))return;a.type==="master"&&tr(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Pm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=xm(i);return tr(a.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Am=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],hP=[231,22612,22743,167,171,163,160,175],fP=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return tr(i,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=et(m,h);l=Hi(S)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(m,h):p===17545?a=et(m,h):p===21420&&l===475249515?u=et(m,h):p===374648427?tr(m,({tag:S,type:T,value:A})=>S===30321?(c=et(A,T)===1,!1):!0):s&&n&&Am.includes(p)&&(o=!0),!o}),(0,It.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,It.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,It.assertNonNullable)(a,"Failed to parse webm Segment duration"),r=r!=null?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:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},mP=i=>{if((0,It.isNullable)(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},bP=(i,e)=>{let t=!1,r=!1,a=o=>(0,It.isNonNullable)(o.time)&&(0,It.isNonNullable)(o.position),s=[],n;return tr(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&Am.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},gP=i=>{let e=0,t=!1;try{tr(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):hP.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},wm={validateData:Pm,parseInit:fP,getIndexRange:mP,parseSegments:bP,parseFeedableSegmentChunk:gP};var Or=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return wm;case"mp4":return Tm}}throw new ReferenceError(`Unsupported mime type ${i}`)};var uu=Qe(Jm(),1);var Vr=require("@vkontakte/videoplayer-shared");var Xm=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Zm=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*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==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],a),hours:e(r==null?void 0:r[6],a),minutes:e(r==null?void 0:r[7],a),seconds:e(r==null?void 0:r[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},rr=(i,e)=>{let t=i;t=(0,uu.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,uu.default)(t,n,(o,u)=>(0,Vr.isNullable)(s)?o:(0,Vr.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},tb=(i,e)=>{var I,E,K,W,U,Q,Z,N,C,ee,le,B,k,J,ae,ce,G,Ye,Bt,At,te,Ie,De,Ne,wt,ur,kt,Vt,lr,qr,Tu,Iu,Eu,xu,Pu,Au,wu,ku,Ru,Lu,$u,Cu,Mu,Du,Ou,Bu,Vu,_u,Nu,Fu;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(K=(E=(I=s.querySelector("BaseURL"))==null?void 0:I.textContent)==null?void 0:E.trim())!=null?K:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Zm(h);else if(m){let Ee=Zm(m);(0,Vr.isNonNullable)(Ee)&&(p=Ee)}else S&&(p=parseInt(S,10));let T=0,A=(U=(W=s.getAttribute("profiles"))==null?void 0:W.split(","))!=null?U:[];for(let Ee of u){let $b=(Q=Ee.getAttribute("id"))!=null?Q:"id"+(T++).toString(10),Ur=(Z=Ee.getAttribute("mimeType"))!=null?Z:"",Bs=(N=Ee.getAttribute("codecs"))!=null?N:"",Vs=(C=Ee.getAttribute("contentType"))!=null?C:Ur==null?void 0:Ur.split("/")[0],Cb=(le=(ee=Ee.getAttribute("profiles"))==null?void 0:ee.split(","))!=null?le:[],Mb=(B=Ee.getAttribute("lang"))!=null?B:void 0,Db=(ae=(J=(k=Ee.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:J.trim())!=null?ae:void 0,Ob=Ee.querySelectorAll("Representation"),Bb=Ee.querySelector("SegmentTemplate"),Vb=(G=(ce=Ee.querySelector("Role"))==null?void 0:ce.getAttribute("value"))!=null?G:void 0,Hr=Vs,he={id:$b,language:Mb,isDefault:Vb==="main",label:Db,codecs:Bs,hdr:Hr==="video"&&Zo(Bs),mime:Ur,representations:[]};for(let pe of Ob){let _b=(Ye=pe.getAttribute("lang"))!=null?Ye:void 0,Nb=(Bt=pe.getAttribute("label"))!=null?Bt:void 0,Fb=(Ie=(te=(At=pe.querySelector("BaseURL"))==null?void 0:At.textContent)==null?void 0:te.trim())!=null?Ie:"",_s=new URL(Fb||o,e).toString(),cr=(De=pe.getAttribute("mimeType"))!=null?De:Ur,ca=(wt=(Ne=pe.getAttribute("codecs"))!=null?Ne:Bs)!=null?wt:"",Ns;if(Vs==="text"){let _t=pe.getAttribute("id")||"",Fs=_t.includes("_auto");Ns={id:_t,isAuto:Fs,kind:"text",url:_s}}else{let _t=(kt=(ur=pe.getAttribute("contentType"))!=null?ur:cr==null?void 0:cr.split("/")[0])!=null?kt:Vs,Fs=(lr=(Vt=Ee.getAttribute("profiles"))==null?void 0:Vt.split(","))!=null?lr:[],qb=parseInt((qr=pe.getAttribute("width"))!=null?qr:"",10),qu=parseInt((Tu=pe.getAttribute("height"))!=null?Tu:"",10),Uu=parseInt((Iu=pe.getAttribute("bandwidth"))!=null?Iu:"",10)/1e3,Hu=(Eu=pe.getAttribute("frameRate"))!=null?Eu:"",Ub=(xu=pe.getAttribute("quality"))!=null?xu:void 0,Hb=Hu?Xm(Hu):void 0,jb=(Pu=pe.getAttribute("id"))!=null?Pu:"id"+(T++).toString(10),Gb=_t==="video"?`${qu}p`:_t==="audio"?`${Uu}Kbps`:ca,Yb=`${jb}@${Gb}`,Wb=[...A,...Cb,...Fs],qs,Qb=pe.querySelector("SegmentBase"),Nt=(Au=pe.querySelector("SegmentTemplate"))!=null?Au:Bb;if(Qb){let Ft=(ku=(wu=pe.querySelector("SegmentBase Initialization"))==null?void 0:wu.getAttribute("range"))!=null?ku:"",[qt,Hs]=Ft.split("-").map(dr=>parseInt(dr,10)),Rt={from:qt,to:Hs},jr=(Ru=pe.querySelector("SegmentBase"))==null?void 0:Ru.getAttribute("indexRange"),[js,da]=jr?jr.split("-").map(dr=>parseInt(dr,10)):[],Gr=jr?{from:js,to:da}:void 0;qs={type:"byteRange",url:_s,initRange:Rt,indexRange:Gr}}else if(Nt){let Ft={representationId:(Lu=pe.getAttribute("id"))!=null?Lu:void 0,bandwidth:($u=pe.getAttribute("bandwidth"))!=null?$u:void 0},qt=parseInt((Cu=Nt.getAttribute("timescale"))!=null?Cu:"",10),Hs=(Mu=Nt.getAttribute("initialization"))!=null?Mu:"",Rt=Nt.getAttribute("media"),jr=(Ou=parseInt((Du=Nt.getAttribute("startNumber"))!=null?Du:"",10))!=null?Ou:1,js=rr(Hs,Ft);if(!Rt)throw new ReferenceError("No media attribute in SegmentTemplate");let da=(Bu=Nt.querySelectorAll("SegmentTimeline S"))!=null?Bu:[],Gr=[],dr=0,Gs="",Ys=0;if(da.length){let pa=jr,We=0;for(let pr of da){let rt=parseInt((Vu=pr.getAttribute("d"))!=null?Vu:"",10),Ut=parseInt((_u=pr.getAttribute("r"))!=null?_u:"",10)||0,ha=parseInt((Nu=pr.getAttribute("t"))!=null?Nu:"",10);We=Number.isFinite(ha)?ha:We;let Ws=rt/qt*1e3,Qs=We/qt*1e3;for(let fa=0;fa<Ut+1;fa++){let Kb=rr(Rt,X(V({},Ft),{segmentNumber:pa.toString(10),segmentTime:(We+fa*rt).toString(10)})),ju=(Qs!=null?Qs:0)+fa*Ws,Jb=ju+Ws;pa++,Gr.push({time:{from:ju,to:Jb},url:Kb})}We+=(Ut+1)*rt,dr+=(Ut+1)*Ws}Ys=We/qt*1e3,Gs=rr(Rt,X(V({},Ft),{segmentNumber:pa.toString(10),segmentTime:We.toString(10)}))}else if((0,Vr.isNonNullable)(p)){let We=parseInt((Fu=Nt.getAttribute("duration"))!=null?Fu:"",10)/qt*1e3,pr=Math.ceil(p/We),rt=0;for(let Ut=1;Ut<pr;Ut++){let ha=rr(Rt,X(V({},Ft),{segmentNumber:Ut.toString(10),segmentTime:rt.toString(10)}));Gr.push({time:{from:rt,to:rt+We},url:ha}),rt+=We}Ys=rt,Gs=rr(Rt,X(V({},Ft),{segmentNumber:pr.toString(10),segmentTime:rt.toString(10)}))}let zb={time:{from:Ys,to:1/0},url:Gs};qs={type:"template",baseUrl:_s,segmentTemplateUrl:Rt,initUrl:js,totalSegmentsDurationMs:dr,segments:Gr,nextSegmentBeyondManifest:zb,timescale:qt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!_t||!cr)continue;let Us={video:"video",audio:"audio",text:"text"}[_t];if(!Us)continue;Hr||(Hr=Us),Ns={id:Yb,kind:Us,segmentReference:qs,profiles:Wb,duration:p,bitrate:Uu,mime:cr,codecs:ca,width:qb,height:qu,fps:Hb,quality:Ub}}he.language||(he.language=_b),he.label||(he.label=Nb),he.mime||(he.mime=cr),he.codecs||(he.codecs=ca),he.hdr||(he.hdr=Hr==="video"&&Zo(ca)),he.representations.push(Ns)}Hr&&a[Hr].push(he)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:a}};var ji=Qe(fi(),1);var rb=require("@vkontakte/videoplayer-shared"),ib=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?Mt(s):void 0)!=null?o:(0,rb.videoSizeToQuality)({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},ab=({id:i,bitrate:e})=>({id:i,bitrate:e}),ys=(i,e,t)=>{var a;let r=e.indexOf(i);return(a=(0,ji.default)(t,Math.round(t.length*r/e.length)))!=null?a:(0,ji.default)(t,-1)},sb=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),cu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,ji.default)(r.split("."),0),isDefault:a}),du=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,ji.default)(a.split("."),0)}),Ts=i=>"url"in i,ir=i=>i.type==="template",Gi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Yi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){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 yt;this.destroyAbortController=new yt;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,function(e){return fe(this,null,function*(){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 ym(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),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=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,ru(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=St(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,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,function(e,t=!1){return fe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,x.assertNonNullable)(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),(0,x.assertNonNullable)(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,x.isNonNullable)(n)&&(this.isLive||(a.forEach(o=>o.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,function(e){return fe(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!ir(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,a=this.representations.get(r);(0,x.assertNonNullable)(a);let s=this.segments.get(r);(0,x.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,x.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),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 yt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||!(0,x.isNullable)(this.switchingToRepresentationId)||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(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=a==null?void 0:a.time.to)!=null?l:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=St(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&ru(this.sourceBuffer.buffered)>=this.bufferLimit){let d=St(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))d="high";else{let p=(0,_r.default)(o,0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&St(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,_r.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}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==null?void 0:e.streams[this.kind].flatMap(a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,a,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!ir(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>X(V({},p),{status:"none",size:void 0})),l=(a=this.segments.get(o.id))!=null?a:[],c=(n=(s=(0,_r.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,x.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let a=r.segmentReference;if(!ir(a))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*a.timescale/1e3).toString(10),l=rr(a.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let a=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=a==null?void 0:a.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.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(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}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:p,to:h}},m)=>{let g=p<=r&&h>=r,S=p>r||g||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),A=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&S&&A&&this.sourceBuffer&&!Ei(this.sourceBuffer.buffered,r))&&S&&A});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return D(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return D(this,null,function*(){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:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,x.abortable)(o,function(){return fe(this,null,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=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=Or(t.mime);a.segment.time.to=h.getSegmentEndTime(d,p)}u&&a.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Gi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return D(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,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&&(yield(0,x.abortable)(n,function(){return fe(this,null,function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Gi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ir(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,_r.default)(e,0).byte.from,to:(0,_r.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ir(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,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:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return D(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){a();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Or(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({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 u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,T=g<a,A=S<=a;if(d.status==="downloading"&&T&&A){d.status="downloaded";let P=new DataView(e.buffer,e.byteOffset+g,h);this.sourceBufferTaskQueue.append(P,s).then(I=>I&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(h,a-g),c.loadedBytes>c.feedingBytes)){let P=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),I=c.loadedBytes===h?P:Or(o.mime).parseFeedableSegmentChunk(P);I!=null&&I.byteLength&&(d.status="partially_fed",c.feedingBytes+=I.byteLength,this.sourceBufferTaskQueue.append(I,s).then(E=>{if(s.aborted)n();else if(E)c.fedBytes+=I.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return D(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<a,g=p<=a;if(m){if(c.status==="downloading"&&g){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,a-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===h?S:Or(u.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(c.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}}})}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ts(e.segment)&&(e.segment.size=e.fedBytes);for(let a of this.representations.values())if(a.id!==t)for(let s of(r=this.segments.get(a.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),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||(t=n),s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=eu(()=>(0,nb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return D(this,null,function*(){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,function(){return fe(this,null,function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Or(e.mime),a)).then(o=>D(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ir(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).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})}dropBuffer(){return D(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return D(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return D(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return a;a.push(u.time),a=n(a);let l=Ts(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(a.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(yield Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,r=!1){return D(this,null,function*(){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,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=Ts(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;a+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)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 l=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+l&&d.status==="fed"&&u(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=eu(()=>{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),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.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 Wi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var ob=i=>{var s;let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,a=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:a}};var se=require("@vkontakte/videoplayer-shared");var Is=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new se.ValueSubject(void 0);this.lastConnectionReused$=new se.ValueSubject(void 0);this.lastRequestFirstBytes$=new se.ValueSubject(void 0);this.abortAllController=new yt;this.subscription=new se.Subscription;this.fetchManifest=(0,se.abortable)(this.abortAllController.signal,function(e){return fe(this,null,function*(){let t=e;this.requestQuic&&(t=Wi(t));let r=yield vt(t,{signal:this.abortAllController.signal}).catch(Qi);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=(0,se.abortable)(this.abortAllController.signal,function(l){return fe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var Q,Z;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),c=N.toString();break}default:(0,se.assertNever)(t)}this.requestQuic&&(c=Wi(c));let p=this.abortAllController.signal,h;if(n){let N=new yt;if(h=(0,se.merge)((0,se.fromEvent)(this.abortAllController.signal,"abort"),(0,se.fromEvent)(n,"abort")).subscribe(()=>{try{N.abort()}catch(C){Qi(C)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(C){Qi(C)}p=N.signal}let m=(0,se.now)(),g=yield vt(c,{priority:s,headers:d,signal:p}).catch(Qi),S=(0,se.now)();if(!g)return h==null||h.unsubscribe(),null;if((Q=this.throughputEstimator)==null||Q.addRawRtt(S-m),!g.ok||!g.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!a&&!o)return h==null||h.unsubscribe(),g.arrayBuffer();let[T,A]=g.body.tee(),P=T.getReader();o&&((Z=this.throughputEstimator)==null||Z.trackStream(A,u));let I=0,E=new Uint8Array(0),K=!1,W=N=>{h==null||h.unsubscribe(),K=!0,Qi(N)},U=(0,se.abortable)(p,function(ee){return fe(this,arguments,function*({done:N,value:C}){if(I===0&&this.lastRequestFirstBytes$.next((0,se.now)()-m),p.aborted){h==null||h.unsubscribe();return}if(!N&&C){let le=new Uint8Array(E.length+C.length);le.set(E),le.set(C,E.length),E=le,I+=C.byteLength,a==null||a(new DataView(E.buffer),I),yield P==null?void 0:P.read().then(U,W)}})}.bind(this));return yield P==null?void 0:P.read().then(U,W),h==null||h.unsubscribe(),K?null:E.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,se.abortable)(this.abortAllController.signal,function(e,t,r){return fe(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,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 p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(T=e.indexRange)!=null?T:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let A=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!A)return null;g=new DataView(A)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,se.abortable)(this.abortAllController.signal,function(e,t){return fe(this,null,function*(){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=>X(V({},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}=ob(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return D(this,null,function*(){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,se.assertNever)(a)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Qi=i=>{if(!Gi(i))throw i};var ar=(i,e,t)=>t*e+(1-t)*i,pu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,ub=(i,e,t,r)=>{let a=0,s=t,n=pu(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};var zi=require("@vkontakte/videoplayer-shared");var Ot=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new zi.ValueSubject(e.initial),this.debounced$=new zi.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Te(`raw_${t}`),this.smoothedSeries$=new Te(`smoothed_${t}`),this.reportedSeries$=new Te(`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+=it(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,zi.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 Es=class extends Ot{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=ar(this.slow,t,this.params.emaAlphaSlow),this.fast=ar(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var xs=class extends Ot{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=pu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,t,this.params.emaAlpha);let a=ub(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var Ps=class extends Ot{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?ar(this.smoothed,t,this.params.emaAlpha):t}};var sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Es({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new xs({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 Ps(V({initial:e,label:"liveEdgeDelay"},t))}};var hu=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var cb=["timeupdate","progress","play","seeked","stalled","waiting"];var As=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.currentAudioRepresentation$=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$=new v.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new yt;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return fe(this,null,function*(){var a;this.element=e,this.manifestUrlString=ve(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.streams.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,function(){return fe(this,null,function*(){var s,n;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t;try{t=tb(e!=null?e:"",this.manifestUrlString)}catch(o){let u=(s=fm(e))!=null?s:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(u)}if(!t)return null;let r=(o,u,l)=>{var c,d,p,h;return!!((d=(c=this.element)==null?void 0:c.canPlayType)!=null&&d.call(c,u)&&((h=(p=Tt())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${l}"`))||o==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((n=t.duration)!=null?n:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:p,codecs:h})=>r(o,p,h)),c=new Set(l.map(({codecs:p})=>p)),d=hm(c);if(d&&(a[o]=l.filter(({codecs:p})=>p.startsWith(d))),o==="video"){let p=mm(),h=this.tuning.preferHDR,m=a.video.some(S=>S.hdr),g=a.video.some(S=>!S.hdr);p&&h&&m?a.video=a.video.filter(S=>S.hdr):g&&(a.video=a.video.filter(S=>!S.hdr))}}return X(V({},t),{streams:a})})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return fe(this,null,function*(){var d;(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Qf():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ps())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(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$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Yi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Yi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(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(p=>{var h;if((h=this.element)!=null&&h.paused){let m=_o(this.manifestUrlString,2);this.manifestUrlString=ve(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...cb.filter(p=>p!=="waiting").map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?St(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.filter)(p=>!!p),(0,v.tap)(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(h=>hu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=h-g,P=1;Math.abs(A)>S&&(P=1+Math.sign(A)*T),hu(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let T=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(P=>{var I,E;return(E=(I=P.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?E:T}))-T}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(g=>D(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,T=_o(this.manifestUrlString,2),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,K=isFinite(h)?h:m,W=this.isActiveLowLatency$.getValue(),U=A<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(W&&U);let Q="none";if(W?Q="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Z=>Z.proceedLowLatencyLive()),Q="active_low_latency"):T!==0&&K<P?Q="live_forward_buffering":K<P+E&&(Q="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),Q==="live_forward_buffering"||Q==="live_with_target_offset"){let Z=p-(P+I),N=this.normolizeLiveOffset(Math.trunc(T+Z/S)),C=Math.abs(N-T),ee;!h||C<=this.tuning.dashCmafLive.offsetCalculationError?ee=T:N>0&&C>this.tuning.dashCmafLive.offsetCalculationError?ee=N:ee=0,this.manifestUrlString=ve(this.manifestUrlString,ee,2)}Q!=="none"&&Q!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:u,someBufferEnded:l}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.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(p=>p.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.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...c)/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=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Is({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=sr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,V({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return D(this,null,function*(){var r,a,s,n;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ve(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...cb.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(()=>{var t;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=()=>{var r,a;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let s=this.element.currentTime*1e3;(r=this.videoBufferManager)==null||r.maintain(s),(a=this.audioBufferManager)==null||a.maintain(s)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return D(this,null,function*(){let a={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return a==null?void 0:a.switchTo(t,r)})}seek(e,t){var a,s,n,o,u;(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((a=this.videoBufferManager.findSegmentStartTime(e))!=null?a:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Ei(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(a=>a.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return D(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.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$.getValue()&&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 ws=class{constructor(e,t){this.fov=e,this.orientation=t}};var ks=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/it(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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?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=V({},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*it(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 db=`attribute vec2 a_vertex;
|
|
38
38
|
attribute vec2 a_texel;
|
|
39
39
|
|
|
40
40
|
varying vec2 v_texel;
|
|
@@ -45,7 +45,7 @@ void main(void) {
|
|
|
45
45
|
// save texel vector to pass to fragment shader
|
|
46
46
|
v_texel = a_texel;
|
|
47
47
|
}
|
|
48
|
-
`;var
|
|
48
|
+
`;var pb=`#ifdef GL_ES
|
|
49
49
|
precision highp float;
|
|
50
50
|
precision highp int;
|
|
51
51
|
#else
|
|
@@ -88,5 +88,5 @@ void main(void) {
|
|
|
88
88
|
// sample using new coordinates
|
|
89
89
|
gl_FragColor = texture2D(u_texture, tc);
|
|
90
90
|
}
|
|
91
|
-
`;var Er=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let 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 Tr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ir(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=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(a,-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){let 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(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Js,this.gl.VERTEX_SHADER),i=this.createShader(Xs,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(){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,i=1,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(){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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,p=t+r;return[a,s,o,u,d,l,c,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(){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 $t=class{constructor(e){this.subscription=new M.Subscription;this.videoState=new H("stopped");this.elementSize$=new M.ValueSubject(void 0);this.textTracksManager=new De;this.droppedFramesManager=new ar;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ir;this.textTracks=[];this.syncPlayback=()=>{var s,o,u;let 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==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let d=(o=(s=this.liveOffset)==null?void 0:s.getTotalPausedTime())!=null?o:0;this.seek(r.position-d,r.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"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(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()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,M.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Er(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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=ye(e.container,e.tuning),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(he(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new yr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Ee(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:M.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,M.filter)(d=>!!d.length),(0,M.once)()).subscribe(d=>{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:d})})),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,M.filter)(M.isNonNullable),(0,M.once)()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe((0,M.map)(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),a((0,M.observeElementSize)(this.video),this.elementSize$),a(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams();if((0,M.assertNonNullable)(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(ua(h));let f=[];for(let b of h.representations){let y=Qs(b);f.push(y),this.audioTracksMap.set(y,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of l.video){c.push(da(p));let h=[];for(let f of p.representations){let b=Ws(f);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(c);for(let p of l.text)for(let h of p.representations){let f=Ys(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:M.ErrorCategory.WTF,message:"Switching representations threw",thrown:d});this.subscription.add((0,M.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,M.fromEvent)(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(d)||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),d==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(s),h){let b=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,b).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,M.filterChanged)()).subscribe(d=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:p}]=l,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(da(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,M.filterChanged)()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[c,{stream:p}]=l,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(ua(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.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);let o=t.playbackState.stateChangeStarted$.pipe((0,M.map)(({to:d})=>d==="ready"),(0,M.filterChanged)());this.subscription.add((0,M.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add((0,M.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,M.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,M.observableFrom)(["init"])).pipe((0,M.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var Y,U,j,X,_,L,Z,oe,C,k,K,re,ue;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(Y=e.videoTrack.getState())==null?void 0:Y.id,s=[...this.videoTracksMap.keys()].find(({id:W})=>W===r),o=t.currentVideoTrack$.getValue(),u=((X=(j=e.videoStream.getState())!=null?j:s&&((U=this.videoTracksMap.get(s))==null?void 0:U.stream))!=null?X:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let d=[...this.videoStreamsMap.keys()].find(({id:W})=>W===u.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let c=Xe(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(_=e.audioStream.getState())!=null?_:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=[...this.audioStreamsMap.keys()].find(({id:W})=>W===(f==null?void 0:f.id)),y=0;if(b){if(s&&!i){let W=mr(s,l,(L=this.audioStreamsMap.get(b))!=null?L:[]);y=Math.max(y,(Z=W==null?void 0:W.bitrate)!=null?Z:-1/0)}if(o){let W=mr(o,l,(oe=this.audioStreamsMap.get(b))!=null?oe:[]);y=Math.max(y,(C=W==null?void 0:W.bitrate)!=null?C:-1/0)}}let x=ct(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:O}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&i&&(x=(k=l.filter(W=>!(0,M.isInvariantQuality)(W.quality)).sort((W,Oe)=>{var ht,at;return((ht=Oe.bitrate)!=null?ht:0)-((at=W.bitrate)!=null?at:0)}).filter(W=>(0,M.isLowerOrEqual)(W.quality,x.quality)&&(0,M.isLowerOrEqual)(W.quality,O))[0])!=null?k:x);let E=i?x!=null?x:s:s!=null?s:x,v=b&&mr(E,l,(K=this.audioStreamsMap.get(b))!=null?K:[]),T=(re=this.videoTracksMap.get(E))==null?void 0:re.representation,z=v&&((ue=this.audioTracksMap.get(v))==null?void 0:ue.representation);if(T&&z)return[T,z];if(T&&!z&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:M.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),Te(this.video)}};var Di=class extends $t{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Lt=require("@vkontakte/videoplayer-shared");var Ci=class extends $t{constructor(e){super(e),this.liveOffset=new ze}subscribe(){super.subscribe();let{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((0,Lt.combine)({interval:(0,Lt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(r-1);s<=0&&e.position$.next(s),(a=this.liveOffset)==null||a.resetTo(-s*1e3)}})).add((0,Lt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Lt.map)(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(s,r)})}};var G=require("@vkontakte/videoplayer-shared");var Fe={};var Gt=(n,e)=>new G.Observable(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Vi=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new H("initializing");this.textTracksManager=new De;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.video=ye(e.container,e.tuning),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(he(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Te(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:G.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||(Fe.Hls=r.default,Fe.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){(0,G.assertNonNullable)(Fe.Hls,"hls.js not loaded"),this.hls=new Fe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(Fe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Ee(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(We(this.video,e.isLooped,i)),this.subscription.add(Ie(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Re(this.video,e.playbackRate,r.playbackRateState$,i)),a(Ce(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe((0,G.map)(d=>d.to)),this.params.output.playbackState$),this.subscription.add(Gt(this.hls,Fe.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)==null?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())==null?void 0:d.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Gt(this.hls,Fe.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:d})=>d.reduce((l,c)=>{var O,E;let p=c.name||c.height.toString(10),{width:h,height:f}=c,b=(E=lt((O=c.attrs.QUALITY)!=null?O:""))!=null?E:(0,G.videoSizeToQuality)({width:h,height:f});if(!b)return l;let y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,x={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:f},fps:y};return this.trackLevels.set(p,{track:x,level:c}),l.push(x),l},[]))),t.availableVideoTracks$),a(Gt(this.hls,Fe.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let l=[];for(let c of d.subtitleTracks){let p=c.name,h=c.attrs.URI||"",f=c.lang,b="internal";l.push({id:p,url:h,language:f,type:b})}e.internalTextTracks.startTransitionTo(l)}}),a(Gt(this.hls,Fe.Events.LEVEL_LOADING).pipe((0,G.map)(({url:d})=>he(d))),t.hostname$),a(Gt(this.hls,Fe.Events.FRAG_CHANGED),d=>{var p,h,f,b;let{video:l,audio:c}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((b=c==null?void 0:c.startPTS)!=null?b:0))*1e3)}),this.subscription.add(dt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))==null?void 0:l.track},o=Gt(this.hls,Fe.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:d})=>s(this.hls.levels[d])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(dt(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{var f;if((0,G.isNullable)(d))return;let l=(f=this.trackLevels.get(d.id))==null?void 0:f.level;if(!l)return;let c=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return R(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield xe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),A(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"),A(this.params.desiredState.playbackState,"stopped",!0)}};var Zs="X-Playback-Duration",pa=n=>R(void 0,null,function*(){var r;let e=yield fetch(n),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Zs)?parseInt(e.headers.get(Zs),10):void 0});var F=require("@vkontakte/videoplayer-shared");var xr=require("@vkontakte/videoplayer-shared");var Go=n=>{let e=null;if(n.QUALITY&&(e=lt(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,xr.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},Wo=(n,e)=>{var a,s;let t=n.split(`
|
|
92
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!l)){if(d){let c=Object.fromEntries(d[1].split(",").map(O=>O.split("="))),p=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,h=Go(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,y;if(c.RESOLUTION){let[O,E]=c.RESOLUTION.split("x").map(v=>parseInt(v,10));O&&E&&(y={width:O,height:E})}let x=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:x,bandwidth:f,size:y,fps:b})}if(l){let c=Object.fromEntries(l[1].split(",").map(b=>b.split("=")).map(([b,y])=>[b,y.replace(/^"|"$/g,"")])),p=(s=c.URI)==null?void 0:s.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,f=c.NAME;p&&h&&r.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Qo=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),ha=0,en=(i,...r)=>R(void 0,[i,...r],function*(n,e=n,t){let s=yield(yield fetch(n)).text();ha+=1;try{let{qualityManifests:o,textTracks:u}=Wo(s,e);return{qualityManifests:o,textTracks:u}}catch(o){if(ha<=t.manifestRetryMaxCount)return yield Qo((0,xr.getExponentialDelay)(ha-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),en(n,e,t)}return{qualityManifests:[],textTracks:[]}}),Ar=en;var Bi=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new H("stopped");this.textTracksManager=new De;this.manifests$=new F.ValueSubject([]);this.liveOffset=new ze;this.manifestStartTime$=new F.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="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 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.prepare()}else(r==null?void 0:r.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,F.assertNever)(t)}};var t;this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:F.VideoQuality.INVARIANT,url:this.params.source.url},Ar(fe(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:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:F.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:F.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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(he(this.params.source.url)),this.maxSeekBackTime$=new F.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:F.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ce(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,F.filterChanged)(),(0,F.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(0,F.isNonNullable)(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(he(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,d,l;let o=(l=(d=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:d.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,F.combine)({startTime:this.manifestStartTime$.pipe((0,F.filter)(F.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,F.map)(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=(0,F.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,F.isNullable)(e))return;let 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){let{max:d,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[c,p]of[[d,"mq"],[l,"lq"]]){let h=String(parseFloat(c||""));p&&c&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=fe(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),pa(s).then(d=>{var l;if(!(0,F.isNullable)(d))this.maxSeekBackTime$.next(d);else{let c=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if((0,F.isNullable)(c)||!isFinite(c))try{fetch(s).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,s).toString();pa(b).then(y=>{(0,F.isNullable)(y)||this.maxSeekBackTime$.next(y)})}})}catch(p){}}})}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let 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()}};var q=require("@vkontakte/videoplayer-shared");var Oi=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("stopped");this.textTracksManager=new De;this.manifests$=new q.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,q.assertNever)(t)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:q.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(he(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ar(fe(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:q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:q.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,q.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,i)),this.subscription.add(Ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var c;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(0,q.isNonNullable)(d.to)){let p=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(he(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(f!==b){let y=this.params.output.element$.getValue();y&&(this.params.desiredState.playbackRate.setState(f),y.playbackRate=f)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,q.map)(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!(0,q.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,q.merge)((0,q.fromEvent)(o,"addtrack"),(0,q.fromEvent)(o,"removetrack"),(0,q.fromEvent)(o,"change"),(0,q.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=(0,q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var a,s;let e=this.selectManifest();if((0,q.isNullable)(e))return;let 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){let{max:o,min:u}=(s=(a=t==null?void 0:t.to)!=null?a:i)!=null?s:{};for(let[d,l]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(d||""));l&&d&&r.searchParams.set(l,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ie=require("@vkontakte/videoplayer-shared");var _i=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{var u,d,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),s.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(d=this.trackUrls[s.to.id])==null?void 0:d.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,ie.assertNever)(e)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},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(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,ie.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(We(this.video,t.isLooped,i)),this.subscription.add(Ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ce(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,d;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ie.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(),c=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(l!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ie.observableFrom)(["init"])).pipe((0,ie.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Te(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=$i(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(he(t))}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,a,s,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(a=Object.values(this.trackUrls).find(c=>!(0,ie.isInvariantQuality)(c.track.quality)&&(0,ie.isLowerOrEqual)(c.track.quality,e)))==null?void 0:a.track,d=(s=this.params.desiredState.videoTrack.getState())==null?void 0:s.id,l=(o=this.trackUrls[d!=null?d:"0"])==null?void 0:o.track;if(u&&l&&(0,ie.isHigherOrEqual)(l.quality,u.quality)&&(t=u),!t){let c=Object.values(this.trackUrls).filter(h=>!(0,ie.isInvariantQuality)(h.track.quality)&&(0,ie.isHigher)(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(d=>d.track);t=ct(u,{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})}};var se=require("@vkontakte/videoplayer-shared");var rn=require("@vkontakte/videoplayer-shared");var tn=["stun:videostun.mycdn.me:80"],Yo=1e3,jo=3,ma=()=>null,kr=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=ma;this.externalStopCallback=ma;this.externalErrorCallback=ma;this.options=this.normalizeOptions(t);let 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{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}}handleUpdateMessage(e){return R(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return R(this,null,function*(){try{let e={iceServers:[{urls:tn}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:rn.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return R(this,null,function*(){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()))}}createOffer(){return R(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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(t){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),Yo)}normalizeOptions(e={}){let t={stunServerList:tn,maxRetryNumber:jo,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ni=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new se.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),A(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()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,se.assertNever)(e)}};this.subscription=new se.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ye(e.container,e.tuning),this.liveStreamClient=new kr(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),Te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:se.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};(0,se.merge)(this.videoState.stateChangeStarted$.pipe((0,se.map)(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,se.map)(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=Ee(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Ce(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())==null?void 0:s.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ie(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.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,se.assertNever)(s.to)}},i)).add((0,se.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.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(he(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:se.VideoQuality.INVARIANT}),this.video.srcObject=e,A(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:se.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Fi=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 tt=require("@vkontakte/videoplayer-shared"),an=n=>new tt.Observable(e=>{let t=new tt.Subscription,i=n.desiredPlaybackState$.stateChangeStarted$.pipe((0,tt.map)(({from:d,to:l})=>`${d}-${l}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe((0,tt.map)(({type:d})=>d!==void 0)),s=new tt.Subject,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Le=require("@vkontakte/videoplayer-shared");var Ui=null,Pr=null;function fa(){return Ui||(Ui=new(window.AudioContext||window.webkitAudioContext)),Pr||(Pr=new GainNode(Ui,{gain:1}),Pr.connect(Ui.destination)),{audioCtx:Ui,gainNode:Pr}}var wr=require("@vkontakte/videoplayer-shared");var Wt=class Wt{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Le.Subscription;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe((0,Le.filter)(s=>!!s.type),(0,Le.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){let{browser:t}=(0,wr.getCurrentBrowser)();t===wr.CurrentClientBrowser.Safari&&e!=="MPEG"||this.subscriptions.add((0,Le.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Le.filter)(({playbackState:i,video:r,volume:{muted:a,volume:s}})=>i==="playing"&&!!r&&!a&&!!s),(0,Le.once)()).subscribe(({video:i})=>this.initAudioContextOnce(i)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=fa(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{var s;if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Wt.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(o){this.volumeMultiplierError$.next({id:Wt.errorId,category:Le.ErrorCategory.VIDEO_PIPELINE,message:(s=o==null?void 0:o.message)!=null?s:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(s=>{var o;this.volumeMultiplierError$.next({id:Wt.errorId,category:Le.ErrorCategory.VIDEO_PIPELINE,message:(o=s==null?void 0:s.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=fa();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Wt.errorId="VolumeMultiplierManager";var Hi=Wt;var qo={chunkDuration:5e3,maxParallelRequests:5},Gi=class{constructor(e){this.current$=new S.ValueSubject({type:void 0});this.providerError$=new S.Subject;this.noAvailableProvidersError$=new S.Subject;this.volumeMultiplierError$=new S.Subject;this.providerOutput={position$:new S.ValueSubject(0),duration$:new S.ValueSubject(1/0),volume$:new S.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new S.ValueSubject([]),currentVideoStream$:new S.ValueSubject(void 0),availableVideoTracks$:new S.ValueSubject([]),currentVideoTrack$:new S.ValueSubject(void 0),availableAudioStreams$:new S.ValueSubject([]),currentAudioStream$:new S.ValueSubject(void 0),availableAudioTracks$:new S.ValueSubject([]),currentVideoSegmentLength$:new S.ValueSubject(0),currentAudioSegmentLength$:new S.ValueSubject(0),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),playbackState$:new S.ValueSubject("")};this.subscription=new S.Subscription;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Es([...As(this.params.tuning),...xs(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>(0,S.isNonNullable)(e.sources[u])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(u=>!r.includes(u)),...t.filter(u=>r.includes(u))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Fi(a);let s=[...ia(!0),...ia(!1)];this.chromecastFormatsIterator=new Fi(s.filter(u=>(0,S.isNonNullable)(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Hi(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}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(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,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(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}e.destroy();let a=this.providerOutput.isBuffering$;a.getValue()||a.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:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,S.assertNonNullable)(o),new Di(J(V({},s),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ci(J(V({},s),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),_t||!this.params.tuning.useHlsJs?new Oi(J(V({},s),{source:o})):new Vi(J(V({},s),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Bi(J(V({},s),{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(J(V({},s),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new ns(J(V({},s),{source:o,config:J(V({},qo),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,S.assertNonNullable)(o),new Ni({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,S.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,S.assertNonNullable)(o),new Xt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,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 i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return J(V({},e),{url:i(e.url)})}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new S.Subscription,t=!1,i=0;return e.add((0,S.merge)(this.providerOutput.error$,an({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,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;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,S.filter)(({to:a})=>a==="playing"),(0,S.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let s=r.category===S.ErrorCategory.NETWORK,o=r.category===S.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:"SCREEN")}})),e}};var B=require("@vkontakte/videoplayer-shared");var zo=5e3,sn="one_video_throughput",nn="one_video_rtt",it=window.navigator.connection,on=()=>{let n=it==null?void 0:it.downlink;if((0,B.isNonNullable)(n)&&n!==10)return n*1e3},un=()=>{let n=it==null?void 0:it.rtt;if((0,B.isNonNullable)(n)&&n!==3e3)return n},dn=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},ba=class n{constructor(e){this.subscription=new B.Subscription;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=n.load(sn)||(e.useBrowserEstimation?on():void 0)||zo,i=(a=(r=n.load(nn))!=null?r:e.useBrowserEstimation?un():void 0)!=null?a:0;if(this.throughput$=new B.ValueSubject(t),this.rtt$=new B.ValueSubject(i),this.rttAdjustedThroughput$=new B.ValueSubject(dn(t,i,e.rttPenaltyRequestSize)),this.throughput=wt.getSmoothedValue(t,-1,e),this.rtt=wt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let s=()=>{let u=on();u&&this.throughput.next(u);let d=un();(0,B.isNonNullable)(d)&&this.rtt.next(d)};it&&"onchange"in it&&this.subscription.add((0,B.fromEvent)(it,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{B.safeStorage.set(sn,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{B.safeStorage.set(nn,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,B.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,B.map)(({throughput:s,rtt:o})=>dn(s,o,e.rttPenaltyRequestSize)),(0,B.filter)(s=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,B.now)(),r=new B.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,B.fromEvent)(e,"progress").pipe((0,B.once)()).subscribe(a=>{t=a.loaded,i=(0,B.now)()}));break;case 1:case 0:r.add((0,B.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,B.now)()}));break}r.add((0,B.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=(0,B.now)(),u=s-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=(0,B.now)(),s=0,o=(0,B.now)(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=p=>R(this,[p],function*({done:l,value:c}){if(l)!t&&this.addRawSpeed(r,(0,B.now)()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=(0,B.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-a;b&&this.addRawSpeed(s,b,1,t),s=c.byteLength,a=(0,B.now)()}else s+=c.byteLength;o=(0,B.now)()}else r+=c.byteLength,s+=c.byteLength,s>=this.tuningConfig.streamMinSampleSize&&(0,B.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,(0,B.now)()-o,this.concurrentDownloads.size),s=0,o=(0,B.now)());yield i==null?void 0:i.read().then(d,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let 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){var i;let t=B.safeStorage.get(e);if((0,B.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},ln=ba;var Wi=require("@vkontakte/videoplayer-shared");var cn={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:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Wi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Wi.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:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,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,preferMultiStream:!1,preferHDR:!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,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},pn=n=>{var e;return J(V({},(0,Wi.fillWithDefault)(n,cn)),{configName:[...(e=n.configName)!=null?e:[],...cn.configName]})};var m=require("@vkontakte/videoplayer-shared");var rt=require("@vkontakte/videoplayer-shared"),ga=({seekState:n,position$:e})=>(0,rt.merge)(n.stateChangeEnded$.pipe((0,rt.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,rt.filter)(rt.isNonNullable)),e.pipe((0,rt.filter)(()=>n.getState().state==="none")));var hn=require("@vkontakte/videoplayer-shared"),mn=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return(0,hn.assertNonNullable)(e,`Wrong container or containerId {${n.container}}`),e};var $r=require("@vkontakte/videoplayer-shared"),fn=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,$r.filter)(r=>r.length>0),(0,$r.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(n)};var Qi=class{constructor(e={configName:[]}){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.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),videoStream:new H(void 0),audioStream: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 m.ValueSubject("stopped"),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,qualityWillChange$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,firstBytes$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:is};if(this.initLogs(),this.tuning=pn(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Zi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ln(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...s)=>{try{return a.apply(t,s)}catch(o){let u=s.map(c=>JSON.stringify(c,(p,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:m.ErrorCategory.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=mn(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Gi({sources:e.sources,meta:(i=e.meta)!=null?i:{},failoverHosts:(r=e.failoverHosts)!=null?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.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&&!ai()?(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.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 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:"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}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,m.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.events.qualityWillChange$.next(),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return e&&this.events.qualityWillChange$.next(),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;(0,m.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>V({type:"external"},t))),this}selectTextTrack(e){var t;return fn(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.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 i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.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,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let 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((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.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 s=this.desiredState.seekState.getState();s.state==="requested"?this.desiredState.seekState.setState(J(V({},s),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:m.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,m.map)(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(s=>s.destination),(0,m.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,m.map)(s=>s.map(({quality:o})=>o).sort((o,u)=>(0,m.isInvariantQuality)(o)?1:(0,m.isInvariantQuality)(u)?-1:(0,m.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s==null?void 0:s.quality),this.info.videoBitrate$.next(s==null?void 0:s.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.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(s=>{this.desiredState.autoVideoTrackLimits.setState(s!=null?s:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(s=>s?{start:s.from,end:s.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,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(s=>s.to),(0,m.filterChanged)(),(0,m.map)(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ga({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),(0,m.filterChanged)(),(0,m.tap)(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(s=>s.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(s=>s.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(ga({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.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.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,m.map)(s=>({id:s?`No${s}`:"NoProviders",category:m.ErrorCategory.VIDEO_PIPELINE,message:s?`${s} 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,m.once)(),(0,m.map)(s=>s!=null?s:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.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 m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:s})=>s==="playing"),(0,m.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,m.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,m.map)(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),(0,m.filterChanged)());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,m.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s==null?void 0:s.videoWidth,height:s==null?void 0:s.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{var u,d;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=s==null?void 0:s.size)==null?void 0:u.width,height:(d=s==null?void 0:s.size)==null?void 0:d.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),c;l==="CONNECTED"?c="second_screen":u?d?s?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(i=>i.length>0),(0,m.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=ct(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,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.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(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),ts(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>es(i)),this.providerContainer.current$.subscribe(({type:i})=>ei("provider",i)),e.duration$.subscribe(i=>ei("duration",i)),e.availableVideoTracks$.pipe((0,m.filter)(i=>!!i.length),(0,m.once)()).subscribe(i=>ei("tracks",i)),this.events.fatalError$.subscribe(new ge("fatalError")),this.events.managedError$.subscribe(new ge("managedError")),e.position$.subscribe(new ge("position")),e.currentVideoTrack$.pipe((0,m.map)(i=>i==null?void 0:i.quality)).subscribe(new ge("quality")),this.info.currentBuffer$.subscribe(new ge("buffer")),e.isBuffering$.subscribe(new ge("isBuffering"))].forEach(i=>this.subscription.add(i)),ei("codecs",Is())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:m.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!(e!=null&&e.released);r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let 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}};var Ye=require("@vkontakte/videoplayer-shared"),Ko=`@vkontakte/videoplayer-core@${Gr}`;
|
|
91
|
+
`;var Rs=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 ws(this.params.fov,this.params.orientation),this.cameraRotationManager=new ks(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(db,this.gl.VERTEX_SHADER),r=this.createShader(pb,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,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,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(){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 nr=class{constructor(e){this.subscription=new M.Subscription;this.videoState=new H("stopped");this.elementSize$=new M.ValueSubject(void 0);this.textTracksManager=new Ue;this.droppedFramesManager=new us;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ns;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;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==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-l,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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(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==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,M.assertNever)(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new Rs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((a=e.projectionData)==null?void 0:a.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.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=Ae(e.container,e.tuning),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(be(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new As({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=Re(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:M.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,M.filter)(l=>!!l.length),(0,M.once)()).subscribe(l=>{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:l})})),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,M.filter)(M.isNonNullable),(0,M.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,M.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(ot(this.video,t.isLooped,a)),this.subscription.add(ke(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,a)),s((0,M.observeElementSize)(this.video),this.elementSize$),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if((0,M.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(cu(h));let m=[];for(let g of h.representations){let S=ab(g);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(du(p));let h=[];for(let m of p.representations){let g=ib(m);g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=sb(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=l=>e.error$.next({id:"RepresentationSwitch",category:M.ErrorCategory.WTF,message:"Switching representations threw",thrown:l});this.subscription.add((0,M.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,M.fromEvent)(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,g).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,M.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(du(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,M.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(cu(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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,M.map)(({to:l})=>l==="ready"),(0,M.filterChanged)());this.subscription.add((0,M.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,M.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,M.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,M.observableFrom)(["init"])).pipe((0,M.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){var W,U,Q,Z,N,C,ee,le,B,k,J,ae,ce;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=(W=e.videoTrack.getState())==null?void 0:W.id,n=[...this.videoTracksMap.keys()].find(({id:G})=>G===a),o=t.currentVideoTrack$.getValue(),u=((Z=(Q=e.videoStream.getState())!=null?Q:n&&((U=this.videoTracksMap.get(n))==null?void 0:U.stream))!=null?Z:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:G})=>G===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=St(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(N=e.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=[...this.audioStreamsMap.keys()].find(({id:G})=>G===(m==null?void 0:m.id)),S=0;if(g){if(n&&!r){let G=ys(n,c,(C=this.audioStreamsMap.get(g))!=null?C:[]);S=Math.max(S,(ee=G==null?void 0:G.bitrate)!=null?ee:-1/0)}if(o){let G=ys(o,c,(le=this.audioStreamsMap.get(g))!=null?le:[]);S=Math.max(S,(B=G==null?void 0:G.bitrate)!=null?B:-1/0)}}let T=Dt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:A}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(T=(k=c.filter(G=>!(0,M.isInvariantQuality)(G.quality)).sort((G,Ye)=>{var Bt,At;return((Bt=Ye.bitrate)!=null?Bt:0)-((At=G.bitrate)!=null?At:0)}).filter(G=>(0,M.isLowerOrEqual)(G.quality,T.quality)&&(0,M.isLowerOrEqual)(G.quality,A))[0])!=null?k:T);let P=r?T!=null?T:n:n!=null?n:T,I=g&&ys(P,c,(J=this.audioStreamsMap.get(g))!=null?J:[]),E=(ae=this.videoTracksMap.get(P))==null?void 0:ae.representation,K=I&&((ce=this.audioTracksMap.get(I))==null?void 0:ce.representation);if(E&&K)return[E,K];if(E&&!K&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:M.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),we(this.video)}};var Ji=class extends nr{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 or=require("@vkontakte/videoplayer-shared");var Xi=class extends nr{constructor(e){super(e),this.liveOffset=new mt}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,or.combine)({interval:(0,or.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(a-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,or.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,or.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(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,a)})}};var hb=Qe(is(),1);var j=require("@vkontakte/videoplayer-shared");var tt={};var Nr=(i,e)=>new j.Observable(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Zi=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new H("initializing");this.textTracksManager=new Ue;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==null?void 0: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,j.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,j.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,j.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,j.assertNever)(e)}break;default:(0,j.assertNever)(t)}};this.video=Ae(e.container,e.tuning),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(be(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),we(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:j.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,hb.default)(import("hls.js").then(a=>{e||(tt.Hls=a.default,tt.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,j.assertNonNullable)(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,j.assertNonNullable)(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:j.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=Re(this.video),s=(l,c)=>this.subscription.add(l.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(ot(this.video,e.isLooped,r)),this.subscription.add(ke(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,a.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Nr(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:j.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),w(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),w(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Nr(this.hls,tt.Events.MANIFEST_PARSED).pipe((0,j.map)(({levels:l})=>l.reduce((c,d)=>{var A,P;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(P=Mt((A=d.attrs.QUALITY)!=null?A:""))!=null?P:(0,j.videoSizeToQuality)({width:h,height:m});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Nr(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang,g="internal";c.push({id:p,url:h,language:m,type:g})}e.internalTextTracks.startTransitionTo(c)}}),s(Nr(this.hls,tt.Events.LEVEL_LOADING).pipe((0,j.map)(({url:l})=>be(l))),t.hostname$),s(Nr(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Ct(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Nr(this.hls,tt.Events.LEVEL_SWITCHED).pipe((0,j.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,j.filter)(j.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,j.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!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 u=(0,j.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return D(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Le(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),w(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"),w(this.params.desiredState.playbackState,"stopped",!0)}};var fb="X-Playback-Duration",fu=i=>D(void 0,null,function*(){var a;let e=yield vt(i),t=yield e.text(),r=(a=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:a[1];return r?parseInt(r,10):e.headers.has(fb)?parseInt(e.headers.get(fb),10):void 0});var q=require("@vkontakte/videoplayer-shared");var bu=Qe(Jn(),1);var Ls=require("@vkontakte/videoplayer-shared");var iA=i=>{let e=null;if(i.QUALITY&&(e=Mt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=(0,Ls.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},aA=(i,e)=>{var s,n;let t=i.split(`
|
|
92
|
+
`),r=[],a=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,bu.default)(l[1].split(",").map(A=>A.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=iA(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[A,P]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));A&&P&&(S={width:A,height:P})}let T=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:T,bandwidth:m,size:S,fps:g})}if(c){let d=(0,bu.default)(c[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&a.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},sA=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),mu=0,mb=(r,...a)=>D(void 0,[r,...a],function*(i,e=i,t){let n=yield(yield vt(i)).text();mu+=1;try{let{qualityManifests:o,textTracks:u}=aA(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(mu<=t.manifestRetryMaxCount)return yield sA((0,Ls.getExponentialDelay)(mu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),mb(i,e,t)}return{qualityManifests:[],textTracks:[]}}),$s=mb;var ea=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Ue;this.manifests$=new q.ValueSubject([]);this.liveOffset=new mt;this.manifestStartTime$=new q.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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=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),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((a==null?void 0:a.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(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==null?void 0:a.to)==="playing"&&w(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==null?void 0:a.to)==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,q.assertNever)(t)}};var t;this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:q.VideoQuality.INVARIANT,url:this.params.source.url},$s(ve(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:q.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:q.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),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(be(this.params.source.url)),this.maxSeekBackTime$=new q.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:q.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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(ke(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,q.filterChanged)(),(0,q.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,q.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(be(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,q.combine)({startTime:this.manifestStartTime$.pipe((0,q.filter)(q.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,q.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,q.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),we(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,q.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:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&a.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ve(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),fu(n).then(l=>{var c;if(!(0,q.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,q.isNullable)(d)||!isFinite(d))try{vt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();fu(g).then(S=>{(0,q.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.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 z=require("@vkontakte/videoplayer-shared");var ta=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new H("stopped");this.textTracksManager=new Ue;this.manifests$=new z.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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=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),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),w(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==null?void 0:a.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,z.assertNever)(t)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:z.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(be(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),$s(ve(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:z.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:z.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},a=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));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$),s(this.videoState.stateChangeEnded$.pipe((0,z.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,z.isNonNullable)(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(be(h.url));let m=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,z.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!(0,z.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,z.merge)((0,z.fromEvent)(o,"addtrack"),(0,z.fromEvent)(o,"removetrack"),(0,z.fromEvent)(o,"change"),(0,z.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,z.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,z.observableFrom)(["init"])).pipe((0,z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),we(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,z.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:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),w(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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ie=require("@vkontakte/videoplayer-shared");var ra=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Ue;this.syncPlayback=()=>{var u,l,c;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"),w(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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(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==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,ie.assertNever)(e)}};this.params=e,this.video=Ae(e.container,e.tuning),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:ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},a=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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$),s(this.videoState.stateChangeEnded$.pipe((0,ie.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ie.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ie.observableFrom)(["init"])).pipe((0,ie.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),we(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Wi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(be(t))}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var a,s,n,o;let t,r=e;if(e&&((a=this.params.output.currentVideoTrack$.getValue())==null?void 0:a.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!(0,ie.isInvariantQuality)(d.track.quality)&&(0,ie.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,ie.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!(0,ie.isInvariantQuality)(h.track.quality)&&(0,ie.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=Dt(u,{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 ne=require("@vkontakte/videoplayer-shared");var gb=require("@vkontakte/videoplayer-shared");var bb=["stun:videostun.mycdn.me:80"],nA=1e3,oA=3,gu=()=>null,Cs=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=gu;this.externalStopCallback=gu;this.externalErrorCallback=gu;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}}handleUpdateMessage(e){return D(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return D(this,null,function*(){try{let e={iceServers:[{urls:bb}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return D(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return D(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:gb.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return D(this,null,function*(){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()))}}createOffer(){return D(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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(t){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),nA)}normalizeOptions(e={}){let t={stunServerList:bb,maxRetryNumber:oA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ia=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new ne.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"),w(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"),w(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==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,ne.assertNever)(e)}};this.subscription=new ne.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container,e.tuning),this.liveStreamClient=new Cs(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),we(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ne.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ne.merge)(this.videoState.stateChangeStarted$.pipe((0,ne.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ne.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=Re(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(He(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(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.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(ke(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,ne.assertNever)(n.to)}},r)).add((0,ne.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ne.observableFrom)(["init"])).pipe((0,ne.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(be(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:ne.VideoQuality.INVARIANT}),this.video.srcObject=e,w(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:ne.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var aa=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 y=require("@vkontakte/videoplayer-shared");var Et=require("@vkontakte/videoplayer-shared"),Sb=i=>new Et.Observable(e=>{let t=new Et.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe((0,Et.map)(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe((0,Et.map)(({type:l})=>l!==void 0)),n=new Et.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var _e=require("@vkontakte/videoplayer-shared");var sa=null,Ms=null;function Su(){return sa||(sa=new(window.AudioContext||window.webkitAudioContext)),Ms||(Ms=new GainNode(sa,{gain:1}),Ms.connect(sa.destination)),{audioCtx:sa,gainNode:Ms}}var Ds=require("@vkontakte/videoplayer-shared");var Fr=class Fr{constructor(e,t,r,a,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.subscriptions=new _e.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||a===1||this.subscriptions.add(this.provider$.pipe((0,_e.filter)(n=>!!n.type),(0,_e.once)()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){let{browser:t}=(0,Ds.getCurrentBrowser)();t===Ds.CurrentClientBrowser.Safari&&e!=="MPEG"||this.subscriptions.add((0,_e.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,_e.filter)(({playbackState:r,video:a,volume:{muted:s,volume:n}})=>r==="playing"&&!!a&&!s&&!!n),(0,_e.once)()).subscribe(({video:r})=>this.initAudioContextOnce(r)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=Su(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Fr.errorId} destroyed`);a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(o){this.volumeMultiplierError$.next({id:Fr.errorId,category:_e.ErrorCategory.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Fr.errorId,category:_e.ErrorCategory.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Su();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Fr.errorId="VolumeMultiplierManager";var na=Fr;var uA={chunkDuration:5e3,maxParallelRequests:5},oa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=cm([...pm(this.params.tuning),...dm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>(0,y.isNonNullable)(e.sources[u])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(u=>!a.includes(u)),...t.filter(u=>a.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new aa(s);let n=[...Xo(!0),...Xo(!1)];this.chromecastFormatsIterator=new aa(n.filter(u=>(0,y.isNonNullable)(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new na(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}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(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:y.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,y.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":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new Ji(X(V({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Xi(X(V({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),$r||!this.params.tuning.useHlsJs?new ta(X(V({},n),{source:o})):new Zi(X(V({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ea(X(V({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ra(X(V({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Gf(X(V({},n),{source:o,config:X(V({},uA),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ia({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.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,y.assertNonNullable)(o),new hi({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,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.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,y.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 X(V({},e),{url:r(e.url)})}return(0,vb.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$,Sb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(a=>({id:`ProviderHangup:${a}`,category:y.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,y.filter)(({to:s})=>s==="playing"),(0,y.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===y.ErrorCategory.NETWORK,o=a.category===y.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};var _=require("@vkontakte/videoplayer-shared");var lA=5e3,yb="one_video_throughput",Tb="one_video_rtt",xt=window.navigator.connection,Ib=()=>{let i=xt==null?void 0:xt.downlink;if((0,_.isNonNullable)(i)&&i!==10)return i*1e3},Eb=()=>{let i=xt==null?void 0:xt.rtt;if((0,_.isNonNullable)(i)&&i!==3e3)return i},xb=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},vu=class i{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(yb)||(e.useBrowserEstimation?Ib():void 0)||lA,r=(s=(a=i.load(Tb))!=null?a:e.useBrowserEstimation?Eb():void 0)!=null?s:0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(xb(t,r,e.rttPenaltyRequestSize)),this.throughput=sr.getSmoothedValue(t,-1,e),this.rtt=sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=Ib();u&&this.throughput.next(u);let l=Eb();(0,_.isNonNullable)(l)&&this.rtt.next(l)};xt&&"onchange"in xt&&this.subscription.add((0,_.fromEvent)(xt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{_.safeStorage.set(yb,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{_.safeStorage.set(Tb,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:n,rtt:o})=>xb(n,o,e.rttPenaltyRequestSize)),(0,_.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,_.now)(),a=new _.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,r=(0,_.now)()}));break;case 1:case 0:a.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,_.now)()}));break}a.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,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,_.now)(),n=0,o=(0,_.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>D(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(a,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,_.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,_.now)()}else n+=d.byteLength;o=(0,_.now)()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}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){var r;let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},Pb=vu;var ua=require("@vkontakte/videoplayer-shared");var Ab={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:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ua.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ua.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:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,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,preferMultiStream:!1,preferHDR:!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:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},wb=i=>{var e;return X(V({},(0,ua.fillWithDefault)(i,Ab)),{configName:[...(e=i.configName)!=null?e:[],...Ab.configName]})};var f=require("@vkontakte/videoplayer-shared");var Pt=require("@vkontakte/videoplayer-shared"),yu=({seekState:i,position$:e})=>(0,Pt.merge)(i.stateChangeEnded$.pipe((0,Pt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Pt.filter)(Pt.isNonNullable)),e.pipe((0,Pt.filter)(()=>i.getState().state==="none")));var kb=require("@vkontakte/videoplayer-shared"),Rb=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return(0,kb.assertNonNullable)(e,`Wrong container or containerId {${i.container}}`),e};var Os=require("@vkontakte/videoplayer-shared"),Lb=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Os.filter)(a=>a.length>0),(0,Os.once)()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var la=class{constructor(e={configName:[]}){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.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),videoStream:new H(void 0),audioStream: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 f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,firstBytes$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:qf};if(this.initLogs(),this.tuning=wb(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ga({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Pb(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 u=n.map(d=>JSON.stringify(d,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:f.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=Rb(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new oa({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(a=e.failoverHosts)!=null?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.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&&!vi()?(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.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}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.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,f.filter)(r=>r.length>0),(0,f.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){var r;(0,f.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>V({type:"external"},t))),this}selectTextTrack(e){var t;return Lb(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.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,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.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,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.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(X(V({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.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,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).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==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.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!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.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,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.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,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(yu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.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.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.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,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>r.next(!1)));let a=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,f.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,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.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(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?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,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var a;let t,r=(a=this.desiredState.videoTrack.getState())==null?void 0:a.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Dt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,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,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.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(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),Ff(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Nf(r)),this.providerContainer.current$.subscribe(({type:r})=>mi("provider",r)),e.duration$.subscribe(r=>mi("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>mi("tracks",r)),this.events.fatalError$.subscribe(new Te("fatalError")),this.events.managedError$.subscribe(new Te("managedError")),e.position$.subscribe(new Te("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new Te("quality")),this.info.currentBuffer$.subscribe(new Te("buffer")),e.isBuffering$.subscribe(new Te("isBuffering"))].forEach(r=>this.subscription.add(r)),mi("codecs",lm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>D(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(a)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&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 lt=require("@vkontakte/videoplayer-shared"),cA=`@vkontakte/videoplayer-core@${zs}`;
|