@vkontakte/videoplayer-core 2.0.105-dev.35548197.0 → 2.0.105-dev.419be451.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,40 +1,40 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.105-dev.35548197.0
3
- * Wed, 10 Jul 2024 13:05:36 GMT
2
+ * @vkontakte/videoplayer-core v2.0.105-dev.419be451.0
3
+ * Thu, 11 Jul 2024 16:26:35 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-105/doc/
5
5
  */
6
- var mu=Object.defineProperty,fu=Object.defineProperties;var bu=Object.getOwnPropertyDescriptors;var cs=Object.getOwnPropertySymbols;var gu=Object.prototype.hasOwnProperty,Su=Object.prototype.propertyIsEnumerable;var Pe=Math.pow,ps=(o,e,t)=>e in o?mu(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,k=(o,e)=>{for(var t in e||(e={}))gu.call(e,t)&&ps(o,t,e[t]);if(cs)for(var t of cs(e))Su.call(e,t)&&ps(o,t,e[t]);return o},V=(o,e)=>fu(o,bu(e));var w=(o,e,t)=>new Promise((i,r)=>{var a=u=>{try{n(t.next(u))}catch(d){r(d)}},s=u=>{try{n(t.throw(u))}catch(d){r(d)}},n=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,s);n((t=t.apply(o,e)).next())}),vu=function(o,e){this[0]=o,this[1]=e},z=(o,e,t)=>{var i=(s,n,u,d)=>{try{var c=t[s](n),l=(n=c.value)instanceof vu,p=c.done;Promise.resolve(l?n[0]:n).then(h=>l?i(s==="return"?s:"next",n[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]=n=>new Promise((u,d)=>i(s,n,u,d)),a={};return t=t.apply(o,e),a[Symbol.asyncIterator]=()=>a,r("next"),r("throw"),r("return"),a};var hs="2.0.105-dev.35548197.0";var ie=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ie||{}),Ge=(b=>(b.MPEG="MPEG",b.DASH="DASH_SEP",b.DASH_SEP="DASH_SEP",b.DASH_SEP_VK="DASH_SEP",b.DASH_WEBM="DASH_WEBM",b.DASH_WEBM_AV1="DASH_WEBM_AV1",b.DASH_WEBM_VK="DASH_WEBM",b.DASH_ONDEMAND="DASH_ONDEMAND",b.DASH_ONDEMAND_VK="DASH_ONDEMAND",b.DASH_LIVE="DASH_LIVE",b.DASH_LIVE_CMAF="DASH_LIVE_CMAF",b.DASH_LIVE_WEBM="DASH_LIVE_WEBM",b.HLS="HLS",b.HLS_ONDEMAND="HLS_ONDEMAND",b.HLS_JS="HLS",b.HLS_LIVE="HLS_LIVE",b.HLS_LIVE_CMAF="HLS_LIVE_CMAF",b.WEB_RTC_LIVE="WEB_RTC_LIVE",b))(Ge||{});var qi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(qi||{}),Jr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Jr||{});var Xr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Xr||{});import{assertNever as vs,assertNonNullable as yu,isNonNullable as zi,ValueSubject as Zr,Subject as Tu,Subscription as Iu,merge as Eu,observableFrom as xu,fromEvent as fs,map as bs,tap as gs,filterChanged as Pu,isNullable as ea,ErrorCategory as Ss}from"@vkontakte/videoplayer-shared";var ms=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Ki=class{constructor(e){this.connection$=new Zr(void 0);this.castState$=new Zr("NOT_AVAILABLE");this.errorEvent$=new Tu;this.realCastState$=new Zr("NOT_AVAILABLE");this.subscription=new Iu;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=zi((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},r||ms("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ss.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(){zi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ea(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ea(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(fs(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 vs(r.sessionState)}})).add(Eu(fs(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(gs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),bs(r=>r.castState)),xu([i.getCastState()])).pipe(Pu(),bs(ku),gs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;let a=r==="CONNECTED",s=zi(this.connection$.getValue());if(a&&!s){let u=i.getCurrentSession();yu(u);let d=u.getCastDevice(),c=(n=u.getMediaSession())==null?void 0:n.media.contentId;(ea(c)||c===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"?zi(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:Ss.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},ku=o=>{switch(o){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 vs(o)}};import{assertNever as ys}from"@vkontakte/videoplayer-shared";var X=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:ys(t)}return o},ta=(o,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(o);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(o);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:ys(e)}};var T=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as Au,Subject as Ji,merge as Ts}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Ji;this.transitionEnded$=new Ji;this.transitionUpdated$=new Ji;this.forceChanged$=new Ji;this.stateChangeStarted$=Ts(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ts(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||Au(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}};import{assertNever as wu}from"@vkontakte/videoplayer-shared";var Is=o=>{switch(o){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return wu(o)}};import{assertNever as xt,assertNonNullable as nt,debounce as Es,ErrorCategory as xs,fromEvent as ot,isNonNullable as Ps,map as ks,merge as As,observableFrom as $u,Subject as Lu,Subscription as ia,timeout as Ru,getHighestQuality as Mu}from"@vkontakte/videoplayer-shared";var Du=5,Cu=5,Bu=500,ws=7e3,Ft=class{constructor(e){this.subscription=new ia;this.loadMediaTimeoutSubscription=new ia;this.videoState=new L("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:xt(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:xt(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:xt(e)}break}default:xt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Is(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 ia;this.subscription.add(e),this.subscription.add(As(this.videoState.stateChangeStarted$.pipe(ks(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(ks(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 Lu;e.add(r.pipe(Es(Bu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let n=s.value;this.params.output.position$.next(n),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(n-a)>Du)&&r.next(n),a=n})),e.add(ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,n=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(n!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Cu&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:xt(s)}}),t(ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=As(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$u(["init"])).pipe(Es(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"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(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"),T(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"),T(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"&&T(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 c=t[e];nt(c);let l=Mu(Object.keys(c));nt(l);let p=c[l];nt(p),i=p,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];nt(c),i=c.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":{let c=t[e];nt(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];nt(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];nt(c),i=X(c.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",l=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:xs.VIDEO_PIPELINE,message:c,thrown:l}),l}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return xt(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:n,subtitle:u}=this.params.meta;return Ps(n)&&(s.metadata.title=n),Ps(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(Ru(ws).subscribe(()=>a(`timeout(${ws})`)))});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:xs.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Ut=o=>{o.removeAttribute("src"),o.load()};var $s=o=>{try{o.pause(),o.playbackRate=0,Ut(o),o.remove()}catch(e){console.error(e)}};var ra=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)}},aa=window.WeakMap?new WeakMap:new ra,re=o=>{let e=o.querySelector("video"),t=!!e;return e?Ut(e):(e=document.createElement("video"),o.appendChild(e)),aa.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ae=o=>{let e=aa.get(o);aa.delete(o),e?Ut(o):$s(o)};import{assertNonNullable as Ht,isNonNullable as Ae,isNullable as _u,fromEvent as Pt,merge as Ls,observableFrom as Rs,filterChanged as Ms,map as Gt,Subject as Ds,Subscription as Nu,ValueSubject as Fu,ErrorCategory as Uu}from"@vkontakte/videoplayer-shared";import{isNonNullable as sa,isNullable as Vu,Subscription as Ou}from"@vkontakte/videoplayer-shared";var Xi=(o,e,t,{equal:i=(s,n)=>s===n,changed$:r,onError:a}={})=>{let s=o.getState(),n=e(),u=Vu(r),d=new Ou;return r&&d.add(r.subscribe(c=>{let l=o.getState();i(c,l)&&o.setState(c)},a)),i(n,s)||(t(s),u&&o.setState(s)),d.add(o.stateChangeStarted$.subscribe(c=>{t(c.to),u&&o.setState(c.to)},a)),d},ke=(o,e,t)=>Xi(e,()=>o.loop,i=>{sa(i)&&(o.loop=i)},{onError:t}),se=(o,e,t,i)=>Xi(e,()=>({muted:o.muted,volume:o.volume}),r=>{sa(r)&&(o.muted=r.muted,o.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}),he=(o,e,t,i)=>Xi(e,()=>o.playbackRate,r=>{sa(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),je=Xi;var Hu=o=>["__",o.language,o.label].join("|"),Gu=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},na=class o{constructor(){this.available$=new Ds;this.current$=new Fu(void 0);this.error$=new Ds;this.subscription=new Nu;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:Uu.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(je(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ae(a)&&this.setInternal(a)},{equal:(a,s)=>Ae(a)&&Ae(s)&&a.length===s.length&&a.every(({id:n},u)=>n===s[u].id),changed$:this.available$.pipe(Gt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(je(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ae(a)&&this.setExternal(a)},{equal:(a,s)=>Ae(a)&&Ae(s)&&a.length===s.length&&a.every(({id:n},u)=>n===s[u].id),changed$:this.available$.pipe(Gt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(je(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(je(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Ht(this.video);let{textTracks:e}=this.video;this.subscription.add(Pt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ls(Pt(e,"addtrack"),Pt(e,"removetrack"),Rs(["init"])).pipe(Gt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Ms((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(Ls(Pt(e,"change"),Rs(["init"])).pipe(Gt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Gt(i=>i&&this.htmlTextTrackToITextTrack(i).id),Ms()).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(Pt(e,"addtrack").subscribe(i=>{var a,s;(a=i.track)==null||a.addEventListener("cuechange",t);let r=n=>{var d,c,l,p,h;let u=(c=(d=n.target)==null?void 0:d.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(l=n.target)==null?void 0:l.cues)!=null?p:null),(h=n.target)==null||h.removeEventListener("cuechange",r))};(s=i.track)==null||s.addEventListener("cuechange",r)})),this.subscription.add(Pt(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;Ae(t.align)&&(r.align=t.align),Ae(t.position)&&(r.position=t.position),Ae(t.size)&&(r.size=t.size),Ae(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ht(this.video);let t=[...this.video.textTracks];return e?t:t.filter(o.isHealthyTrack)}htmlTextTrackToITextTrack(e){var n,u;let{language:t,label:i}=e,r=e.id?e.id:Hu(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:(n=this.externalTracks.get(r))==null?void 0:n.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){Ht(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(_u(e)||!Gu(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){Ht(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){Ht(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)}},me=na;var De=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 Cs=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},oa=o=>{let e=Cs(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},Bs=o=>{let e=Cs(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as fe,map as Qe,merge as Os,filterChanged as Qu,isNonNullable as _s,Subject as Wu,filter as Ns,mapTo as Fs,combine as Yu,once as qu,ErrorCategory as zu,ValueSubject as Us,getCurrentBrowser as Ku,CurrentClientBrowser as Ju}from"@vkontakte/videoplayer-shared";var ju=3,Vs=(o,e,t=ju)=>{let i=0,r=0;for(let a=0;a<o.length;a++){let s=o.start(a),n=o.end(a);if(s<=e&&e<=n){if(i=s,r=n,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)o.end(u)+t>=i&&(i=o.start(u));for(let u=a+1;u<o.length;u++)o.start(u)-t<=r&&(r=o.end(u))}}return{from:i,to:r}};var ne=o=>{let e=v=>fe(o,v).pipe(Fs(void 0)),i=Os(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>fe(o,v))).pipe(Qe(v=>v.type==="ended"?o.readyState<2:o.readyState<3),Qu()),r=Os(fe(o,"progress"),fe(o,"timeupdate")).pipe(Qe(()=>Vs(o.buffered,o.currentTime))),s=Ku().browser===Ju.Safari?Yu({play:e("play").pipe(qu()),playing:e("playing")}).pipe(Fs(void 0)):e("playing"),n=fe(o,"volumechange").pipe(Qe(()=>({muted:o.muted,volume:o.volume}))),u=fe(o,"ratechange").pipe(Qe(()=>o.playbackRate)),d=fe(o,"error").pipe(Ns(()=>!!(o.error||o.played.length)),Qe(()=>{var y;let v=o.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:zu.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=o.error)!=null?y:void 0}})),c=fe(o,"timeupdate").pipe(Qe(()=>o.currentTime)),l=new Wu,p=.3,h;c.subscribe(v=>{o.loop&&_s(h)&&_s(v)&&h>=o.duration-p&&v<=p&&l.next(h),h=v});let m=e("pause").pipe(Ns(()=>!o.error&&h!==o.duration)),f=fe(o,"enterpictureinpicture"),g=fe(o,"leavepictureinpicture"),S=new Us(Bs(o));f.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let b=new Us(oa(o));return fe(o,"fullscreenchange").pipe(Qe(()=>oa(o))).subscribe(b),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:fe(o,"durationchange").pipe(Qe(()=>o.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:S,inFullscreen$:b}};import{VideoQuality as We}from"@vkontakte/videoplayer-shared";var Ye=o=>{switch(o){case"mobile":return We.Q_144P;case"lowest":return We.Q_240P;case"low":return We.Q_360P;case"sd":case"medium":return We.Q_480P;case"hd":case"high":return We.Q_720P;case"fullhd":case"full":return We.Q_1080P;case"quadhd":case"quad":return We.Q_1440P;case"ultrahd":case"ultra":return We.Q_2160P}};import{isNonNullable as qe,isNullable as da,now as Ys,isHigher as la,isHigherOrEqual as Qs,isInvariantQuality as Ws,isLower as ca,isLowerOrEqual as Xu,videoSizeToQuality as Zu,assertNotEmptyArray as ed}from"@vkontakte/videoplayer-shared";var ua=!1,Ce={},Hs=o=>{ua=o},Gs=()=>{Ce={}},js=o=>{o(Ce)},jt=(o,e)=>{var t;ua&&(Ce.meta=(t=Ce.meta)!=null?t:{},Ce.meta[o]=e)},ee=class{constructor(e){this.name=e}next(e){var i,r;if(!ua)return;Ce.series=(i=Ce.series)!=null?i:{};let t=(r=Ce.series[this.name])!=null?r:[];t.push([Date.now(),e]),Ce.series[this.name]=t}};var td=new ee("best_bitrate"),id=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t,Zi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ys()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},rd='Assertion "ABR Tracks is empty array" failed',ad=(o,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:n,current:u,history:d,droppedVideoMaxQualityLimit:c,abrLogger:l})=>{var F,A,x,U,j;ed(o,rd);let p=i.usePixelRatio&&(F=window.devicePixelRatio)!=null?F:1,h=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},m=h&&Zu(h),f=i.considerPlaybackRate&&qe(n)?n:1,g=o.filter(P=>!Ws(P.quality)).sort((P,I)=>la(P.quality,I.quality)?-1:1),S=(A=g.at(-1))==null?void 0:A.quality,b=(x=g.at(0))==null?void 0:x.quality,$=da(r)||qe(r.min)&&qe(r.max)&&ca(r.max,r.min)||qe(r.min)&&b&&la(r.min,b)||qe(r.max)&&S&&ca(r.max,S),v=f*id(s!=null?s:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),y={},M=g.filter(P=>(m?ca(P.quality,m):!0)?(qe(t)&&isFinite(t)&&qe(P.bitrate)?t-a>=P.bitrate*v:!0)?i.lazyQualitySwitch&&qe(i.minBufferToSwitchUp)&&u&&!Ws(u.quality)&&(s!=null?s:0)<i.minBufferToSwitchUp&&la(P.quality,u.quality)?(y[P.quality]="Buffer",!1):!!c&&Qs(P.quality,c)?(y[P.quality]="DroppedFramesLimit",!1):$||(da(r.max)||Xu(P.quality,r.max))&&(da(r.min)||Qs(P.quality,r.min))?!0:(y[P.quality]="FitsQualityLimits",!1):(y[P.quality]="FitsThroughput",!1):(y[P.quality]="FitsContainer",!1))[0];M&&M.bitrate&&td.next(M.bitrate);let R=(U=M!=null?M:g[Math.ceil((g.length-1)/2)])!=null?U:o[0];R.quality!==((j=d==null?void 0:d.last)==null?void 0:j.quality)&&l({message:`
6
+ var Cg=Object.create;var en=Object.defineProperty,Mg=Object.defineProperties,Dg=Object.getOwnPropertyDescriptor,Og=Object.getOwnPropertyDescriptors,Bg=Object.getOwnPropertyNames,gl=Object.getOwnPropertySymbols,Vg=Object.getPrototypeOf,yl=Object.prototype.hasOwnProperty,_g=Object.prototype.propertyIsEnumerable;var Ue=Math.pow,vl=(i,e,t)=>e in i?en(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,k=(i,e)=>{for(var t in e||(e={}))yl.call(e,t)&&vl(i,t,e[t]);if(gl)for(var t of gl(e))_g.call(e,t)&&vl(i,t,e[t]);return i},N=(i,e)=>Mg(i,Og(e));var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Ng=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Bg(e))!yl.call(i,a)&&a!==t&&en(i,a,{get:()=>e[a],enumerable:!(r=Dg(e,a))||r.enumerable});return i};var He=(i,e,t)=>(t=i!=null?Cg(Vg(i)):{},Ng(e||!i||!i.__esModule?en(t,"default",{value:i,enumerable:!0}):t,i));var $=(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())}),Fg=function(i,e){this[0]=i,this[1]=e},Z=(i,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Fg,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 ye=f((_$,kl)=>{"use strict";kl.exports=function(i){try{return!!i()}catch(e){return!0}}});var Nr=f((N$,Rl)=>{"use strict";var Qg=ye();Rl.exports=!Qg(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var oe=f((F$,Cl)=>{"use strict";var $l=Nr(),Ll=Function.prototype,nn=Ll.call,zg=$l&&Ll.bind.bind(nn,nn);Cl.exports=$l?zg:function(i){return function(){return nn.apply(i,arguments)}}});var ar=f((q$,Dl)=>{"use strict";var Ml=oe(),Kg=Ml({}.toString),Jg=Ml("".slice);Dl.exports=function(i){return Jg(Kg(i),8,-1)}});var Bl=f((U$,Ol)=>{"use strict";var Xg=oe(),Zg=ye(),ev=ar(),on=Object,tv=Xg("".split);Ol.exports=Zg(function(){return!on("z").propertyIsEnumerable(0)})?function(i){return ev(i)=="String"?tv(i,""):on(i)}:on});var sr=f((H$,Vl)=>{"use strict";Vl.exports=function(i){return i==null}});var ha=f((j$,_l)=>{"use strict";var rv=sr(),iv=TypeError;_l.exports=function(i){if(rv(i))throw iv("Can't call method on "+i);return i}});var nr=f((G$,Nl)=>{"use strict";var av=Bl(),sv=ha();Nl.exports=function(i){return av(sv(i))}});var un=f((Y$,Fl)=>{"use strict";Fl.exports=function(){}});var Lt=f((W$,ql)=>{"use strict";ql.exports={}});var ee=f((Ul,Hl)=>{"use strict";var fa=function(i){return i&&i.Math==Math&&i};Hl.exports=fa(typeof globalThis=="object"&&globalThis)||fa(typeof window=="object"&&window)||fa(typeof self=="object"&&self)||fa(typeof global=="object"&&global)||function(){return this}()||Ul||Function("return this")()});var cn=f((Q$,jl)=>{"use strict";var ln=typeof document=="object"&&document.all,nv=typeof ln=="undefined"&&ln!==void 0;jl.exports={all:ln,IS_HTMLDDA:nv}});var W=f((z$,Yl)=>{"use strict";var Gl=cn(),ov=Gl.all;Yl.exports=Gl.IS_HTMLDDA?function(i){return typeof i=="function"||i===ov}:function(i){return typeof i=="function"}});var zl=f((K$,Ql)=>{"use strict";var uv=ee(),lv=W(),Wl=uv.WeakMap;Ql.exports=lv(Wl)&&/native code/.test(String(Wl))});var je=f((J$,Xl)=>{"use strict";var Kl=W(),Jl=cn(),cv=Jl.all;Xl.exports=Jl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Kl(i)||i===cv}:function(i){return typeof i=="object"?i!==null:Kl(i)}});var Ge=f((X$,Zl)=>{"use strict";var dv=ye();Zl.exports=!dv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var ma=f((Z$,tc)=>{"use strict";var pv=ee(),ec=je(),dn=pv.document,hv=ec(dn)&&ec(dn.createElement);tc.exports=function(i){return hv?dn.createElement(i):{}}});var pn=f((eL,rc)=>{"use strict";var fv=Ge(),mv=ye(),bv=ma();rc.exports=!fv&&!mv(function(){return Object.defineProperty(bv("div"),"a",{get:function(){return 7}}).a!=7})});var hn=f((tL,ic)=>{"use strict";var Sv=Ge(),gv=ye();ic.exports=Sv&&gv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Me=f((rL,ac)=>{"use strict";var vv=je(),yv=String,Tv=TypeError;ac.exports=function(i){if(vv(i))return i;throw Tv(yv(i)+" is not an object")}});var ue=f((iL,sc)=>{"use strict";var Iv=Nr(),ba=Function.prototype.call;sc.exports=Iv?ba.bind(ba):function(){return ba.apply(ba,arguments)}});var Sa=f((aL,nc)=>{"use strict";nc.exports={}});var Qe=f((sL,uc)=>{"use strict";var fn=Sa(),mn=ee(),Ev=W(),oc=function(i){return Ev(i)?i:void 0};uc.exports=function(i,e){return arguments.length<2?oc(fn[i])||oc(mn[i]):fn[i]&&fn[i][e]||mn[i]&&mn[i][e]}});var Fr=f((nL,lc)=>{"use strict";var xv=oe();lc.exports=xv({}.isPrototypeOf)});var qr=f((oL,cc)=>{"use strict";cc.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var Sn=f((uL,bc)=>{"use strict";var mc=ee(),bn=qr(),dc=mc.process,pc=mc.Deno,hc=dc&&dc.versions||pc&&pc.version,fc=hc&&hc.v8,De,ga;fc&&(De=fc.split("."),ga=De[0]>0&&De[0]<4?1:+(De[0]+De[1]));!ga&&bn&&(De=bn.match(/Edge\/(\d+)/),(!De||De[1]>=74)&&(De=bn.match(/Chrome\/(\d+)/),De&&(ga=+De[1])));bc.exports=ga});var gn=f((lL,gc)=>{"use strict";var Sc=Sn(),Pv=ye(),Av=ee(),wv=Av.String;gc.exports=!!Object.getOwnPropertySymbols&&!Pv(function(){var i=Symbol();return!wv(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Sc&&Sc<41})});var vn=f((cL,vc)=>{"use strict";var kv=gn();vc.exports=kv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var yn=f((dL,yc)=>{"use strict";var Rv=Qe(),$v=W(),Lv=Fr(),Cv=vn(),Mv=Object;yc.exports=Cv?function(i){return typeof i=="symbol"}:function(i){var e=Rv("Symbol");return $v(e)&&Lv(e.prototype,Mv(i))}});var Ur=f((pL,Tc)=>{"use strict";var Dv=String;Tc.exports=function(i){try{return Dv(i)}catch(e){return"Object"}}});var ze=f((hL,Ic)=>{"use strict";var Ov=W(),Bv=Ur(),Vv=TypeError;Ic.exports=function(i){if(Ov(i))return i;throw Vv(Bv(i)+" is not a function")}});var Hr=f((fL,Ec)=>{"use strict";var _v=ze(),Nv=sr();Ec.exports=function(i,e){var t=i[e];return Nv(t)?void 0:_v(t)}});var Pc=f((mL,xc)=>{"use strict";var Tn=ue(),In=W(),En=je(),Fv=TypeError;xc.exports=function(i,e){var t,r;if(e==="string"&&In(t=i.toString)&&!En(r=Tn(t,i))||In(t=i.valueOf)&&!En(r=Tn(t,i))||e!=="string"&&In(t=i.toString)&&!En(r=Tn(t,i)))return r;throw Fv("Can't convert object to primitive value")}});var Oe=f((bL,Ac)=>{"use strict";Ac.exports=!0});var Rc=f((SL,kc)=>{"use strict";var wc=ee(),qv=Object.defineProperty;kc.exports=function(i,e){try{qv(wc,i,{value:e,configurable:!0,writable:!0})}catch(t){wc[i]=e}return e}});var va=f((gL,Lc)=>{"use strict";var Uv=ee(),Hv=Rc(),$c="__core-js_shared__",jv=Uv[$c]||Hv($c,{});Lc.exports=jv});var xn=f((vL,Mc)=>{"use strict";var Gv=Oe(),Cc=va();(Mc.exports=function(i,e){return Cc[i]||(Cc[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:Gv?"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 jr=f((yL,Dc)=>{"use strict";var Yv=ha(),Wv=Object;Dc.exports=function(i){return Wv(Yv(i))}});var Be=f((TL,Oc)=>{"use strict";var Qv=oe(),zv=jr(),Kv=Qv({}.hasOwnProperty);Oc.exports=Object.hasOwn||function(e,t){return Kv(zv(e),t)}});var Pn=f((IL,Bc)=>{"use strict";var Jv=oe(),Xv=0,Zv=Math.random(),ey=Jv(1 .toString);Bc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+ey(++Xv+Zv,36)}});var ie=f((EL,_c)=>{"use strict";var ty=ee(),ry=xn(),Vc=Be(),iy=Pn(),ay=gn(),sy=vn(),or=ty.Symbol,An=ry("wks"),ny=sy?or.for||or:or&&or.withoutSetter||iy;_c.exports=function(i){return Vc(An,i)||(An[i]=ay&&Vc(or,i)?or[i]:ny("Symbol."+i)),An[i]}});var Uc=f((xL,qc)=>{"use strict";var oy=ue(),Nc=je(),Fc=yn(),uy=Hr(),ly=Pc(),cy=ie(),dy=TypeError,py=cy("toPrimitive");qc.exports=function(i,e){if(!Nc(i)||Fc(i))return i;var t=uy(i,py),r;if(t){if(e===void 0&&(e="default"),r=oy(t,i,e),!Nc(r)||Fc(r))return r;throw dy("Can't convert object to primitive value")}return e===void 0&&(e="number"),ly(i,e)}});var ya=f((PL,Hc)=>{"use strict";var hy=Uc(),fy=yn();Hc.exports=function(i){var e=hy(i,"string");return fy(e)?e:e+""}});var Ct=f(Gc=>{"use strict";var my=Ge(),by=pn(),Sy=hn(),Ta=Me(),jc=ya(),gy=TypeError,wn=Object.defineProperty,vy=Object.getOwnPropertyDescriptor,kn="enumerable",Rn="configurable",$n="writable";Gc.f=my?Sy?function(e,t,r){if(Ta(e),t=jc(t),Ta(r),typeof e=="function"&&t==="prototype"&&"value"in r&&$n in r&&!r[$n]){var a=vy(e,t);a&&a[$n]&&(e[t]=r.value,r={configurable:Rn in r?r[Rn]:a[Rn],enumerable:kn in r?r[kn]:a[kn],writable:!1})}return wn(e,t,r)}:wn:function(e,t,r){if(Ta(e),t=jc(t),Ta(r),by)try{return wn(e,t,r)}catch(a){}if("get"in r||"set"in r)throw gy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Gr=f((wL,Yc)=>{"use strict";Yc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Mt=f((kL,Wc)=>{"use strict";var yy=Ge(),Ty=Ct(),Iy=Gr();Wc.exports=yy?function(i,e,t){return Ty.f(i,e,Iy(1,t))}:function(i,e,t){return i[e]=t,i}});var Ia=f((RL,zc)=>{"use strict";var Ey=xn(),xy=Pn(),Qc=Ey("keys");zc.exports=function(i){return Qc[i]||(Qc[i]=xy(i))}});var Ea=f(($L,Kc)=>{"use strict";Kc.exports={}});var Dn=f((LL,Zc)=>{"use strict";var Py=zl(),Xc=ee(),Ay=je(),wy=Mt(),Ln=Be(),Cn=va(),ky=Ia(),Ry=Ea(),Jc="Object already initialized",Mn=Xc.TypeError,$y=Xc.WeakMap,xa,Yr,Pa,Ly=function(i){return Pa(i)?Yr(i):xa(i,{})},Cy=function(i){return function(e){var t;if(!Ay(e)||(t=Yr(e)).type!==i)throw Mn("Incompatible receiver, "+i+" required");return t}};Py||Cn.state?(Ve=Cn.state||(Cn.state=new $y),Ve.get=Ve.get,Ve.has=Ve.has,Ve.set=Ve.set,xa=function(i,e){if(Ve.has(i))throw Mn(Jc);return e.facade=i,Ve.set(i,e),e},Yr=function(i){return Ve.get(i)||{}},Pa=function(i){return Ve.has(i)}):(Dt=ky("state"),Ry[Dt]=!0,xa=function(i,e){if(Ln(i,Dt))throw Mn(Jc);return e.facade=i,wy(i,Dt,e),e},Yr=function(i){return Ln(i,Dt)?i[Dt]:{}},Pa=function(i){return Ln(i,Dt)});var Ve,Dt;Zc.exports={set:xa,get:Yr,has:Pa,enforce:Ly,getterFor:Cy}});var On=f((CL,id)=>{"use strict";var My=Nr(),rd=Function.prototype,ed=rd.apply,td=rd.call;id.exports=typeof Reflect=="object"&&Reflect.apply||(My?td.bind(ed):function(){return td.apply(ed,arguments)})});var Bn=f((ML,ad)=>{"use strict";var Dy=ar(),Oy=oe();ad.exports=function(i){if(Dy(i)==="Function")return Oy(i)}});var ud=f(od=>{"use strict";var sd={}.propertyIsEnumerable,nd=Object.getOwnPropertyDescriptor,By=nd&&!sd.call({1:2},1);od.f=By?function(e){var t=nd(this,e);return!!t&&t.enumerable}:sd});var Vn=f(cd=>{"use strict";var Vy=Ge(),_y=ue(),Ny=ud(),Fy=Gr(),qy=nr(),Uy=ya(),Hy=Be(),jy=pn(),ld=Object.getOwnPropertyDescriptor;cd.f=Vy?ld:function(e,t){if(e=qy(e),t=Uy(t),jy)try{return ld(e,t)}catch(r){}if(Hy(e,t))return Fy(!_y(Ny.f,e,t),e[t])}});var _n=f((BL,dd)=>{"use strict";var Gy=ye(),Yy=W(),Wy=/#|\.prototype\./,Wr=function(i,e){var t=zy[Qy(i)];return t==Jy?!0:t==Ky?!1:Yy(e)?Gy(e):!!e},Qy=Wr.normalize=function(i){return String(i).replace(Wy,".").toLowerCase()},zy=Wr.data={},Ky=Wr.NATIVE="N",Jy=Wr.POLYFILL="P";dd.exports=Wr});var Qr=f((VL,hd)=>{"use strict";var pd=Bn(),Xy=ze(),Zy=Nr(),eT=pd(pd.bind);hd.exports=function(i,e){return Xy(i),e===void 0?i:Zy?eT(i,e):function(){return i.apply(e,arguments)}}});var xe=f((_L,md)=>{"use strict";var Aa=ee(),tT=On(),rT=Bn(),iT=W(),aT=Vn().f,sT=_n(),ur=Sa(),nT=Qr(),lr=Mt(),fd=Be(),oT=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 tT(i,this,arguments)};return e.prototype=i.prototype,e};md.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Aa:a?Aa[t]:(Aa[t]||{}).prototype,o=r?ur:ur[t]||lr(ur,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,S,v;for(p in e)l=sT(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&fd(n,p),m=o[p],c&&(i.dontCallGetSet?(v=aT(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(c&&typeof m==typeof h)&&(i.bind&&c?S=nT(h,Aa):i.wrap&&c?S=oT(h):s&&iT(h)?S=rT(h):S=h,(i.sham||h&&h.sham||m&&m.sham)&&lr(S,"sham",!0),lr(o,p,S),s&&(d=t+"Prototype",fd(ur,d)||lr(ur,d,{}),lr(ur[d],p,h),i.real&&u&&(l||!u[p])&&lr(u,p,h)))}});var gd=f((NL,Sd)=>{"use strict";var Nn=Ge(),uT=Be(),bd=Function.prototype,lT=Nn&&Object.getOwnPropertyDescriptor,Fn=uT(bd,"name"),cT=Fn&&function(){}.name==="something",dT=Fn&&(!Nn||Nn&&lT(bd,"name").configurable);Sd.exports={EXISTS:Fn,PROPER:cT,CONFIGURABLE:dT}});var yd=f((FL,vd)=>{"use strict";var pT=Math.ceil,hT=Math.floor;vd.exports=Math.trunc||function(e){var t=+e;return(t>0?hT:pT)(t)}});var wa=f((qL,Td)=>{"use strict";var fT=yd();Td.exports=function(i){var e=+i;return e!==e||e===0?0:fT(e)}});var Ed=f((UL,Id)=>{"use strict";var mT=wa(),bT=Math.max,ST=Math.min;Id.exports=function(i,e){var t=mT(i);return t<0?bT(t+e,0):ST(t,e)}});var Pd=f((HL,xd)=>{"use strict";var gT=wa(),vT=Math.min;xd.exports=function(i){return i>0?vT(gT(i),9007199254740991):0}});var ka=f((jL,Ad)=>{"use strict";var yT=Pd();Ad.exports=function(i){return yT(i.length)}});var Rd=f((GL,kd)=>{"use strict";var TT=nr(),IT=Ed(),ET=ka(),wd=function(i){return function(e,t,r){var a=TT(e),s=ET(a),n=IT(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}};kd.exports={includes:wd(!0),indexOf:wd(!1)}});var Cd=f((YL,Ld)=>{"use strict";var xT=oe(),qn=Be(),PT=nr(),AT=Rd().indexOf,wT=Ea(),$d=xT([].push);Ld.exports=function(i,e){var t=PT(i),r=0,a=[],s;for(s in t)!qn(wT,s)&&qn(t,s)&&$d(a,s);for(;e.length>r;)qn(t,s=e[r++])&&(~AT(a,s)||$d(a,s));return a}});var Un=f((WL,Md)=>{"use strict";Md.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Od=f((QL,Dd)=>{"use strict";var kT=Cd(),RT=Un();Dd.exports=Object.keys||function(e){return kT(e,RT)}});var Vd=f(Bd=>{"use strict";var $T=Ge(),LT=hn(),CT=Ct(),MT=Me(),DT=nr(),OT=Od();Bd.f=$T&&!LT?Object.defineProperties:function(e,t){MT(e);for(var r=DT(t),a=OT(t),s=a.length,n=0,o;s>n;)CT.f(e,o=a[n++],r[o]);return e}});var Hn=f((KL,_d)=>{"use strict";var BT=Qe();_d.exports=BT("document","documentElement")});var Wn=f((JL,Gd)=>{"use strict";var VT=Me(),_T=Vd(),Nd=Un(),NT=Ea(),FT=Hn(),qT=ma(),UT=Ia(),Fd=">",qd="<",Gn="prototype",Yn="script",Hd=UT("IE_PROTO"),jn=function(){},jd=function(i){return qd+Yn+Fd+i+qd+"/"+Yn+Fd},Ud=function(i){i.write(jd("")),i.close();var e=i.parentWindow.Object;return i=null,e},HT=function(){var i=qT("iframe"),e="java"+Yn+":",t;return i.style.display="none",FT.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(jd("document.F=Object")),t.close(),t.F},Ra,$a=function(){try{Ra=new ActiveXObject("htmlfile")}catch(e){}$a=typeof document!="undefined"?document.domain&&Ra?Ud(Ra):HT():Ud(Ra);for(var i=Nd.length;i--;)delete $a[Gn][Nd[i]];return $a()};NT[Hd]=!0;Gd.exports=Object.create||function(e,t){var r;return e!==null?(jn[Gn]=VT(e),r=new jn,jn[Gn]=null,r[Hd]=e):r=$a(),t===void 0?r:_T.f(r,t)}});var Wd=f((XL,Yd)=>{"use strict";var jT=ye();Yd.exports=!jT(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var zn=f((ZL,zd)=>{"use strict";var GT=Be(),YT=W(),WT=jr(),QT=Ia(),zT=Wd(),Qd=QT("IE_PROTO"),Qn=Object,KT=Qn.prototype;zd.exports=zT?Qn.getPrototypeOf:function(i){var e=WT(i);if(GT(e,Qd))return e[Qd];var t=e.constructor;return YT(t)&&e instanceof t?t.prototype:e instanceof Qn?KT:null}});var cr=f((eC,Kd)=>{"use strict";var JT=Mt();Kd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:JT(i,e,t),i}});var Zn=f((tC,Zd)=>{"use strict";var XT=ye(),ZT=W(),eI=je(),tI=Wn(),Jd=zn(),rI=cr(),iI=ie(),aI=Oe(),Xn=iI("iterator"),Xd=!1,Ke,Kn,Jn;[].keys&&(Jn=[].keys(),"next"in Jn?(Kn=Jd(Jd(Jn)),Kn!==Object.prototype&&(Ke=Kn)):Xd=!0);var sI=!eI(Ke)||XT(function(){var i={};return Ke[Xn].call(i)!==i});sI?Ke={}:aI&&(Ke=tI(Ke));ZT(Ke[Xn])||rI(Ke,Xn,function(){return this});Zd.exports={IteratorPrototype:Ke,BUGGY_SAFARI_ITERATORS:Xd}});var La=f((rC,tp)=>{"use strict";var nI=ie(),oI=nI("toStringTag"),ep={};ep[oI]="z";tp.exports=String(ep)==="[object z]"});var dr=f((iC,rp)=>{"use strict";var uI=La(),lI=W(),Ca=ar(),cI=ie(),dI=cI("toStringTag"),pI=Object,hI=Ca(function(){return arguments}())=="Arguments",fI=function(i,e){try{return i[e]}catch(t){}};rp.exports=uI?Ca:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=fI(e=pI(i),dI))=="string"?t:hI?Ca(e):(r=Ca(e))=="Object"&&lI(e.callee)?"Arguments":r}});var ap=f((aC,ip)=>{"use strict";var mI=La(),bI=dr();ip.exports=mI?{}.toString:function(){return"[object "+bI(this)+"]"}});var Ma=f((sC,np)=>{"use strict";var SI=La(),gI=Ct().f,vI=Mt(),yI=Be(),TI=ap(),II=ie(),sp=II("toStringTag");np.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;yI(a,sp)||gI(a,sp,{configurable:!0,value:e}),r&&!SI&&vI(a,"toString",TI)}}});var up=f((nC,op)=>{"use strict";var EI=Zn().IteratorPrototype,xI=Wn(),PI=Gr(),AI=Ma(),wI=Lt(),kI=function(){return this};op.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=xI(EI,{next:PI(+!r,t)}),AI(i,a,!1,!0),wI[a]=kI,i}});var cp=f((oC,lp)=>{"use strict";var RI=oe(),$I=ze();lp.exports=function(i,e,t){try{return RI($I(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var pp=f((uC,dp)=>{"use strict";var LI=W(),CI=String,MI=TypeError;dp.exports=function(i){if(typeof i=="object"||LI(i))return i;throw MI("Can't set "+CI(i)+" as a prototype")}});var eo=f((lC,hp)=>{"use strict";var DI=cp(),OI=Me(),BI=pp();hp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=DI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return OI(a),BI(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var xp=f((cC,Ep)=>{"use strict";var VI=xe(),_I=ue(),Da=Oe(),Tp=gd(),NI=W(),FI=up(),fp=zn(),mp=eo(),qI=Ma(),UI=Mt(),to=cr(),HI=ie(),bp=Lt(),Ip=Zn(),jI=Tp.PROPER,GI=Tp.CONFIGURABLE,Sp=Ip.IteratorPrototype,Oa=Ip.BUGGY_SAFARI_ITERATORS,zr=HI("iterator"),gp="keys",Kr="values",vp="entries",yp=function(){return this};Ep.exports=function(i,e,t,r,a,s,n){FI(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Oa&&v in c)return c[v];switch(v){case gp:return function(){return new t(this,v)};case Kr:return function(){return new t(this,v)};case vp:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[zr]||c["@@iterator"]||a&&c[a],p=!Oa&&d||o(a),h=e=="Array"&&c.entries||d,m,b,S;if(h&&(m=fp(h.call(new i)),m!==Object.prototype&&m.next&&(!Da&&fp(m)!==Sp&&(mp?mp(m,Sp):NI(m[zr])||to(m,zr,yp)),qI(m,u,!0,!0),Da&&(bp[u]=yp))),jI&&a==Kr&&d&&d.name!==Kr&&(!Da&&GI?UI(c,"name",Kr):(l=!0,p=function(){return _I(d,this)})),a)if(b={values:o(Kr),keys:s?p:o(gp),entries:o(vp)},n)for(S in b)(Oa||l||!(S in c))&&to(c,S,b[S]);else VI({target:e,proto:!0,forced:Oa||l},b);return(!Da||n)&&c[zr]!==p&&to(c,zr,p,{name:a}),bp[e]=p,b}});var Ap=f((dC,Pp)=>{"use strict";Pp.exports=function(i,e){return{value:i,done:e}}});var io=f((pC,Lp)=>{"use strict";var YI=nr(),ro=un(),wp=Lt(),Rp=Dn(),WI=Ct().f,QI=xp(),Ba=Ap(),zI=Oe(),KI=Ge(),$p="Array Iterator",JI=Rp.set,XI=Rp.getterFor($p);Lp.exports=QI(Array,"Array",function(i,e){JI(this,{type:$p,target:YI(i),index:0,kind:e})},function(){var i=XI(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Ba(void 0,!0)):t=="keys"?Ba(r,!1):t=="values"?Ba(e[r],!1):Ba([r,e[r]],!1)},"values");var kp=wp.Arguments=wp.Array;ro("keys");ro("values");ro("entries");if(!zI&&KI&&kp.name!=="values")try{WI(kp,"name",{value:"values"})}catch(i){}});var Mp=f((hC,Cp)=>{"use strict";var ZI=ie(),eE=Lt(),tE=ZI("iterator"),rE=Array.prototype;Cp.exports=function(i){return i!==void 0&&(eE.Array===i||rE[tE]===i)}});var ao=f((fC,Op)=>{"use strict";var iE=dr(),Dp=Hr(),aE=sr(),sE=Lt(),nE=ie(),oE=nE("iterator");Op.exports=function(i){if(!aE(i))return Dp(i,oE)||Dp(i,"@@iterator")||sE[iE(i)]}});var Vp=f((mC,Bp)=>{"use strict";var uE=ue(),lE=ze(),cE=Me(),dE=Ur(),pE=ao(),hE=TypeError;Bp.exports=function(i,e){var t=arguments.length<2?pE(i):e;if(lE(t))return cE(uE(t,i));throw hE(dE(i)+" is not iterable")}});var Fp=f((bC,Np)=>{"use strict";var fE=ue(),_p=Me(),mE=Hr();Np.exports=function(i,e,t){var r,a;_p(i);try{if(r=mE(i,"return"),!r){if(e==="throw")throw t;return t}r=fE(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return _p(r),t}});var _a=f((SC,jp)=>{"use strict";var bE=Qr(),SE=ue(),gE=Me(),vE=Ur(),yE=Mp(),TE=ka(),qp=Fr(),IE=Vp(),EE=ao(),Up=Fp(),xE=TypeError,Va=function(i,e){this.stopped=i,this.result=e},Hp=Va.prototype;jp.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=bE(e,r),l,c,d,p,h,m,b,S=function(I){return l&&Up(l,"normal",I),new Va(!0,I)},v=function(I){return a?(gE(I),o?u(I[0],I[1],S):u(I[0],I[1])):o?u(I,S):u(I)};if(s)l=i.iterator;else if(n)l=i;else{if(c=EE(i),!c)throw xE(vE(i)+" is not iterable");if(yE(c)){for(d=0,p=TE(i);p>d;d++)if(h=v(i[d]),h&&qp(Hp,h))return h;return new Va(!1)}l=IE(i,c)}for(m=s?i.next:l.next;!(b=SE(m,l)).done;){try{h=v(b.value)}catch(I){Up(l,"throw",I)}if(typeof h=="object"&&h&&qp(Hp,h))return h}return new Va(!1)}});var Yp=f((gC,Gp)=>{"use strict";var PE=ya(),AE=Ct(),wE=Gr();Gp.exports=function(i,e,t){var r=PE(e);r in i?AE.f(i,r,wE(0,t)):i[r]=t}});var Wp=f(()=>{"use strict";var kE=xe(),RE=_a(),$E=Yp();kE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return RE(e,function(r,a){$E(t,r,a)},{AS_ENTRIES:!0}),t}})});var zp=f((TC,Qp)=>{"use strict";io();Wp();var LE=Sa();Qp.exports=LE.Object.fromEntries});var Jp=f((IC,Kp)=>{"use strict";Kp.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 eh=f(()=>{"use strict";io();var CE=Jp(),ME=ee(),DE=dr(),OE=Mt(),Xp=Lt(),BE=ie(),Zp=BE("toStringTag");for(Na in CE)so=ME[Na],Fa=so&&so.prototype,Fa&&DE(Fa)!==Zp&&OE(Fa,Zp,Na),Xp[Na]=Xp.Array;var so,Fa,Na});var rh=f((PC,th)=>{"use strict";var VE=zp();eh();th.exports=VE});var no=f((AC,ih)=>{"use strict";var _E=rh();ih.exports=_E});var ah=f(()=>{"use strict"});var Jr=f((RC,sh)=>{"use strict";var NE=ar();sh.exports=typeof process!="undefined"&&NE(process)=="process"});var oh=f(($C,nh)=>{"use strict";var FE=Ct();nh.exports=function(i,e,t){return FE.f(i,e,t)}});var ch=f((LC,lh)=>{"use strict";var qE=Qe(),UE=oh(),HE=ie(),jE=Ge(),uh=HE("species");lh.exports=function(i){var e=qE(i);jE&&e&&!e[uh]&&UE(e,uh,{configurable:!0,get:function(){return this}})}});var ph=f((CC,dh)=>{"use strict";var GE=Fr(),YE=TypeError;dh.exports=function(i,e){if(GE(e,i))return i;throw YE("Incorrect invocation")}});var uo=f((MC,hh)=>{"use strict";var WE=oe(),QE=W(),oo=va(),zE=WE(Function.toString);QE(oo.inspectSource)||(oo.inspectSource=function(i){return zE(i)});hh.exports=oo.inspectSource});var vh=f((DC,gh)=>{"use strict";var KE=oe(),JE=ye(),fh=W(),XE=dr(),ZE=Qe(),ex=uo(),mh=function(){},tx=[],bh=ZE("Reflect","construct"),lo=/^\s*(?:class|function)\b/,rx=KE(lo.exec),ix=!lo.exec(mh),Xr=function(e){if(!fh(e))return!1;try{return bh(mh,tx,e),!0}catch(t){return!1}},Sh=function(e){if(!fh(e))return!1;switch(XE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ix||!!rx(lo,ex(e))}catch(t){return!0}};Sh.sham=!0;gh.exports=!bh||JE(function(){var i;return Xr(Xr.call)||!Xr(Object)||!Xr(function(){i=!0})||i})?Sh:Xr});var Th=f((OC,yh)=>{"use strict";var ax=vh(),sx=Ur(),nx=TypeError;yh.exports=function(i){if(ax(i))return i;throw nx(sx(i)+" is not a constructor")}});var co=f((BC,Eh)=>{"use strict";var Ih=Me(),ox=Th(),ux=sr(),lx=ie(),cx=lx("species");Eh.exports=function(i,e){var t=Ih(i).constructor,r;return t===void 0||ux(r=Ih(t)[cx])?e:ox(r)}});var Ph=f((VC,xh)=>{"use strict";var dx=oe();xh.exports=dx([].slice)});var wh=f((_C,Ah)=>{"use strict";var px=TypeError;Ah.exports=function(i,e){if(i<e)throw px("Not enough arguments");return i}});var po=f((NC,kh)=>{"use strict";var hx=qr();kh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(hx)});var To=f((FC,Vh)=>{"use strict";var Te=ee(),fx=On(),mx=Qr(),Rh=W(),bx=Be(),Bh=ye(),$h=Hn(),Sx=Ph(),Lh=ma(),gx=wh(),vx=po(),yx=Jr(),go=Te.setImmediate,vo=Te.clearImmediate,Tx=Te.process,ho=Te.Dispatch,Ix=Te.Function,Ch=Te.MessageChannel,Ex=Te.String,fo=0,Zr={},Mh="onreadystatechange",ei,Ot,mo,bo;Bh(function(){ei=Te.location});var yo=function(i){if(bx(Zr,i)){var e=Zr[i];delete Zr[i],e()}},So=function(i){return function(){yo(i)}},Dh=function(i){yo(i.data)},Oh=function(i){Te.postMessage(Ex(i),ei.protocol+"//"+ei.host)};(!go||!vo)&&(go=function(e){gx(arguments.length,1);var t=Rh(e)?e:Ix(e),r=Sx(arguments,1);return Zr[++fo]=function(){fx(t,void 0,r)},Ot(fo),fo},vo=function(e){delete Zr[e]},yx?Ot=function(i){Tx.nextTick(So(i))}:ho&&ho.now?Ot=function(i){ho.now(So(i))}:Ch&&!vx?(mo=new Ch,bo=mo.port2,mo.port1.onmessage=Dh,Ot=mx(bo.postMessage,bo)):Te.addEventListener&&Rh(Te.postMessage)&&!Te.importScripts&&ei&&ei.protocol!=="file:"&&!Bh(Oh)?(Ot=Oh,Te.addEventListener("message",Dh,!1)):Mh in Lh("script")?Ot=function(i){$h.appendChild(Lh("script"))[Mh]=function(){$h.removeChild(this),yo(i)}}:Ot=function(i){setTimeout(So(i),0)});Vh.exports={set:go,clear:vo}});var Io=f((qC,Nh)=>{"use strict";var _h=function(){this.head=null,this.tail=null};_h.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}}};Nh.exports=_h});var qh=f((UC,Fh)=>{"use strict";var xx=qr();Fh.exports=/ipad|iphone|ipod/i.test(xx)&&typeof Pebble!="undefined"});var Hh=f((HC,Uh)=>{"use strict";var Px=qr();Uh.exports=/web0s(?!.*chrome)/i.test(Px)});var Jh=f((jC,Kh)=>{"use strict";var Bt=ee(),jh=Qr(),Ax=Vn().f,Eo=To().set,wx=Io(),kx=po(),Rx=qh(),$x=Hh(),xo=Jr(),Gh=Bt.MutationObserver||Bt.WebKitMutationObserver,Yh=Bt.document,Wh=Bt.process,qa=Bt.Promise,Qh=Ax(Bt,"queueMicrotask"),wo=Qh&&Qh.value,pr,Po,Ao,Ua,zh;wo||(ti=new wx,ri=function(){var i,e;for(xo&&(i=Wh.domain)&&i.exit();e=ti.get();)try{e()}catch(t){throw ti.head&&pr(),t}i&&i.enter()},!kx&&!xo&&!$x&&Gh&&Yh?(Po=!0,Ao=Yh.createTextNode(""),new Gh(ri).observe(Ao,{characterData:!0}),pr=function(){Ao.data=Po=!Po}):!Rx&&qa&&qa.resolve?(Ua=qa.resolve(void 0),Ua.constructor=qa,zh=jh(Ua.then,Ua),pr=function(){zh(ri)}):xo?pr=function(){Wh.nextTick(ri)}:(Eo=jh(Eo,Bt),pr=function(){Eo(ri)}),wo=function(i){ti.head||pr(),ti.add(i)});var ti,ri;Kh.exports=wo});var Zh=f((GC,Xh)=>{"use strict";Xh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var Ha=f((YC,ef)=>{"use strict";ef.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Vt=f((WC,tf)=>{"use strict";var Lx=ee();tf.exports=Lx.Promise});var ko=f((QC,rf)=>{"use strict";rf.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var sf=f((zC,af)=>{"use strict";var Cx=ko(),Mx=Jr();af.exports=!Cx&&!Mx&&typeof window=="object"&&typeof document=="object"});var hr=f((KC,uf)=>{"use strict";var Dx=ee(),ii=Vt(),Ox=W(),Bx=_n(),Vx=uo(),_x=ie(),Nx=sf(),Fx=ko(),qx=Oe(),Ro=Sn(),nf=ii&&ii.prototype,Ux=_x("species"),$o=!1,of=Ox(Dx.PromiseRejectionEvent),Hx=Bx("Promise",function(){var i=Vx(ii),e=i!==String(ii);if(!e&&Ro===66||qx&&!(nf.catch&&nf.finally))return!0;if(!Ro||Ro<51||!/native code/.test(i)){var t=new ii(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Ux]=r,$o=t.then(function(){})instanceof r,!$o)return!0}return!e&&(Nx||Fx)&&!of});uf.exports={CONSTRUCTOR:Hx,REJECTION_EVENT:of,SUBCLASSING:$o}});var fr=f((JC,cf)=>{"use strict";var lf=ze(),jx=TypeError,Gx=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw jx("Bad Promise constructor");e=r,t=a}),this.resolve=lf(e),this.reject=lf(t)};cf.exports.f=function(i){return new Gx(i)}});var Rf=f(()=>{"use strict";var Yx=xe(),Wx=Oe(),Wa=Jr(),dt=ee(),gr=ue(),df=cr(),pf=eo(),Qx=Ma(),zx=ch(),Kx=ze(),Ya=W(),Jx=je(),Xx=ph(),Zx=co(),Sf=To().set,Oo=Jh(),eP=Zh(),tP=Ha(),rP=Io(),gf=Dn(),Qa=Vt(),Bo=hr(),vf=fr(),za="Promise",yf=Bo.CONSTRUCTOR,iP=Bo.REJECTION_EVENT,aP=Bo.SUBCLASSING,Lo=gf.getterFor(za),sP=gf.set,mr=Qa&&Qa.prototype,_t=Qa,ja=mr,Tf=dt.TypeError,Co=dt.document,Vo=dt.process,Mo=vf.f,nP=Mo,oP=!!(Co&&Co.createEvent&&dt.dispatchEvent),If="unhandledrejection",uP="rejectionhandled",hf=0,Ef=1,lP=2,_o=1,xf=2,Ga,ff,cP,mf,Pf=function(i){var e;return Jx(i)&&Ya(e=i.then)?e:!1},Af=function(i,e){var t=e.value,r=e.state==Ef,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===xf&&pP(e),e.rejection=_o),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(Tf("Promise-chain cycle")):(l=Pf(u))?gr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},wf=function(i,e){i.notified||(i.notified=!0,Oo(function(){for(var t=i.reactions,r;r=t.get();)Af(r,i);i.notified=!1,e&&!i.rejection&&dP(i)}))},kf=function(i,e,t){var r,a;oP?(r=Co.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),dt.dispatchEvent(r)):r={promise:e,reason:t},!iP&&(a=dt["on"+i])?a(r):i===If&&eP("Unhandled promise rejection",t)},dP=function(i){gr(Sf,dt,function(){var e=i.facade,t=i.value,r=bf(i),a;if(r&&(a=tP(function(){Wa?Vo.emit("unhandledRejection",t,e):kf(If,e,t)}),i.rejection=Wa||bf(i)?xf:_o,a.error))throw a.value})},bf=function(i){return i.rejection!==_o&&!i.parent},pP=function(i){gr(Sf,dt,function(){var e=i.facade;Wa?Vo.emit("rejectionHandled",e):kf(uP,e,i.value)})},br=function(i,e,t){return function(r){i(e,r,t)}},Sr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=lP,wf(i,!0))},Do=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Tf("Promise can't be resolved itself");var r=Pf(e);r?Oo(function(){var a={done:!1};try{gr(r,e,br(Do,a,i),br(Sr,a,i))}catch(s){Sr(a,s,i)}}):(i.value=e,i.state=Ef,wf(i,!1))}catch(a){Sr({done:!1},a,i)}}};if(yf&&(_t=function(e){Xx(this,ja),Kx(e),gr(Ga,this);var t=Lo(this);try{e(br(Do,t),br(Sr,t))}catch(r){Sr(t,r)}},ja=_t.prototype,Ga=function(e){sP(this,{type:za,done:!1,notified:!1,parent:!1,reactions:new rP,rejection:!1,state:hf,value:void 0})},Ga.prototype=df(ja,"then",function(e,t){var r=Lo(this),a=Mo(Zx(this,_t));return r.parent=!0,a.ok=Ya(e)?e:!0,a.fail=Ya(t)&&t,a.domain=Wa?Vo.domain:void 0,r.state==hf?r.reactions.add(a):Oo(function(){Af(a,r)}),a.promise}),ff=function(){var i=new Ga,e=Lo(i);this.promise=i,this.resolve=br(Do,e),this.reject=br(Sr,e)},vf.f=Mo=function(i){return i===_t||i===cP?new ff(i):nP(i)},!Wx&&Ya(Qa)&&mr!==Object.prototype)){mf=mr.then,aP||df(mr,"then",function(e,t){var r=this;return new _t(function(a,s){gr(mf,r,a,s)}).then(e,t)},{unsafe:!0});try{delete mr.constructor}catch(i){}pf&&pf(mr,ja)}Yx({global:!0,constructor:!0,wrap:!0,forced:yf},{Promise:_t});Qx(_t,za,!1,!0);zx(za)});var Df=f((eM,Mf)=>{"use strict";var hP=ie(),Lf=hP("iterator"),Cf=!1;try{$f=0,No={next:function(){return{done:!!$f++}},return:function(){Cf=!0}},No[Lf]=function(){return this},Array.from(No,function(){throw 2})}catch(i){}var $f,No;Mf.exports=function(i,e){if(!e&&!Cf)return!1;var t=!1;try{var r={};r[Lf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var Fo=f((tM,Of)=>{"use strict";var fP=Vt(),mP=Df(),bP=hr().CONSTRUCTOR;Of.exports=bP||!mP(function(i){fP.all(i).then(void 0,function(){})})});var Bf=f(()=>{"use strict";var SP=xe(),gP=ue(),vP=ze(),yP=fr(),TP=Ha(),IP=_a(),EP=Fo();SP({target:"Promise",stat:!0,forced:EP},{all:function(e){var t=this,r=yP.f(t),a=r.resolve,s=r.reject,n=TP(function(){var o=vP(t.resolve),u=[],l=0,c=1;IP(e,function(d){var p=l++,h=!1;c++,gP(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 _f=f(()=>{"use strict";var xP=xe(),PP=Oe(),AP=hr().CONSTRUCTOR,Uo=Vt(),wP=Qe(),kP=W(),RP=cr(),Vf=Uo&&Uo.prototype;xP({target:"Promise",proto:!0,forced:AP,real:!0},{catch:function(i){return this.then(void 0,i)}});!PP&&kP(Uo)&&(qo=wP("Promise").prototype.catch,Vf.catch!==qo&&RP(Vf,"catch",qo,{unsafe:!0}));var qo});var Nf=f(()=>{"use strict";var $P=xe(),LP=ue(),CP=ze(),MP=fr(),DP=Ha(),OP=_a(),BP=Fo();$P({target:"Promise",stat:!0,forced:BP},{race:function(e){var t=this,r=MP.f(t),a=r.reject,s=DP(function(){var n=CP(t.resolve);OP(e,function(o){LP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Ff=f(()=>{"use strict";var VP=xe(),_P=ue(),NP=fr(),FP=hr().CONSTRUCTOR;VP({target:"Promise",stat:!0,forced:FP},{reject:function(e){var t=NP.f(this);return _P(t.reject,void 0,e),t.promise}})});var Ho=f((cM,qf)=>{"use strict";var qP=Me(),UP=je(),HP=fr();qf.exports=function(i,e){if(qP(i),UP(e)&&e.constructor===i)return e;var t=HP.f(i),r=t.resolve;return r(e),t.promise}});var jf=f(()=>{"use strict";var jP=xe(),GP=Qe(),Uf=Oe(),YP=Vt(),Hf=hr().CONSTRUCTOR,WP=Ho(),QP=GP("Promise"),zP=Uf&&!Hf;jP({target:"Promise",stat:!0,forced:Uf||Hf},{resolve:function(e){return WP(zP&&this===QP?YP:this,e)}})});var Gf=f(()=>{"use strict";Rf();Bf();_f();Nf();Ff();jf()});var zf=f(()=>{"use strict";var KP=xe(),JP=Oe(),Ka=Vt(),XP=ye(),Wf=Qe(),Qf=W(),ZP=co(),Yf=Ho(),eA=cr(),Go=Ka&&Ka.prototype,tA=!!Ka&&XP(function(){Go.finally.call({then:function(){}},function(){})});KP({target:"Promise",proto:!0,real:!0,forced:tA},{finally:function(i){var e=ZP(this,Wf("Promise")),t=Qf(i);return this.then(t?function(r){return Yf(e,i()).then(function(){return r})}:i,t?function(r){return Yf(e,i()).then(function(){throw r})}:i)}});!JP&&Qf(Ka)&&(jo=Wf("Promise").prototype.finally,Go.finally!==jo&&eA(Go,"finally",jo,{unsafe:!0}));var jo});var Ja=f((SM,Kf)=>{"use strict";var rA=Qe();Kf.exports=rA});var Xf=f((gM,Jf)=>{"use strict";ah();Gf();zf();var iA=Ja();Jf.exports=iA("Promise","finally")});var em=f((vM,Zf)=>{"use strict";var aA=Xf();Zf.exports=aA});var Xa=f((yM,tm)=>{"use strict";var sA=em();tm.exports=sA});var Pm=f(()=>{"use strict";var LA=xe(),CA=jr(),MA=ka(),DA=wa(),OA=un();LA({target:"Array",proto:!0},{at:function(e){var t=CA(this),r=MA(t),a=DA(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});OA("at")});var wm=f((RD,Am)=>{"use strict";Pm();var BA=Ja();Am.exports=BA("Array","at")});var Rm=f(($D,km)=>{"use strict";var VA=wm();km.exports=VA});var ui=f((LD,$m)=>{"use strict";var _A=Rm();$m.exports=_A});var Lb=f(()=>{"use strict"});var Cb=f(()=>{"use strict"});var Db=f((VV,Mb)=>{"use strict";var Jw=je(),Xw=ar(),Zw=ie(),ek=Zw("match");Mb.exports=function(i){var e;return Jw(i)&&((e=i[ek])!==void 0?!!e:Xw(i)=="RegExp")}});var Bb=f((_V,Ob)=>{"use strict";var tk=dr(),rk=String;Ob.exports=function(i){if(tk(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return rk(i)}});var _b=f((NV,Vb)=>{"use strict";var ik=Me();Vb.exports=function(){var i=ik(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 qb=f((FV,Fb)=>{"use strict";var ak=ue(),sk=Be(),nk=Fr(),ok=_b(),Nb=RegExp.prototype;Fb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Nb)&&!sk(i,"flags")&&nk(Nb,i)?ak(ok,i):e}});var Hb=f((qV,Ub)=>{"use strict";var yu=oe(),uk=jr(),lk=Math.floor,gu=yu("".charAt),ck=yu("".replace),vu=yu("".slice),dk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pk=/\$([$&'`]|\d{1,2})/g;Ub.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=pk;return a!==void 0&&(a=uk(a),u=dk),ck(s,u,function(l,c){var d;switch(gu(c,0)){case"$":return"$";case"&":return i;case"`":return vu(e,0,t);case"'":return vu(e,n);case"<":d=a[vu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=lk(p/10);return h===0?l:h<=o?r[h-1]===void 0?gu(c,1):r[h-1]+gu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Qb=f(()=>{"use strict";var hk=xe(),fk=ue(),Tu=oe(),jb=ha(),mk=W(),bk=sr(),Sk=Db(),wr=Bb(),gk=Hr(),vk=qb(),yk=Hb(),Tk=ie(),Ik=Oe(),Ek=Tk("replace"),xk=TypeError,Wb=Tu("".indexOf),Pk=Tu("".replace),Gb=Tu("".slice),Ak=Math.max,Yb=function(i,e,t){return t>i.length?-1:e===""?t:Wb(i,e,t)};hk({target:"String",proto:!0},{replaceAll:function(e,t){var r=jb(this),a,s,n,o,u,l,c,d,p,h=0,m=0,b="";if(!bk(e)){if(a=Sk(e),a&&(s=wr(jb(vk(e))),!~Wb(s,"g")))throw xk("`.replaceAll` does not allow non-global regexes");if(n=gk(e,Ek),n)return fk(n,e,r,t);if(Ik&&a)return Pk(wr(r),e,t)}for(o=wr(r),u=wr(e),l=mk(t),l||(t=wr(t)),c=u.length,d=Ak(1,c),h=Yb(o,u,0);h!==-1;)p=l?wr(t(u,h,o)):yk(u,o,h,[],void 0,t),b+=Gb(o,m,h)+p,m=h+c,h=Yb(o,u,h+d);return m<o.length&&(b+=Gb(o,m)),b}})});var Kb=f((jV,zb)=>{"use strict";Lb();Cb();Qb();var wk=Ja();zb.exports=wk("String","replaceAll")});var Xb=f((GV,Jb)=>{"use strict";var kk=Kb();Jb.exports=kk});var eS=f((YV,Zb)=>{"use strict";var Rk=Xb();Zb.exports=Rk});var Tl="__VERSION__";var ve=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ve||{}),$t=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))($t||{});var ca=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ca||{}),tn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(tn||{});var rn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(rn||{});import{assertNever as wl,assertNonNullable as qg,isNonNullable as da,ValueSubject as an,Subject as Ug,Subscription as Hg,merge as jg,observableFrom as Gg,fromEvent as El,map as xl,tap as Pl,filterChanged as Yg,isNullable as sn,ErrorCategory as Al}from"@vkontakte/videoplayer-shared";var Il=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 pa=class{constructor(e){this.connection$=new an(void 0);this.castState$=new an("NOT_AVAILABLE");this.errorEvent$=new Ug;this.realCastState$=new an("NOT_AVAILABLE");this.subscription=new Hg;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=da((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Il("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Al.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(){da(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();sn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();sn(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(El(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 wl(a.sessionState)}})).add(jg(El(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Pl(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),xl(a=>a.castState)),Gg([r.getCastState()])).pipe(Yg(),xl(Wg),Pl(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=da(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();qg(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(sn(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"?da(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:Al.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Wg=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 wl(i)}};var QS=He(no(),1);var dm=He(Xa(),1);import{assertNever as rm}from"@vkontakte/videoplayer-shared";var ae=(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:rm(t)}return i},Yo=(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:rm(e)}};var E=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as nA,Subject as Za,merge as im}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new Za;this.transitionEnded$=new Za;this.transitionUpdated$=new Za;this.forceChanged$=new Za;this.stateChangeStarted$=im(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=im(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||nA(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}};import{assertNever as oA}from"@vkontakte/videoplayer-shared";var am=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 oA(i)}};import{assertNever as vr,assertNonNullable as Nt,debounce as sm,ErrorCategory as nm,fromEvent as Ft,isNonNullable as om,map as um,merge as lm,observableFrom as uA,Subject as lA,Subscription as Wo,timeout as cA,getHighestQuality as dA}from"@vkontakte/videoplayer-shared";var pA=5,hA=5,fA=500,cm=7e3,ai=class{constructor(e){this.subscription=new Wo;this.loadMediaTimeoutSubscription=new Wo;this.videoState=new C("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:vr(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:vr(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:vr(e)}break}default:vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(am(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 Wo;this.subscription.add(e),this.subscription.add(lm(this.videoState.stateChangeStarted$.pipe(um(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(um(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 lA;e.add(a.pipe(sm(fA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ft(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)>pA)&&a.next(o),s=o})),e.add(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ft(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<hA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:vr(n)}}),t(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Ft(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=lm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,uA(["init"])).pipe(sm(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(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"),E(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"),E(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"&&E(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];Nt(c);let d=dA(Object.keys(c));Nt(d);let p=c[d];Nt(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Nt(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];Nt(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Nt(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];Nt(c),r=ae(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:nm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return vr(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 om(o)&&(n.metadata.title=o),om(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(cA(cm).subscribe(()=>s(`timeout(${cm})`)))});(0,dm.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:nm.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var si=i=>{i.removeAttribute("src"),i.load()};var pm=i=>{try{i.pause(),i.playbackRate=0,si(i),i.remove()}catch(e){console.error(e)}};var Qo=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)}},zo=window.WeakMap?new WeakMap:new Qo,le=i=>{let e=i.querySelector("video"),t=!!e;return e?si(e):(e=document.createElement("video"),i.appendChild(e)),zo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ce=i=>{let e=zo.get(i);zo.delete(i),e?si(i):pm(i)};import{assertNonNullable as ni,isNonNullable as We,isNullable as SA,fromEvent as yr,merge as hm,observableFrom as fm,filterChanged as mm,map as oi,Subject as bm,Subscription as gA,ValueSubject as vA,ErrorCategory as yA}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ko,isNullable as mA,Subscription as bA}from"@vkontakte/videoplayer-shared";var es=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=mA(a),l=new bA;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},Ye=(i,e,t)=>es(e,()=>i.loop,r=>{Ko(r)&&(i.loop=r)},{onError:t}),de=(i,e,t,r)=>es(e,()=>({muted:i.muted,volume:i.volume}),a=>{Ko(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}),Pe=(i,e,t,r)=>es(e,()=>i.playbackRate,a=>{Ko(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),pt=es;var TA=i=>["__",i.language,i.label].join("|"),IA=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Jo=class i{constructor(){this.available$=new bm;this.current$=new vA(void 0);this.error$=new bm;this.subscription=new gA;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:yA.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(pt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,n)=>We(s)&&We(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(oi(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(pt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,n)=>We(s)&&We(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(oi(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(pt(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(pt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ni(this.video);let{textTracks:e}=this.video;this.subscription.add(yr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(hm(yr(e,"addtrack"),yr(e,"removetrack"),fm(["init"])).pipe(oi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),mm((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(hm(yr(e,"change"),fm(["init"])).pipe(oi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),oi(r=>r&&this.htmlTextTrackToITextTrack(r).id),mm()).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(yr(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(yr(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;We(t.align)&&(a.align=t.align),We(t.position)&&(a.position=t.position),We(t.size)&&(a.size=t.size),We(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ni(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:TA(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){ni(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(SA(e)||!IA(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){ni(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){ni(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)}},Ae=Jo;var Xe=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 Sm=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},Xo=i=>{let e=Sm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},gm=i=>{let e=Sm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as we,map as ht,merge as ym,filterChanged as xA,isNonNullable as Tm,Subject as PA,filter as Im,mapTo as Em,combine as AA,once as wA,ErrorCategory as kA,ValueSubject as xm,getCurrentBrowser as RA,CurrentClientBrowser as $A}from"@vkontakte/videoplayer-shared";var EA=3,vm=(i,e,t=EA)=>{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 pe=i=>{let e=g=>we(i,g).pipe(Em(void 0)),r=ym(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>we(i,g))).pipe(ht(g=>g.type==="ended"?i.readyState<2:i.readyState<3),xA()),a=ym(we(i,"progress"),we(i,"timeupdate")).pipe(ht(()=>vm(i.buffered,i.currentTime))),n=RA().browser===$A.Safari?AA({play:e("play").pipe(wA()),playing:e("playing")}).pipe(Em(void 0)):e("playing"),o=we(i,"volumechange").pipe(ht(()=>({muted:i.muted,volume:i.volume}))),u=we(i,"ratechange").pipe(ht(()=>i.playbackRate)),l=we(i,"error").pipe(Im(()=>!!(i.error||i.played.length)),ht(()=>{var y;let g=i.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:kA.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:(y=i.error)!=null?y:void 0}})),c=we(i,"timeupdate").pipe(ht(()=>i.currentTime)),d=new PA,p=.3,h;c.subscribe(g=>{i.loop&&Tm(h)&&Tm(g)&&h>=i.duration-p&&g<=p&&d.next(h),h=g});let m=e("pause").pipe(Im(()=>!i.error&&h!==i.duration)),b=we(i,"enterpictureinpicture"),S=we(i,"leavepictureinpicture"),v=new xm(gm(i));b.subscribe(()=>v.next(!0)),S.subscribe(()=>v.next(!1));let I=new xm(Xo(i));return we(i,"fullscreenchange").pipe(ht(()=>Xo(i))).subscribe(I),{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$:we(i,"durationchange").pipe(ht(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:u,inPiP$:v,inFullscreen$:I}};import{VideoQuality as ft}from"@vkontakte/videoplayer-shared";var mt=i=>{switch(i){case"mobile":return ft.Q_144P;case"lowest":return ft.Q_240P;case"low":return ft.Q_360P;case"sd":case"medium":return ft.Q_480P;case"hd":case"high":return ft.Q_720P;case"fullhd":case"full":return ft.Q_1080P;case"quadhd":case"quad":return ft.Q_1440P;case"ultrahd":case"ultra":return ft.Q_2160P}};var iu=He(ui(),1);import{isNonNullable as bt,isNullable as eu,now as Bm,isHigher as tu,isHigherOrEqual as Dm,isInvariantQuality as Om,isLower as ru,isLowerOrEqual as NA,videoSizeToQuality as FA,assertNotEmptyArray as qA}from"@vkontakte/videoplayer-shared";var Zo=!1,Ze={},Lm=i=>{Zo=i},Cm=()=>{Ze={}},Mm=i=>{i(Ze)},li=(i,e)=>{var t;Zo&&(Ze.meta=(t=Ze.meta)!=null?t:{},Ze.meta[i]=e)},se=class{constructor(e){this.name=e}next(e){var r,a;if(!Zo)return;Ze.series=(r=Ze.series)!=null?r:{};let t=(a=Ze.series[this.name])!=null?a:[];t.push([Date.now(),e]),Ze.series[this.name]=t}};var UA=new se("best_bitrate"),HA=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,ts=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Bm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},jA='Assertion "ABR Tracks is empty array" failed',GA=(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 H,R,A,j,Q;qA(i,jA);let p=r.usePixelRatio&&(H=window.devicePixelRatio)!=null?H: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&&FA(h),b=r.considerPlaybackRate&&bt(o)?o:1,S=i.filter(w=>!Om(w.quality)).sort((w,x)=>tu(w.quality,x.quality)?-1:1),v=(R=(0,iu.default)(S,-1))==null?void 0:R.quality,I=(A=(0,iu.default)(S,0))==null?void 0:A.quality,T=eu(a)||bt(a.min)&&bt(a.max)&&ru(a.max,a.min)||bt(a.min)&&I&&tu(a.min,I)||bt(a.max)&&v&&ru(a.max,v),g=b*HA(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),y={},L=S.filter(w=>(m?ru(w.quality,m):!0)?(bt(t)&&isFinite(t)&&bt(w.bitrate)?t-s>=w.bitrate*g:!0)?r.lazyQualitySwitch&&bt(r.minBufferToSwitchUp)&&u&&!Om(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&tu(w.quality,u.quality)?(y[w.quality]="Buffer",!1):!!c&&Dm(w.quality,c)?(y[w.quality]="DroppedFramesLimit",!1):T||(eu(a.max)||NA(w.quality,a.max))&&(eu(a.min)||Dm(w.quality,a.min))?!0:(y[w.quality]="FitsQualityLimits",!1):(y[w.quality]="FitsThroughput",!1):(y[w.quality]="FitsContainer",!1))[0];L&&L.bitrate&&UA.next(L.bitrate);let M=(j=L!=null?L:S[Math.ceil((S.length-1)/2)])!=null?j:i[0];M.quality!==((Q=l==null?void 0:l.last)==null?void 0:Q.quality)&&d({message:`
7
7
  [available tracks]
8
- ${o.map(P=>`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate} }`).join(`
8
+ ${i.map(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(i!=null?i:{}).map(([P,I])=>`${P}: ${I}`).join(`
12
+ ${Object.entries(r!=null?r:{}).map(([w,x])=>`${w}: ${x}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
16
16
  containerQualityLimit: ${m},
17
17
  throughput: ${t},
18
- reserve: ${a},
19
- playbackRate: ${n},
20
- playbackRateFactor: ${f},
21
- forwardBufferHealth: ${s},
22
- bitrateFactor: ${v},
23
- minBufferToSwitchUp: ${i.minBufferToSwitchUp},
18
+ reserve: ${s},
19
+ playbackRate: ${o},
20
+ playbackRateFactor: ${b},
21
+ forwardBufferHealth: ${n},
22
+ bitrateFactor: ${g},
23
+ minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
24
  droppedVideoMaxQualityLimit: ${c},
25
- limitsAreInvalid: ${$},
26
- maxQualityLimit: ${r==null?void 0:r.max},
27
- minQualityLimit: ${r==null?void 0:r.min},
25
+ limitsAreInvalid: ${T},
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(y).map(([P,I])=>`${P}: ${I}`).join(`
30
+ ${Object.entries(y).map(([w,x])=>`${w}: ${x}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
- [best track] ${M==null?void 0:M.quality}
34
- [selected track] ${R==null?void 0:R.quality}
35
- `});let H=R&&d&&d.history[R.id]&&Ys()-d.history[R.id]<=i.trackCooldown&&(!d.last||R.id!==d.last.id);if(R!=null&&R.id&&d&&!H&&d.recordSelection(R),H&&(d!=null&&d.last)){let P=d.last;return d==null||d.recordSwitch(P),l({message:`
36
- [last selected] ${P==null?void 0:P.quality}
37
- `}),P}return d==null||d.recordSwitch(R),R},ze=ad;var K=o=>new URL(o).hostname;import{assertNever as Zs,assertNonNullable as en,combine as xd,debounce as Pd,ErrorCategory as tn,filter as kd,filterChanged as Ad,isNonNullable as ba,map as ar,merge as rn,observableFrom as wd,Subscription as $d,ValueSubject as ga,videoQualityToHeight as Ld,videoSizeToQuality as Rd}from"@vkontakte/videoplayer-shared";var qs=o=>{if(o instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(o.message))throw o;return!(o instanceof DOMException&&(o.code===20||o.name==="AbortError"))},oe=o=>w(void 0,null,function*(){let e=o.muted;try{yield o.play()}catch(t){if(!qs(t))return!1;if(e)return console.warn(t),!1;o.muted=!0;try{yield o.play()}catch(i){return qs(i)&&(o.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as tr,isNullable as od,assertNonNullable as Yt}from"@vkontakte/videoplayer-shared";import{isNonNullable as zs,assertNonNullable as er,now as sd}from"@vkontakte/videoplayer-shared";function J(){return sd()}function pa(o){return J()-o}function ha(o){let e=o.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,n,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),n&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Ks(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function kt(o,e,t,i){let r=window.XMLHttpRequest,a,s,n,u=!1,d=0,c,l,p=!1,h="arraybuffer",m=7e3,f=2e3,g=()=>{if(u)return;er(c);let x=pa(c),U;if(x<f){U=f-x,setTimeout(g,U);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,B()},S=x=>(a=x,A),b=x=>(l=x,A),$=()=>(h="json",A),v=()=>{if(!u){if(--d>=0){g(),i&&i();return}u=!0,l&&l(),t&&t()}},y=x=>(p=x,A),B=()=>{c=J(),s=new r,s.open("get",o);let x=0,U,j=0,P=()=>(er(c),Math.max(c,Math.max(U||0,j||0)));if(a&&s.addEventListener("progress",I=>{let N=J();a.updateChunk&&I.loaded>x&&(a.updateChunk(P(),I.loaded-x),x=I.loaded,U=N)}),n&&(s.timeout=n,s.addEventListener("timeout",()=>v())),s.addEventListener("load",()=>{if(u)return;er(s);let I=s.status;if(I>=200&&I<300){if(s.response.byteLength&&a){let N=s.response.byteLength-x;N&&a.updateChunk&&a.updateChunk(P(),N)}s.responseType==="json"&&!Object.values(s.response).length?v():(l&&l(),e(s.response))}else v()}),s.addEventListener("error",()=>{v()}),p){let I=()=>{er(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(j=J(),s.removeEventListener("readystatechange",I))};s.addEventListener("readystatechange",I)}return s.responseType=h,s.send(),A},A={withBitrateReporting:S,withParallel:y,withJSONResponse:$,withRetryCount:x=>(d=x,A),withRetryInterval:(x,U)=>(zs(x)&&(f=x),zs(U)&&(m=U),A),withTimeout:x=>(n=x,A),withFinally:b,send:B,abort:()=>{s&&(s.abort(),s=void 0),u=!0,l&&l()}};return A}var Qt=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,n=a.end-a.start;i+=s;let u=a.bytes*s/n;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 Wt=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=J(),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=J()-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()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=kt(t,a,()=>r("error"),n),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=J()}_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=J();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 n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-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 ir=1e4,ma=3;var ud=6e4,dd=10,ld=1,cd=500,qt=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 Qt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ha(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=ha(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 n=0;n<this.manifest.length;++n)a=this.manifest[n],!(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||tr(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=()=>{Ks(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 Wt(ma,ir,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,n=null,u=null,d=null,c=!1,l=()=>{let v=a&&(!c||c===this.rep);return v||t("Not running!"),v},p=(v,y,B)=>{u&&u.abort(),u=kt(this.urlResolver.resolve(v,!1),y,B,()=>this._retryCallback()).withTimeout(ir).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ma).withFinally(()=>{u=null}).send()},h=(v,y,B)=>{Yt(this.filesFetcher),n==null||n.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),y,B,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},m=v=>{let y=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${y}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let B=J()-1e4,M=0;for(let H=0;H<this.bufferStates.length;H++){let F=this.bufferStates[H];v=Math.min(v,F.buf),F.ts<B&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${v} drop=${M} jitter=${this.sourceJitter}`);let R=v-ld;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?m(1.15):R>1?m(1.1):R>.3?m(1.05):m(1)}},S=v=>{let y,B=()=>y&&y.start?y.start.length:0,M=I=>y.start[I]/1e3,R=I=>y.dur[I]/1e3,H=I=>y.fragIndex+I,F=(I,N)=>({chunkIdx:H(I),startTS:M(I),dur:R(I),discontinuity:N}),A=()=>{let I=0;if(y&&y.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,q=N;this.sourceJitter>1&&(q+=this.sourceJitter-1);let Z=y.dur.length-1;for(;Z>=0&&(q-=y.dur[Z],!(q<=0));--Z);I=Math.min(Z,y.dur.length-1-Q),I=Math.max(I,0)}return F(I,!0)},x=I=>{let N=B();if(!(N<=0)){if(tr(I)){for(let Q=0;Q<N;Q++)if(M(Q)>I)return F(Q)}return A()}},U=I=>{let N=B(),Q=I?I.chunkIdx+1:0,q=Q-y.fragIndex;if(!(N<=0)){if(!I||q<0||q-N>dd)return t(`Resync: offset=${q} bChunks=${N} chunk=`+JSON.stringify(I)),A();if(!(q>=N))return F(Q-y.fragIndex,!1)}},j=(I,N,Q)=>{d&&d.abort(),d=kt(this.urlResolver.resolve(I,!0,this.lowLatency),N,Q,()=>this._retryCallback()).withTimeout(ir).withRetryCount(ma).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,N)=>{j(v,Q=>{if(!l())return;y=Q;let q=!!y.lowLatency;q!==this.lowLatency&&f(q);let Z=0;for(let Re=0;Re<y.dur.length;++Re)Z+=y.dur[Re];Z>0&&(Yt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/y.dur.length)),r({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,I(x(N))},()=>this._handleNetworkError())},nextChunk:U}},b=()=>{a=!1,n&&n.abort(),u&&u.abort(),d&&d.abort(),Yt(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:v=>{let{videoElement:y,logger:B}=this.params,M=S(e.jidxUrl),R,H,F,A,x=0,U,j,P,I=()=>{U&&(clearTimeout(U),U=void 0);let O=Math.max(cd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=x+O,de=J(),ce=Math.min(1e4,te-de);x=de;let Ne=()=>{d||l()&&M.seek(()=>{l()&&(x=J(),N(),I())})};ce>0?U=window.setTimeout(()=>{this.paused?I():Ne()},ce):Ne()},N=()=>{let O;for(;O=M.nextChunk(A);)A=O,Fi(O);let te=M.nextChunk(F);if(te){if(F&&te.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?I():(b(),this._initPlayerWith(e));return}Re(te)}else I()},Q=(O,te)=>{if(!l()||!this.sourceBuffer)return;let de,ce,Ne,vt=Fe=>{window.setTimeout(()=>{l()&&Q(O,te)},Fe)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),vt(100);else{let Fe=J(),tt=y.currentTime;!this.paused&&y.buffered.length>1&&j===tt&&Fe-P>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),j!==tt&&(j=tt,P=Fe);let yt=this._getBufferSizeSec();if(yt>30)B(`Buffered ${yt} seconds; delaying appendBuffer`),vt(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:Fe,buf:yt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(Ot){if(Ot.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),Ne=this.sourceBuffer.buffered.length,Ne!==0&&(de=this.sourceBuffer.buffered.start(0),ce=tt,ce-de>4&&this.sourceBuffer.remove(de,ce-3)),vt(1e3);else throw Ot}}},q=()=>{H&&R&&(B([`Appending chunk, sz=${H.byteLength}:`,JSON.stringify(F)]),Q(H,function(){H=null,N()}))},Z=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),Re=O=>{l()&&h(Z(O),(te,de)=>{if(l()){if(de/=1e3,H=te,F=O,s=O.startTS,de){let ce=Math.min(10,O.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}q()}},()=>this._handleNetworkError())},Fi=O=>{l()&&(Yt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(O),!1)))},Vt=O=>{l()&&(e.cachedHeader=O,Q(O,()=>{R=!0,q()}))};a=!0,M.seek(O=>{if(l()){if(x=J(),!O){I();return}A=O,!od(v)||O.startTS>v?Re(O):(F=O,N())}},v),e.cachedHeader?Vt(e.cachedHeader):p(e.headerUrl,Vt,()=>this._handleNetworkError())},stop:b,getTimestampSec:()=>s},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),tr(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,Yt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return tr(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/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(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},a=(()=>({updateChunk:(p,h)=>{let m=J();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),s=-1/0,n,u=!0,d=()=>{let l=a.get();if(l&&n&&this.autoQuality){if(u&&l>n&&pa(s)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,p)=>{let h=a.updateChunk(l,p);return h&&d(),h},notifySwitch:l=>{let p=J();l<n&&(s=p),n=l}}}_fetchManifest(e,t,i){this.manifestRequest=kt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ir).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;oe(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 n=[];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,n.push(u))}),n.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),n):(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))},ud))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as pd,filter as Js,fromEvent as hd,interval as md,isHigher as fd,isInvariantQuality as bd,isLower as gd,merge as Sd,Subject as Xs,Subscription as vd}from"@vkontakte/videoplayer-shared";var fa=class{constructor(){this.onDroopedVideoFramesLimit$=new Xs;this.subscription=new vd;this.playing=!1;this.tracks=[];this.forceChecker$=new Xs;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&&!bd(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&&fd(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.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(hd(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=md(this.droppedFramesChecker.checkTime).pipe(Js(()=>this.playing),Js(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(pd(this.droppedFramesChecker.checkTime)),i=Sd(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])=>gd(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}},rr=fa;import{map as yd,Observable as Td}from"@vkontakte/videoplayer-shared";import{fromEvent as Id}from"@vkontakte/videoplayer-shared";var zt=()=>{var o;return!!((o=window.documentPictureInPicture)!=null&&o.window)||!!document.pictureInPictureElement};var Ed=(o,e)=>new Td(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,n)=>{s.forEach(u=>t.next(u.isIntersecting||zt()))},k(k({},i),e));r.observe(o);let a=Id(document,"visibilitychange").pipe(yd(s=>!document.hidden||zt())).subscribe(s=>t.next(s));return()=>{r.unobserve(o),a.unsubscribe}}),be=Ed;var Md=["paused","playing","ready"],Dd=["paused","playing","ready"],Kt=class{constructor(e){this.subscription=new $d;this.videoState=new L("stopped");this.representations$=new ga([]);this.textTracksManager=new me;this.droppedFramesManager=new rr;this.maxSeekBackTime$=new ga(1/0);this.zeroTime$=new ga(void 0);this.liveOffset=new De;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:tn.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let s=e.manifest,n=[];for(let u of s){let d=(t=u.name)!=null?t:u.index.toString(10),c=(i=Ye(u.name))!=null?i:Rd(u.video),l=u.bitrate/1e3,p=k({},u.video);if(!c)continue;let h={id:d,quality:c,bitrate:l,size:p};n.push({track:h,representation:u})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.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,n=(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),ba(n)&&this.params.output.currentVideoTrack$.next(n);break}case"bandwidth":{let{size:s,duration:n}=e;this.params.dependencies.throughputEstimator.addRawSpeed(s,n);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(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Dd.includes(e)&&(s||n)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&Md.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(X(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(X(this.params.source.url,u))}return;default:return Zs(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:tn.WTF,message:"DashLiveProvider internal logic error",thrown:r})};rn(this.videoState.stateChangeStarted$.pipe(ar(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ar(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=re(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(K(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=ne(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(ar(r=>r.map(({track:a})=>a)))}),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(Ad(),ar(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(xd({zeroTime:this.zeroTime$.pipe(kd(ba)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(ke(this.video,this.params.desiredState.isLooped,t)).add(se(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(he(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(be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Ld(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 Zs(r.to)}},t)).add(rn(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,wd(["init"])).pipe(Pd(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),ae(this.video)}createLiveDashPlayer(){let e=new qt({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,c,l,p,h,m;let e=this.representations$.getValue(),t=(c=(d=this.params.desiredState.videoTrack.getTransition())==null?void 0:d.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(p=(l=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:l.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&ba(t)?t:ze(e.map(({track:f})=>f),{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(),n=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==n)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==n){let f=(m=e.find(({track:g})=>g.id===a))==null?void 0:m.representation;en(f,"Representations missing"),this.dash.startPlay(f,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;en(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(X(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var an=Kt;var Be=(o,e)=>{let t=0;for(let i=0;i<o.length;i++){let r=o.start(i)*1e3,a=o.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as bl,assertNonNullable as jn,debounce as gl,ErrorCategory as Ma,filter as Sl,filterChanged as Qn,fromEvent as vl,isLowerOrEqual as Wn,isNonNullable as yl,videoSizeToQuality as Yn,map as gr,merge as Sr,observableFrom as Tl,observeElementSize as Il,once as El,Subscription as xl,ValueSubject as qn}from"@vkontakte/videoplayer-shared";var Jt=(o,e)=>{for(let t=0;t<o.length;t++)if(o.start(t)*1e3<=e&&o.end(t)*1e3>e)return!0;return!1};import{abortable as $a,assertNonNullable as ft,combine as cr,ErrorCategory as Je,filter as pr,filterChanged as On,fromEvent as Rt,interval as La,isNonNullable as _n,map as Ra,merge as Mt,Subject as Nn,Subscription as Fn,tap as ll,throttle as cl,ValueSubject as ue}from"@vkontakte/videoplayer-shared";import{assertNever as Cd,CurrentClientBrowser as Bd,ErrorCategory as sn,getCurrentBrowser as Vd,Subject as nn}from"@vkontakte/videoplayer-shared";var Od=16,dn=!1,on,un;try{dn=Vd().browser===Bd.Safari&&parseInt((un=(on=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:on[1])!=null?un:"",10)<=Od}catch(o){console.error(o)}var Sa=class{constructor(e){this.bufferFull$=new nn;this.error$=new nn;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:sn.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return w(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 w(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 w(this,null,function*(){return new Promise(t=>{let i;dn&&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:sn.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:Cd(t)}}},ln=Sa;var va=o=>{let e=0;for(let t=0;t<o.length;t++)e+=o.end(t)-o.start(t);return e*1e3};import{abortable as $t,assertNever as il,assertNonNullable as we,ErrorCategory as Lt,fromEvent as Ea,getExponentialDelay as xa,isNonNullable as wn,isNullable as $e,once as rl,Subject as al,Subscription as sl,ValueSubject as vi}from"@vkontakte/videoplayer-shared";var _=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 At=class extends _{};var Xt=class extends _{};var Zt=class extends _{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 ei=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ti=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ii=class extends _{constructor(t,i){super(t,i);this.data=this.content}};var W=class extends _{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ut=class extends W{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,n=a<<1>>>1,u=this.readUint32();a=this.readUint32();let d=a>>>28,c=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:d,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var ri=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends W{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 ni=class extends W{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var oi=class extends W{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ui=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends W{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 li=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends W{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var hi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends W{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 fi=class extends W{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 bi=class extends W{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 Nd={ftyp:Zt,moov:ei,moof:ti,mdat:ii,sidx:ut,trak:ri,mdia:ui,mfhd:pi,tkhd:di,traf:hi,tfhd:mi,tfdt:fi,trun:bi,minf:li,sv3d:ai,st3d:si,prhd:ni,proj:ci,equi:oi,uuid:Xt,unknown:At},dt=class o{constructor(e={}){this.options=k({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=Nd[e];return i?new i(t,new o):new At(t,new o)}};var wt=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 Ud=new TextDecoder("ascii"),Hd=o=>Ud.decode(new DataView(o.buffer,o.byteOffset+4,4))==="ftyp",Gd=o=>{let e=new ut(o,new dt),t=e.earliestPresentationTime/e.timescale*1e3,i=o.byteOffset+o.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,n={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,n})},jd=(o,e)=>{let i=new dt().parse(o),r=new wt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let n=a[0],u=s[s.length-1],d=n.source.byteOffset,l=u.source.byteOffset-n.source.byteOffset+u.size;return new DataView(o.buffer,d,l)},Qd=(o,e)=>{let i=new dt().parse(o),a=new wt(i).findAll("traf"),s=a[a.length-1].children.find(l=>l.type==="tfhd"),n=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((l,p)=>l+p,0):d=s.defaultSampleDuration*u.sampleCount,(Number(n.baseMediaDecodeTime)+d)/e*1e3},Wd=o=>{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 dt().parse(o),r=new wt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.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},cn={validateData:Hd,parseInit:Wd,getIndexRange:()=>{},parseSegments:Gd,parseFeedableSegmentChunk:jd,getSegmentEndTime:Qd};import{assertNonNullable as Ta,isNonNullable as fn,isNullable as qd}from"@vkontakte/videoplayer-shared";import{assertNever as Yd}from"@vkontakte/videoplayer-shared";var pn={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"}},hn=o=>{let e=o.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=gi(o,t),r=i in pn,a=r?pn[i].type:"binary",s=o.getUint8(t),n=0;s&128?n=1:s&64?n=2:s&32?n=3:s&16?n=4:s&8?n=5:s&4?n=6:s&2?n=7:s&1&&(n=8);let u=new DataView(o.buffer,o.byteOffset+t+1,n-1),d=s&255>>n,c=gi(u),l=d*Pe(2,(n-1)*8)+c,p=t+n,h;return p+l>o.byteLength?h=new DataView(o.buffer,o.byteOffset+p):h=new DataView(o.buffer,o.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},gi=(o,e=o.byteLength)=>{switch(e){case 1:return o.getUint8(0);case 2:return o.getUint16(0);case 3:return o.getUint8(0)*Pe(2,16)+o.getUint16(1);case 4:return o.getUint32(0);case 5:return o.getUint8(0)*Pe(2,32)+o.getUint32(1);case 6:return o.getUint16(0)*Pe(2,32)+o.getUint32(2);case 7:{let t=o.getUint8(0)*281474976710656+o.getUint16(1)*4294967296+o.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ie=(o,e)=>{switch(e){case"int":return o.getInt8(0);case"uint":return gi(o);case"float":return o.byteLength===4?o.getFloat32(0):o.getFloat64(0);case"string":return new TextDecoder("ascii").decode(o);case"utf8":return new TextDecoder("utf-8").decode(o);case"date":return new Date(Date.UTC(2001,0)+o.getInt8(0)).getTime();case"master":return o;case"binary":return o;default:Yd(e)}},lt=(o,e)=>{let t=0;for(;t<o.byteLength;){let i=new DataView(o.buffer,o.byteOffset+t),r=hn(i);if(!e(r))return;r.type==="master"&&lt(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},mn=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=hn(o);return lt(r.value,({tag:a,type:s,value:n})=>(a===17143?e=Ie(n,s):a===17026?t=Ie(n,s):a===17029&&(i=Ie(n,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var bn=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],zd=[231,22612,22743,167,171,163,160,175],Kd=o=>{let e,t,i,r,a=!1,s=!1,n=!1,u,d,c=!1,l=0;return lt(o,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let g=Ie(m,h);d=gi(g)}else p!==21420&&(d=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=Ie(m,h):p===17545?r=Ie(m,h):p===21420&&d===475249515?u=Ie(m,h):p===374648427?lt(m,({tag:g,type:S,value:b})=>g===30321?(c=Ie(b,S)===1,!1):!0):a&&s&&bn.includes(p)&&(n=!0),!n}),Ta(e,"Failed to parse webm Segment start"),Ta(t,"Failed to parse webm Segment end"),Ta(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:c,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Jd=o=>{if(qd(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Xd=(o,e)=>{let t=!1,i=!1,r=n=>fn(n.time)&&fn(n.position),a=[],s;return lt(o,({tag:n,type:u,value:d})=>{switch(n){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Ie(d,u));break;case 183:break;case 241:s&&(s.position=Ie(d,u));break;default:t&&bn.includes(n)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((n,u)=>{let{time:d,position:c}=n,l=a[u+1];return{status:"none",time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},Zd=o=>{let e=0,t=!1;try{lt(o,i=>i.tag===524531317?i.tagSize<=o.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):zd.includes(i.tag)?(e+i.tagSize<=o.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=o.byteLength&&t?new DataView(o.buffer,o.byteOffset,e):null},gn={validateData:mn,parseInit:Kd,getIndexRange:Jd,parseSegments:Xd,parseFeedableSegmentChunk:Zd};import{isNonNullable as vn,isNullable as yn}from"@vkontakte/videoplayer-shared";var Sn=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var Tn=o=>{if(!o.startsWith("P"))return;let e=(s,n)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*n},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(o),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},ct=(o,e)=>{let t=o;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,(n,u)=>yn(a)?n:yn(u)?a:a.padStart(parseInt(u,10),"0"))}return t},En=(o,e)=>{var v,y,B,M,R,H,F,A,x,U,j,P,I,N,Q,q,Z,Re,Fi,Vt,O,te,de,ce,Ne,vt,Fe,tt,yt,Ot,Ya,qa,za,Ka,Ja,Xa,Za,es,ts,is,rs,as;let i=new DOMParser().parseFromString(o,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],n=(B=(y=(v=a.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:y.trim())!=null?B:"",u=s.children,d=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=c?new Date(c).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),f=a.getElementsByTagName("vk:Attrs")[0],g=f==null?void 0:f.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Tn(h);else if(m){let pe=Tn(m);vn(pe)&&(p=pe)}else g&&(p=parseInt(g,10));let S=0,b=(R=(M=a.getAttribute("profiles"))==null?void 0:M.split(","))!=null?R:[],$=b.includes("urn:webm:dash:profile:webm-on-demand:2012")||b.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let pe of u){let Ui=pe.getAttribute("mimeType"),eu=pe.getAttribute("codecs"),ss=(H=pe.getAttribute("contentType"))!=null?H:Ui==null?void 0:Ui.split("/")[0],tu=(A=(F=pe.getAttribute("profiles"))==null?void 0:F.split(","))!=null?A:[],ns=pe.querySelectorAll("Representation"),iu=pe.querySelector("SegmentTemplate");if(ss==="text"){for(let Y of ns){let Ue=Y.getAttribute("id")||"",Hi=pe.getAttribute("lang"),Tt=pe.getAttribute("label"),Ur=(j=(U=(x=Y.querySelector("BaseURL"))==null?void 0:x.textContent)==null?void 0:U.trim())!=null?j:"",Hr=new URL(Ur||n,e).toString(),Gi=Ue.includes("_auto");r.text.push({id:Ue,lang:Hi,label:Tt,isAuto:Gi,kind:"text",url:Hr})}continue}for(let Y of ns){let Ue=(P=Y.getAttribute("mimeType"))!=null?P:Ui,Hi=(N=(I=Y.getAttribute("codecs"))!=null?I:eu)!=null?N:"",Tt=(q=(Q=Y.getAttribute("contentType"))!=null?Q:Ue==null?void 0:Ue.split("/")[0])!=null?q:ss,Ur=(Re=(Z=pe.getAttribute("profiles"))==null?void 0:Z.split(","))!=null?Re:[],Hr=parseInt((Fi=Y.getAttribute("width"))!=null?Fi:"",10),Gi=parseInt((Vt=Y.getAttribute("height"))!=null?Vt:"",10),os=parseInt((O=Y.getAttribute("bandwidth"))!=null?O:"",10)/1e3,us=(te=Y.getAttribute("frameRate"))!=null?te:"",ru=(de=Y.getAttribute("quality"))!=null?de:void 0,au=us?Sn(us):void 0,su=(ce=Y.getAttribute("id"))!=null?ce:(S++).toString(10),nu=Tt==="video"?`${Gi}p`:Tt==="audio"?`${os}Kbps`:Hi,ou=`${su}@${nu}`,uu=(Fe=(vt=(Ne=Y.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:vt.trim())!=null?Fe:"",ds=new URL(uu||n,e).toString(),du=[...b,...tu,...Ur],Gr,lu=Y.querySelector("SegmentBase"),it=(tt=Y.querySelector("SegmentTemplate"))!=null?tt:iu;if(lu){let rt=(Ot=(yt=Y.querySelector("SegmentBase Initialization"))==null?void 0:yt.getAttribute("range"))!=null?Ot:"",[at,Qr]=rt.split("-").map(It=>parseInt(It,10)),He={from:at,to:Qr},_t=(Ya=Y.querySelector("SegmentBase"))==null?void 0:Ya.getAttribute("indexRange"),[Wr,ji]=_t?_t.split("-").map(It=>parseInt(It,10)):[],Nt=_t?{from:Wr,to:ji}:void 0;Gr={type:"byteRange",url:ds,initRange:He,indexRange:Nt}}else if(it){let rt={representationId:(qa=Y.getAttribute("id"))!=null?qa:void 0,bandwidth:(za=Y.getAttribute("bandwidth"))!=null?za:void 0},at=parseInt((Ka=it.getAttribute("timescale"))!=null?Ka:"",10),Qr=(Ja=it.getAttribute("initialization"))!=null?Ja:"",He=it.getAttribute("media"),_t=(Za=parseInt((Xa=it.getAttribute("startNumber"))!=null?Xa:"",10))!=null?Za:1,Wr=ct(Qr,rt);if(!He)throw new ReferenceError("No media attribute in SegmentTemplate");let ji=(es=it.querySelectorAll("SegmentTimeline S"))!=null?es:[],Nt=[],It=0,Yr="",qr=0;if(ji.length){let Qi=_t,Te=0;for(let Et of ji){let xe=parseInt((ts=Et.getAttribute("d"))!=null?ts:"",10),st=parseInt((is=Et.getAttribute("r"))!=null?is:"",10)||0,Wi=parseInt((rs=Et.getAttribute("t"))!=null?rs:"",10);Te=Number.isFinite(Wi)?Wi:Te;let zr=xe/at*1e3,Kr=Te/at*1e3;for(let Yi=0;Yi<st+1;Yi++){let pu=ct(He,V(k({},rt),{segmentNumber:Qi.toString(10),segmentTime:(Te+Yi*xe).toString(10)})),ls=(Kr!=null?Kr:0)+Yi*zr,hu=ls+zr;Qi++,Nt.push({time:{from:ls,to:hu},url:pu})}Te+=(st+1)*xe,It+=(st+1)*zr}qr=Te/at*1e3,Yr=ct(He,V(k({},rt),{segmentNumber:Qi.toString(10),segmentTime:Te.toString(10)}))}else if(vn(p)){let Te=parseInt((as=it.getAttribute("duration"))!=null?as:"",10)/at*1e3,Et=Math.ceil(p/Te),xe=0;for(let st=1;st<Et;st++){let Wi=ct(He,V(k({},rt),{segmentNumber:st.toString(10),segmentTime:xe.toString(10)}));Nt.push({time:{from:xe,to:xe+Te},url:Wi}),xe+=Te}qr=xe,Yr=ct(He,V(k({},rt),{segmentNumber:Et.toString(10),segmentTime:xe.toString(10)}))}let cu={time:{from:qr,to:1/0},url:Yr};Gr={type:"template",baseUrl:ds,segmentTemplateUrl:He,initUrl:Wr,totalSegmentsDurationMs:It,segments:Nt,nextSegmentBeyondManifest:cu,timescale:at}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Tt||!Ue)continue;let jr={video:"video",audio:"audio",text:"text"}[Tt];jr&&r[jr].push({id:ou,kind:jr,segmentReference:Gr,profiles:du,duration:p,bitrate:os,mime:Ue,codecs:Hi,width:Hr,height:Gi,fps:au,quality:ru})}}return{dynamic:d,liveAvailabilityStartTime:l,duration:p,container:$,representations:r}};import{videoSizeToQuality as tl}from"@vkontakte/videoplayer-shared";var xn=({id:o,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;let s=(n=a?Ye(a):void 0)!=null?n:tl({width:e,height:t});return s&&{id:o,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},Pn=({id:o,bitrate:e})=>({id:o,bitrate:e}),kn=(o,e,t)=>{var r;let i=e.indexOf(t);return(r=o.at(Math.round(o.length*i/e.length)))!=null?r:o.at(-1)},An=({id:o,lang:e,label:t,url:i,isAuto:r})=>({id:o,url:i,isAuto:r,type:"internal",language:e,label:t}),sr=o=>"url"in o,pt=o=>o.type==="template",Si=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var yi=class{constructor(e,t,i,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:c}){this.currentSegmentLength$=new vi(0);this.onLastSegment$=new vi(!1);this.fullyBuffered$=new vi(!1);this.playingRepresentation$=new vi(void 0);this.playingRepresentationInit$=new vi(void 0);this.error$=new al;this.gaps=[];this.subscription=new sl;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=$t(this.destroyAbortController.signal,function(e){return z(this,null,function*(){let t=this.representations.get(e);we(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ln(this.sourceBuffer),this.subscription.add(Ea(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>this.error$.next({id:"SegmentEjection",category:Lt.WTF,message:"Error when trying to clear segments ejected by browser",thrown:s}))),this.subscription.add(Ea(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Lt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n)return;let u=Math.min(this.bufferLimit,va(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=Be(this.sourceBuffer.buffered,n),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(n,s*2,d<c)}else this.pruneBufferOld(n,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);we(i,"No init buffer for starting representation"),we(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=$t(this.destroyAbortController.signal,function(e){return z(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);we(t,`No such representation ${e}`);let i=this.segments.get(e),r=this.initData.get(e);if($e(r)||$e(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),we(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);let a=this.getCurrentPosition();wn(a)&&(this.isLive||(i.forEach(s=>s.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(a,1/0,!0)),this.maintain(a))})}.bind(this));this.seekLive=$t(this.destroyAbortController.signal,function(e){return z(this,null,function*(){var n;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let d=e.find(p=>p.id===u);d&&this.representations.set(u,d);let c=this.representations.get(u);if(!c||!pt(c.segmentReference))return;let l=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,l)}let t=(n=this.switchingToRepresentationId)!=null?n:this.downloadingRepresentationId,i=this.representations.get(t);we(i);let r=this.segments.get(t);we(r,"No segments for starting representation");let a=this.initData.get(t);if(we(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let s=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),s&&(yield this.sourceBufferTaskQueue.remove(s.from*1e3,s.to*1e3,this.destroyAbortController.signal)),this.searchGaps(r,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));switch(this.fetcher=a,this.tuning=s,this.compatibilityMode=d,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=i,i){case"mp4":this.containerParser=cn;break;case"webm":this.containerParser=gn;break;default:il(i)}this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.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,c;if($e(e)||$e(this.downloadingRepresentationId)||$e(this.playingRepresentationId)||$e(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(we(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next(((d=r==null?void 0:r.time.to)!=null?d:0)-((c=r==null?void 0:r.time.from)!=null?c:0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Be(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)&&va(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Be(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p);return}let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,t.segmentReference.type,a),n.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(n.includes(r))l="high";else{let p=n.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(n,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!n.length&&Be(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;wn(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.representations[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 t,i,r,a;for(let s of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!s||!pt(s.segmentReference))return;let n=s.segmentReference.segments.map(l=>V(k({},l),{status:"none",size:void 0})),u=(i=this.segments.get(s.id))!=null?i:[],d=(a=(r=u.at(-1))==null?void 0:r.time.to)!=null?a:0,c=n==null?void 0:n.findIndex(l=>Math.floor(d)>=Math.floor(l.time.from)&&Math.floor(d)<=Math.floor(l.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(s.segmentReference);this.segments.set(s.id,l)}else{let l=n.slice(c+1);this.segments.set(s.id,[...u,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;we(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLive(i)}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let i of this.representations.values()){let r=i.segmentReference;if(!pt(r))return;let a=Math.round(e.time.to*r.timescale/1e3).toString(10),s=ct(r.segmentTemplateUrl,{segmentTime:a}),n=(t=this.segments.get(i.id))!=null?t:[],u=n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.from));u&&(u.time.to=e.time.to),!!n.find(c=>Math.floor(c.time.from)===Math.floor(e.time.to))||n.push({status:"none",time:{from:e.time.to,to:1/0},url:s})}}findSegmentStartTime(e){var a,s,n;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(n=r==null?void 0:r.time.from)!=null?n: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:l,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,g=p>i||f||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),b=this.preloadOnly&&p<=i+S||h<=i+S;return(l==="none"||l==="partially_ejected"&&g&&b&&this.sourceBuffer&&!Jt(this.sourceBuffer.buffered,i))&&g&&b});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,n=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(s<=d||n<=c);l++){let p=a[l];if(s+=p.byte.to+1-p.byte.from,n+=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 w(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 w(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:n,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield $t(n,function(){return z(this,null,function*(){let c=xa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))})}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(s,{range:a,signal:n,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;let l=new DataView(c);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(l,p)}u&&r.feedingBytes&&d?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(l,n),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Si(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,i="auto"){return w(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:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(yield $t(s,function(){return z(this,null,function*(){let u=xa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),Ea(window,"online").pipe(rl()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:n,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Si(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(pt(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:(n,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:n,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!pt(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,c)=>{if(!a.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}: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 w(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))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 c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(d.status="partially_fed",u.feedingBytes+=l.byteLength,yield this.sourceBufferTaskQueue.append(l),u.fedBytes+=l.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let c=d.byte.from-i,l=d.byte.to-i,p=l-c+1,h=c<r,m=l<=r;if(h){if(d.status==="downloading"&&m){d.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+c,p);this.sourceBufferTaskQueue.append(f,a).then(g=>g&&!a.aborted?this.onSegmentFullyAppended(u,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?f:this.containerParser.parseFeedableSegmentChunk(f);g!=null&&g.byteLength&&(d.status="partially_fed",u.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,a).then(S=>{if(a.aborted)s();else if(S)u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t);else{if(u.feedingBytes<p)return;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",sr(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.isActiveLowLatency()&&this.updateLowLatencyLive(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 w(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?$t(this.destroyAbortController.signal,function(){return z(this,null,function*(){let n=xa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,n))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(n=>w(this,null,function*(){if(!n)return;let{init:u,dataView:d,segments:c}=n,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l);let p=c;this.isLive&&pt(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,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Lt.WTF,message:"loadInit threw",thrown:n})});return this.initData.set(e.id,s),s})}pruneBuffer(e,t,i=!1){return w(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)})}pruneBufferNew(e,t,i=!1){return w(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||$e(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=n=>{var c;let u=!0;for(let l of r)Math.round(l.from)===Math.round(n.time.to)?(l.from=n.time.from,u=!1):Math.round(l.to)===Math.round(n.time.from)&&(l.to=n.time.to,u=!1);u&&r.push(n.time);let d=sr(n)?(c=n.size)!=null?c:0:n.byte.to-n.byte.from;a+=d};for(let n of this.segments.values())for(let u of n){if(a>=t)break;let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&u.status==="fed"&&s(u)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let u=this.sourceBuffer.buffered.start(n)*1e3,d=this.sourceBuffer.buffered.end(n)*1e3;for(let c of this.segments.values())for(let l of c)if(l.status==="none"&&Math.round(l.time.from)<=Math.round(u)&&Math.round(l.time.to)>=Math.round(d)){r.push({from:u,to:d});break}}if(r.length&&i){let n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+n&&d.status==="fed"&&s(d)}return r.length?(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1})}pruneBufferOld(e,t,i=!1){return w(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||$e(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,n=!1,u=d=>{var l;a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let c=sr(d)?(l=d.size)!=null?l:0:d.byte.to-d.byte.from;r+=c};for(let d of this.segments.values())for(let c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&u(c)}if(n=isFinite(a)&&isFinite(s),!n){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&u(c)}}if(n=isFinite(a)&&isFinite(s),!n)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let c=this.sourceBuffer.buffered.start(d)*1e3,l=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(c)&&Math.round(h.time.to)>=Math.round(l)){a=c,s=l;break}}if(n=isFinite(a)&&isFinite(s),!n&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>e+d&&l.status==="fed"&&u(l)}return n=isFinite(a)&&isFinite(s),n?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,n=this.sourceBuffer.buffered.end(a)*1e3;if(!(n<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&n>=i.time.to){r=void 0;break}n>i.time.from&&n<i.time.to&&(r.from=n),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:Lt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if($e(this.sourceBuffer)||$e(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),n=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=s&&c.to+t>=n),d=e.filter(c=>s>=c.from-t&&s<=c.to+t||n>=c.from-t&&n<=c.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var Ti=o=>{let e=new URL(o);return e.searchParams.set("quic","1"),e.toString()};var $n=o=>{var a;let e=o.get("X-Delivery-Type"),t=o.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}};import{abortable as Ii,assertNever as Ln,fromEvent as Rn,merge as nl,now as Pa,Subscription as ol,ValueSubject as ka}from"@vkontakte/videoplayer-shared";var nr=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new ka(void 0);this.lastConnectionReused$=new ka(void 0);this.lastRequestFirstBytes$=new ka(void 0);this.abortAllController=new AbortController;this.subscription=new ol;this.fetchManifest=Ii(this.abortAllController.signal,function(e){return z(this,null,function*(){let t=e;this.requestQuic&&(t=Ti(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(Ei);return i?(this.onHeadersReceived(i.headers),i.text()):null})}.bind(this));this.fetch=Ii(this.abortAllController.signal,function(d){return z(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:n=!0,isLowLatency:u=!1}={}){var H,F;let c=e,l=new Headers;if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(c,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),c=A.toString();break}default:Ln(t)}this.requestQuic&&(c=Ti(c));let p=this.abortAllController.signal,h;if(s){let A=new AbortController;if(h=nl(Rn(this.abortAllController.signal,"abort"),Rn(s,"abort")).subscribe(()=>{try{A.abort()}catch(x){Ei(x)}}),this.abortAllController.signal.aborted||s.aborted)try{A.abort()}catch(x){Ei(x)}p=A.signal}let m=Pa(),f=yield fetch(c,{priority:a,headers:l,signal:p}).catch(Ei),g=Pa();if(!f)return h==null||h.unsubscribe(),null;if((H=this.throughputEstimator)==null||H.addRawRtt(g-m),!f.ok||!f.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`));if(this.onHeadersReceived(f.headers),!r&&!n)return h==null||h.unsubscribe(),f.arrayBuffer();let[S,b]=f.body.tee(),$=S.getReader();n&&((F=this.throughputEstimator)==null||F.trackStream(b,u));let v=0,y=new Uint8Array(0),B=!1,M=A=>{h==null||h.unsubscribe(),B=!0,Ei(A)},R=Ii(p,function(U){return z(this,arguments,function*({done:A,value:x}){if(v===0&&this.lastRequestFirstBytes$.next(Pa()-m),p.aborted){h==null||h.unsubscribe();return}if(!A&&x){let j=new Uint8Array(y.length+x.length);j.set(y),j.set(x,y.length),y=j,v+=x.byteLength,r==null||r(new DataView(y.buffer),v),yield $==null?void 0:$.read().then(R,M)}})}.bind(this));return yield $==null?void 0:$.read().then(R,M),h==null||h.unsubscribe(),B?null:y.buffer})}.bind(this));this.fetchByteRangeRepresentation=Ii(this.abortAllController.signal,function(e,t,i){return z(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,n=a,u=!1,d,c;e.indexRange&&(d=e.indexRange.from,c=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),n=Math.max(c,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:n},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(l,m.from-s,m.to-m.from+1);else{let b=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!b)return null;f=new DataView(b)}let g=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(l),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ii(this.abortAllController.signal,function(e,t){return z(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=>V(k({},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}=$n(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return w(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:Ln(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ei=o=>{if(!Si(o))throw o};var ht=(o,e,t)=>t*e+(1-t)*o,Aa=(o,e)=>o.reduce((t,i)=>t+i,0)/e,Mn=(o,e,t,i)=>{let r=0,a=t,s=Aa(o,e),n=e<i?e:i;for(let u=0;u<n;u++)o[a]>s?r++:r--,a=(o.length+a-1)%o.length;return Math.abs(r)===n};import{isNullable as ul,ValueSubject as Dn}from"@vkontakte/videoplayer-shared";var Ke=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 Dn(e.initial),this.debounced$=new Dn(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ee(`raw_${t}`),this.smoothedSeries$=new ee(`smoothed_${t}`),this.reportedSeries$=new ee(`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 n=0;n<this.pastMeasures.length;n++)this.pastMeasures[n]!==void 0&&(t+=Pe(this.pastMeasures[n]-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)&&(ul(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 or=class extends Ke{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=ht(this.slow,t,this.params.emaAlphaSlow),this.fast=ht(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var ur=class extends Ke{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=Aa(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ht(this.emaSmoothed,t,this.params.emaAlpha);let r=Mn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var dr=class extends Ke{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?ht(this.smoothed,t,this.params.emaAlpha):t}};var mt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new or({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ur({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 dr(k({initial:e,label:"liveEdgeDelay"},t))}};var wa=(o,e)=>{o&&o.playbackRate!==e&&(o.playbackRate=e)};var Ve=()=>window.ManagedMediaSource||window.MediaSource,lr=()=>{var o,e;return!!(window.ManagedMediaSource&&((e=(o=window.ManagedSourceBuffer)==null?void 0:o.prototype)!=null&&e.appendBuffer))},Cn=()=>{var o,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(o=window.SourceBuffer)==null?void 0:o.prototype)!=null&&e.appendBuffer))},Bn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Un=["timeupdate","progress","play","seeked","stalled","waiting"];var hr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Fn;this.representationSubscription=new Fn;this.state$=new L("none");this.currentVideoRepresentation$=new ue(void 0);this.currentVideoRepresentationInit$=new ue(void 0);this.currentVideoSegmentLength$=new ue(0);this.currentAudioSegmentLength$=new ue(0);this.error$=new Nn;this.lastConnectionType$=new ue(void 0);this.lastConnectionReused$=new ue(void 0);this.lastRequestFirstBytes$=new ue(void 0);this.isLive$=new ue(!1);this.liveDuration$=new ue(0);this.liveAvailabilityStartTime$=new ue(void 0);this.bufferLength$=new ue(0);this.liveLoadBufferLength$=new ue(0);this.livePositionFromPlayer$=new ue(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ue(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Nn;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=$a(this.destroyController.signal,function(e,t,i){return z(this,null,function*(){var r;this.element=e,this.manifestUrlString=X(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Je.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=$a(this.destroyController.signal,function(){return z(this,null,function*(){var r;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Je.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=En(e!=null?e:"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:Je.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let i=({kind:a,mime:s,codecs:n})=>{var u,d,c,l;return!!((d=(u=this.element)==null?void 0:u.canPlayType)!=null&&d.call(u,s)&&((l=(c=Ve())==null?void 0:c.isTypeSupported)!=null&&l.call(c,`${s}; codecs="${n}"`))||a==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((r=t.duration)!=null?r:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),V(k({},t),{representations:Object.fromEntries(Object.entries(t.representations).map(([a,s])=>[a,s.filter(i)]))})})}.bind(this));this.initRepresentations=$a(this.destroyController.signal,function(e,t,i){return z(this,null,function*(){var h;ft(this.manifest),ft(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=m=>{this.representationSubscription.add(Rt(m,"error").pipe(pr(f=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Je.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Bn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&lr())if(i){let m=document.createElement("source");r(m),m.type="application/x-mpegurl",m.src=i.url,this.element.appendChild(m)}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};if(this.videoBufferManager=new yi("video",this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],_n(t)&&(this.audioBufferManager=new yi("audio",this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(La(1e3).subscribe(m=>{var f;if((f=this.element)!=null&&f.paused){let g=ta(this.manifestUrlString,2);this.manifestUrlString=X(this.manifestUrlString,g+1e3,2)}})),this.representationSubscription.add(Mt(...Un.filter(m=>m!=="waiting").map(m=>Rt(this.element,m))).pipe(Ra(m=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),On(),pr(m=>!!m),ll(m=>{var f;(f=this.stallWatchdogSubscription)==null||f.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(On()).subscribe(f=>wa(this.element,1))),this.representationSubscription.add(cr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(pr(({bufferLength:f,isActiveLowLatency:g})=>g&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(cr({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:g})=>{if(!g)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,$=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=f-S,y=1;Math.abs(v)>b&&(y=1+Math.sign(v)*$),wa(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var S,b;let g=0;if(f){let $=((b=(S=this.element)==null?void 0:S.currentTime)!=null?b:0)*1e3;g=Math.min(...this.bufferManagers.map(y=>{var B,M;return(M=(B=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:B.to)!=null?M:$}))-$}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let m=0;this.representationSubscription.add(cr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(cl(1e3)).subscribe(S=>w(this,[S],function*({liveLoadBufferLength:f,bufferLength:g}){if(ft(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,$=ta(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),B=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,M=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,R=isFinite(f)?f:g,H=this.isActiveLowLatency$.getValue(),F=v<=this.tuning.live.activeLiveDelay&&$===0;this.isActiveLowLatency$.next(H&&F);let A="none";if(H?A="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&F?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(x=>x.proceedLowLatencyLive()),A="active_low_latency"):$!==0&&R<y?A="live_forward_buffering":R<y+M&&(A="live_with_target_offset"),isFinite(f)&&(m=f>m?f:m),A==="live_forward_buffering"||A==="live_with_target_offset"){let x=m-(y+B),U=this.normolizeLiveOffset(Math.trunc($+x/b)),j=Math.abs(U-$),P;!f||j<=this.tuning.dashCmafLive.offsetCalculationError?P=$:U>0&&j>this.tuning.dashCmafLive.offsetCalculationError?P=U:P=0,this.manifestUrlString=X(this.manifestUrlString,P,2)}A!=="none"&&A!=="active_low_latency"&&(m=0,this.updateLive())})))}let n=Mt(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(Ra(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),u=Mt(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(Ra(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(Mt(this.forceEnded$,cr({allBuffersFull:n,someBufferEnded:u}).pipe(pr(({allBuffersFull:m,someBufferEnded:f})=>m&&f))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(m=this.source)==null||m.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Je.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(Mt(...this.bufferManagers.map(m=>m.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(m=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",m)}));let d=(h=this.manifest.duration)!=null?h:0,c=(m,f)=>{var g;return Math.max(m,(g=f.duration)!=null?g:0)},l=this.manifest.representations.audio.reduce(c,d),p=this.manifest.representations.video.reduce(c,d);(l||p)&&(this.source.duration=Math.max(l,p)/1e3),this.audioBufferManager&&_n(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=La(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),r=>{this.error$.next({id:"GapWatchdog",category:Je.WTF,message:"Error handling gaps",thrown:r})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new nr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=mt.getLiveEstimatedDelaySmoothedValue(0,k({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return w(this,null,function*(){var i,r,a,s;ft(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=X(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.representations.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive((a=this.manifest)==null?void 0:a.representations.audio))})}initBuffer(){ft(this.element),this.state$.setState("running"),this.subscription.add(Mt(...Un.map(e=>Rt(this.element,e)),Rt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Je.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Rt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Rt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=5e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=La(5e3).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Je.FATAL,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return w(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var r,a,s,n,u;ft(this.element),ft(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),Jt(this.element.buffered,i)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)==null||n.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)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}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 w(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 mr=class{constructor(e,t){this.fov=e,this.orientation=t}};var fr=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/Pe(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=k({},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*Pe(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 Hn=`attribute vec2 a_vertex;
33
+ [best track] ${L==null?void 0:L.quality}
34
+ [selected track] ${M==null?void 0:M.quality}
35
+ `});let U=M&&l&&l.history[M.id]&&Bm()-l.history[M.id]<=r.trackCooldown&&(!l.last||M.id!==l.last.id);if(M!=null&&M.id&&l&&!U&&l.recordSelection(M),U&&(l!=null&&l.last)){let w=l.last;return l==null||l.recordSwitch(w),d({message:`
36
+ [last selected] ${w==null?void 0:w.quality}
37
+ `}),w}return l==null||l.recordSwitch(M),M},St=GA;var te=i=>new URL(i).hostname;import{assertNever as Um,assertNonNullable as Hm,combine as dw,debounce as pw,ErrorCategory as jm,filter as Gm,filterChanged as hw,isNonNullable as uu,map as ns,merge as Ym,observableFrom as fw,once as mw,Subscription as bw,ValueSubject as lu,videoQualityToHeight as Sw,videoSizeToQuality as gw}from"@vkontakte/videoplayer-shared";var Vm=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"))},he=i=>$(void 0,null,function*(){let e=i.muted;try{yield i.play()}catch(t){if(!Vm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return Vm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as is,isNullable as QA,assertNonNullable as pi}from"@vkontakte/videoplayer-shared";import{isNonNullable as _m,assertNonNullable as rs,now as YA}from"@vkontakte/videoplayer-shared";function re(){return YA()}function au(i){return re()-i}function su(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 Nm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Tr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(u)return;rs(c);let A=au(c),j;if(A<b){j=b-A,setTimeout(S,j);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,B()},v=A=>(s=A,R),I=A=>(d=A,R),T=()=>(h="json",R),g=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},y=A=>(p=A,R),B=()=>{c=re(),n=new a,n.open("get",i);let A=0,j,Q=0,w=()=>(rs(c),Math.max(c,Math.max(j||0,Q||0)));if(s&&n.addEventListener("progress",x=>{let _=re();s.updateChunk&&x.loaded>A&&(s.updateChunk(w(),x.loaded-A),A=x.loaded,j=_)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>g())),n.addEventListener("load",()=>{if(u)return;rs(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let _=n.response.byteLength-A;_&&s.updateChunk&&s.updateChunk(w(),_)}n.responseType==="json"&&!Object.values(n.response).length?g():(d&&d(),e(n.response))}else g()}),n.addEventListener("error",()=>{g()}),p){let x=()=>{rs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=re(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),R},R={withBitrateReporting:v,withParallel:y,withJSONResponse:T,withRetryCount:A=>(l=A,R),withRetryInterval:(A,j)=>(_m(A)&&(b=A),_m(j)&&(m=j),R),withTimeout:A=>(o=A,R),withFinally:I,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return R}var ci=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 di=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=re(),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=re()-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=Tr(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=re()}_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=re();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 as=1e4,nu=3;var zA=6e4,KA=10,JA=1,XA=500,hi=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 ci(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=su(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=su(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||is(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=()=>{Nm(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 di(nu,as,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 g=s&&(!c||c===this.rep);return g||t("Not running!"),g},p=(g,y,B)=>{u&&u.abort(),u=Tr(this.urlResolver.resolve(g,!1),y,B,()=>this._retryCallback()).withTimeout(as).withBitrateReporting(this.bitrateSwitcher).withRetryCount(nu).withFinally(()=>{u=null}).send()},h=(g,y,B)=>{pi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),y,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=g=>{let y=r.playbackRate;r.playbackRate!==g&&(t(`Playback rate switch: ${y}=>${g}`),r.playbackRate=g)},b=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let B=re()-1e4,L=0;for(let U=0;U<this.bufferStates.length;U++){let H=this.bufferStates[U];g=Math.min(g,H.buf),H.ts<B&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${g} drop=${L} jitter=${this.sourceJitter}`);let M=g-JA;this.sourceJitter>=0?M-=this.sourceJitter/2:this.sourceJitter-=1,M>3?m(1.15):M>1?m(1.1):M>.3?m(1.05):m(1)}},v=g=>{let y,B=()=>y&&y.start?y.start.length:0,L=x=>y.start[x]/1e3,M=x=>y.dur[x]/1e3,U=x=>y.fragIndex+x,H=(x,_)=>({chunkIdx:U(x),startTS:L(x),dur:M(x),discontinuity:_}),R=()=>{let x=0;if(y&&y.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,z=_;this.sourceJitter>1&&(z+=this.sourceJitter-1);let D=y.dur.length-1;for(;D>=0&&(z-=y.dur[D],!(z<=0));--D);x=Math.min(D,y.dur.length-1-G),x=Math.max(x,0)}return H(x,!0)},A=x=>{let _=B();if(!(_<=0)){if(is(x)){for(let G=0;G<_;G++)if(L(G)>x)return H(G)}return R()}},j=x=>{let _=B(),G=x?x.chunkIdx+1:0,z=G-y.fragIndex;if(!(_<=0)){if(!x||z<0||z-_>KA)return t(`Resync: offset=${z} bChunks=${_} chunk=`+JSON.stringify(x)),R();if(!(z>=_))return H(G-y.fragIndex,!1)}},Q=(x,_,G)=>{l&&l.abort(),l=Tr(this.urlResolver.resolve(x,!0,this.lowLatency),_,G,()=>this._retryCallback()).withTimeout(as).withRetryCount(nu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,_)=>{Q(g,G=>{if(!d())return;y=G;let z=!!y.lowLatency;z!==this.lowLatency&&b(z);let D=0;for(let Le=0;Le<y.dur.length;++Le)D+=y.dur[Le];D>0&&(pi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(D/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,x(A(_))},()=>this._handleNetworkError())},nextChunk:j}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),pi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:g=>{let{videoElement:y,logger:B}=this.params,L=v(e.jidxUrl),M,U,H,R,A=0,j,Q,w,x=()=>{j&&(clearTimeout(j),j=void 0);let F=Math.max(XA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=A+F,Se=re(),Ee=Math.min(1e4,ne-Se);A=Se;let ut=()=>{l||d()&&L.seek(()=>{d()&&(A=re(),_(),x())})};Ee>0?j=window.setTimeout(()=>{this.paused?x():ut()},Ee):ut()},_=()=>{let F;for(;F=L.nextChunk(R);)R=F,Et(F);let ne=L.nextChunk(H);if(ne){if(H&&ne.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}Le(ne)}else x()},G=(F,ne)=>{if(!d()||!this.sourceBuffer)return;let Se,Ee,ut,Zt=lt=>{window.setTimeout(()=>{d()&&G(F,ne)},lt)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),Zt(100);else{let lt=re(),xt=y.currentTime;!this.paused&&y.buffered.length>1&&Q===xt&&lt-w>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),Q!==xt&&(Q=xt,w=lt);let er=this._getBufferSizeSec();if(er>30)B(`Buffered ${er} seconds; delaying appendBuffer`),Zt(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:lt,buf:er}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Dr){if(Dr.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),ut=this.sourceBuffer.buffered.length,ut!==0&&(Se=this.sourceBuffer.buffered.start(0),Ee=xt,Ee-Se>4&&this.sourceBuffer.remove(Se,Ee-3)),Zt(1e3);else throw Dr}}},z=()=>{U&&M&&(B([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(H)]),G(U,function(){U=null,_()}))},D=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),Le=F=>{d()&&h(D(F),(ne,Se)=>{if(d()){if(Se/=1e3,U=ne,H=F,n=F.startTS,Se){let Ee=Math.min(10,F.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ee:Ee}z()}},()=>this._handleNetworkError())},Et=F=>{d()&&(pi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(F),!1)))},ot=F=>{d()&&(e.cachedHeader=F,G(F,()=>{M=!0,z()}))};s=!0,L.seek(F=>{if(d()){if(A=re(),!F){x();return}R=F,!QA(g)||F.startTS>g?Le(F):(H=F,_())}},g),e.cachedHeader?ot(e.cachedHeader):p(e.headerUrl,ot,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),is(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,pi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return is(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=re();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&&au(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=re();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Tr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(as).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;he(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))},zA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as ZA,filter as Fm,fromEvent as ew,interval as tw,isHigher as rw,isInvariantQuality as iw,isLower as aw,merge as sw,Subject as qm,Subscription as nw}from"@vkontakte/videoplayer-shared";var ou=class{constructor(){this.onDroopedVideoFramesLimit$=new qm;this.subscription=new nw;this.playing=!1;this.tracks=[];this.forceChecker$=new qm;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&&!iw(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&&rw(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(ew(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=tw(this.droppedFramesChecker.checkTime).pipe(Fm(()=>this.playing),Fm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(ZA(this.droppedFramesChecker.checkTime)),r=sw(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])=>aw(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}},ss=ou;import{map as ow,Observable as uw}from"@vkontakte/videoplayer-shared";import{fromEvent as lw}from"@vkontakte/videoplayer-shared";var fi=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var cw=(i,e)=>new uw(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||fi()))},k(k({},r),e));a.observe(i);let s=lw(document,"visibilitychange").pipe(ow(n=>!document.hidden||fi())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),ke=cw;var vw=["paused","playing","ready"],yw=["paused","playing","ready"],mi=class{constructor(e){this.subscription=new bw;this.videoState=new C("stopped");this.representations$=new lu([]);this.textTracksManager=new Ae;this.droppedFramesManager=new ss;this.maxSeekBackTime$=new lu(1/0);this.zeroTime$=new lu(void 0);this.liveOffset=new Xe;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:jm.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:gw(u.video),d=u.bitrate/1e3,p=k({},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),uu(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(yw.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&vw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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(ae(this.params.source.url,u))}return;default:return Um(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:jm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Ym(this.videoState.stateChangeStarted$.pipe(ns(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ns(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=le(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(te(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=pe(this.video);this.subscription.add(this.representations$.pipe(ns(a=>a.map(({track:s})=>s)),Gm(a=>!!a.length),mw()).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(hw(),ns(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(dw({zeroTime:this.zeroTime$.pipe(Gm(uu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Ye(this.video,this.params.desiredState.isLooped,t)).add(de(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Pe(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(ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&Sw(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 Um(a.to)}},t)).add(Ym(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,fw(["init"])).pipe(pw(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),ce(this.video)}createLiveDashPlayer(){let e=new hi({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&&uu(t)?t:St(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}),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 b=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;Hm(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;Hm(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(ae(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Wm=mi;var gt=(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)};import{assertNever as Gk,assertNonNullable as Yk,debounce as Wk,ErrorCategory as Du,filter as PS,filterChanged as Ou,fromEvent as Qk,isLowerOrEqual as AS,isNonNullable as zk,isInvariantQuality as Kk,map as Jk,merge as ws,observableFrom as Xk,observeElementSize as Zk,once as wS,Subscription as eR,ValueSubject as tR}from"@vkontakte/videoplayer-shared";var os=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}},Ir=class extends os{constructor(){super(),this.listeners||os.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},bi=class{constructor(){Object.defineProperty(this,"signal",{value:new Ir,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&&(bi.prototype[Symbol.toStringTag]="AbortController",Ir.prototype[Symbol.toStringTag]="AbortSignal");function us(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 cu(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!us({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 Si=us({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Qm=Si?cu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,et=Si?Qm.fetch:window.fetch,rO=Si?Qm.Request:window.Request,tt=Si?bi:window.AbortController,iO=Si?Ir:window.AbortSignal;var ob=He(ui(),1);var rt=()=>window.ManagedMediaSource||window.MediaSource,ls=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},zm=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Km=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as bs,isAndroid as Ew}from"@vkontakte/videoplayer-shared";var ub=Ew(),Re=document.createElement("video"),xw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Pw='video/mp4; codecs="hev1.1.6.L93.B0"',lb='video/webm; codecs="vp09.00.10.08"',cb='video/webm; codecs="av01.0.00M.08"',Aw='audio/mp4; codecs="mp4a.40.2"',ww='audio/webm; codecs="opus"',Jm,Xm,qt={mms:ls(),mse:zm(),hls:!!((Jm=Re.canPlayType)!=null&&Jm.call(Re,"application/x-mpegurl")||(Xm=Re.canPlayType)!=null&&Xm.call(Re,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Zm,eb,fe={mp4:!!((Zm=Re.canPlayType)!=null&&Zm.call(Re,"video/mp4")),webm:!!((eb=Re.canPlayType)!=null&&eb.call(Re,"video/webm")),cmaf:!0},cs,tb,ds,rb,ps,ib,hs,ab,fs,sb,ms,nb,me={h264:!!((tb=(cs=rt())==null?void 0:cs.isTypeSupported)!=null&&tb.call(cs,xw)),h265:!!((rb=(ds=rt())==null?void 0:ds.isTypeSupported)!=null&&rb.call(ds,Pw)),vp9:!!((ib=(ps=rt())==null?void 0:ps.isTypeSupported)!=null&&ib.call(ps,lb)),av1:!!((ab=(hs=rt())==null?void 0:hs.isTypeSupported)!=null&&ab.call(hs,cb)),aac:!!((sb=(fs=rt())==null?void 0:fs.isTypeSupported)!=null&&sb.call(fs,Aw)),opus:!!((nb=(ms=rt())==null?void 0:ms.isTypeSupported)!=null&&nb.call(ms,ww))},Er=(me.h264||me.h265)&&me.aac,Ut,kw=()=>$(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(N(k({},i),{video:N(k({},i.video),{contentType:cb})})),window.navigator.mediaCapabilities.decodingInfo(N(k({},i),{video:N(k({},i.video),{contentType:lb})}))]);Ut={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{kw()}catch(i){console.error(i)}var xr=qt.hls&&fe.mp4,db=()=>Object.keys(me).filter(i=>me[i]),pb=(i,e=!1,t=!1)=>{let r=qt.mse||qt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&fe.mp4&&Er;case"DASH_WEBM":return r&&fe.webm&&me.vp9&&me.opus;case"DASH_WEBM_AV1":return r&&fe.webm&&me.av1&&me.opus;case"DASH_STREAMS":return r&&(fe.mp4&&Er||fe.webm&&(me.vp9||me.av1)&&(me.opus||me.aac));case"DASH_LIVE":return qt.mse&&fe.mp4&&Er;case"DASH_LIVE_CMAF":return r&&fe.mp4&&Er&&fe.cmaf;case"DASH_ONDEMAND":return r&&fe.mp4&&Er;case"HLS":case"HLS_ONDEMAND":return xr||e&&qt.mse&&fe.mp4&&Er;case"HLS_LIVE":case"HLS_LIVE_CMAF":return xr;case"MPEG":return fe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return qt.webrtc&&qt.ws&&me.h264&&(fe.mp4||fe.webm);default:return bs(a)}})},gi=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 Ut?Ut[t].smooth?[t,e]:Ut[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ut?Ut[t].powerEfficient?[t,e]:Ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:bs(i)}return[e,t]},hb=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...gi(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ub)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...gi(i),"DASH_SEP","DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...gi(i),"DASH_STREAMS","HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...gi(i),"MPEG","DASH_SEP","DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...gi(i),"DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND"];default:bs(e)}return xr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},fb=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o;if(ub)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:bs(i)}else xr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},du=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],mb=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,ob.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};var vi=(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 bb=()=>window.matchMedia("(dynamic-range: high)").matches,pu=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};import{abortable as Lu,assertNonNullable as Kt,combine as gS,ErrorCategory as yt,filter as Is,filterChanged as _k,fromEvent as Lr,interval as Cu,isNonNullable as vS,map as Mu,merge as Cr,Subject as yS,Subscription as TS,tap as Nk,throttle as Fk,ValueSubject as be}from"@vkontakte/videoplayer-shared";var $r=He(ui(),1);var Rw=(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)},$w=i=>window.clearTimeout(i),Sb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",hu=Sb?Rw:window.requestIdleCallback,SO=Sb?$w:window.cancelIdleCallback;var dS=He(Xa(),1);import{assertNever as Lw,CurrentClientBrowser as Cw,ErrorCategory as gb,getCurrentBrowser as Mw,Subject as vb}from"@vkontakte/videoplayer-shared";var Dw=16,Ib=!1,yb,Tb;try{Ib=Mw().browser===Cw.Safari&&parseInt((Tb=(yb=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:yb[1])!=null?Tb:"",10)<=Dw}catch(i){console.error(i)}var fu=class{constructor(e){this.bufferFull$=new vb;this.error$=new vb;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:gb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return $(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 $(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 $(this,null,function*(){return new Promise(t=>{let r;Ib&&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:gb.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:Lw(t)}}},Eb=fu;var mu=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as kr,assertNonNullable as it,ErrorCategory as Rr,fromEvent as Au,getExponentialDelay as wu,once as Lk,isNonNullable as cS,isNullable as at,Subject as Ck,Subscription as Mk,ValueSubject as Ui}from"@vkontakte/videoplayer-shared";var q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Pr=class extends q{};var yi=class extends q{};var Ti=class extends q{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var Ii=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=class extends q{constructor(t,r){super(t,r);this.data=this.content}};var K=class extends q{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Ht=class extends K{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 Pi=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends K{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 ki=class extends K{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ri=class extends K{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var $i=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends K{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 Ci=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends K{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var Oi=class extends q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends K{constructor(t,r){super(t,r);this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Vi=class extends K{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 _i=class extends K{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 Bw={ftyp:Ti,moov:Ii,moof:Ei,mdat:xi,sidx:Ht,trak:Pi,mdia:$i,mfhd:Di,tkhd:Li,traf:Oi,tfhd:Bi,tfdt:Vi,trun:_i,minf:Ci,sv3d:Ai,st3d:wi,prhd:ki,proj:Mi,equi:Ri,uuid:yi,unknown:Pr},jt=class i{constructor(e={}){this.options=k({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=Bw[e];return r?new r(t,new i):new Pr(t,new i)}};var Ar=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 _w=new TextDecoder("ascii"),Nw=i=>_w.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Fw=i=>{let e=new Ht(i,new jt),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})},qw=(i,e)=>{let r=new jt().parse(i),a=new Ar(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)},Uw=(i,e)=>{let r=new jt().parse(i),s=new Ar(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},Hw=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 jt().parse(i),a=new Ar(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},xb={validateData:Nw,parseInit:Hw,getIndexRange:()=>{},parseSegments:Fw,parseFeedableSegmentChunk:qw,getSegmentEndTime:Uw};import{assertNonNullable as Su,isNonNullable as kb,isNullable as Gw}from"@vkontakte/videoplayer-shared";import{assertNever as jw}from"@vkontakte/videoplayer-shared";var Pb={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"}},Ab=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=Ni(i,t),a=r in Pb,s=a?Pb[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=Ni(u),d=l*Ue(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}},Ni=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Ue(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Ue(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Ue(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},_e=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Ni(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:jw(e)}},Gt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Ab(r);if(!e(a))return;a.type==="master"&&Gt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},wb=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Ab(i);return Gt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=_e(o,n):s===17026?t=_e(o,n):s===17029&&(r=_e(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Rb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Yw=[231,22612,22743,167,171,163,160,175],Ww=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Gt(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=_e(m,h);l=Ni(S)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=_e(m,h):p===17545?a=_e(m,h):p===21420&&l===475249515?u=_e(m,h):p===374648427?Gt(m,({tag:S,type:v,value:I})=>S===30321?(c=_e(I,v)===1,!1):!0):s&&n&&Rb.includes(p)&&(o=!0),!o}),Su(e,"Failed to parse webm Segment start"),Su(t,"Failed to parse webm Segment end"),Su(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}}}},Qw=i=>{if(Gw(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zw=(i,e)=>{let t=!1,r=!1,a=o=>kb(o.time)&&kb(o.position),s=[],n;return Gt(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=_e(l,u));break;case 183:break;case 241:n&&(n.position=_e(l,u));break;default:t&&Rb.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}}})},Kw=i=>{let e=0,t=!1;try{Gt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Yw.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},$b={validateData:wb,parseInit:Ww,getIndexRange:Qw,parseSegments:zw,parseFeedableSegmentChunk:Kw};var Fi=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return $b;case"mp4":return xb}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Iu=He(eS(),1);import{isNonNullable as rS,isNullable as iS}from"@vkontakte/videoplayer-shared";var tS=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var aS=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},Yt=(i,e)=>{let t=i;t=(0,Iu.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,Iu.default)(t,n,(o,u)=>iS(s)?o:iS(u)?s:s.padStart(parseInt(u,10),"0"))}return t},nS=(i,e)=>{var g,y,B,L,M,U,H,R,A,j,Q,w,x,_,G,z,D,Le,Et,ot,F,ne,Se,Ee,ut,Zt,lt,xt,er,Dr,Ku,Ju,Xu,Zu,el,tl,rl,il,al,sl,nl,ol,ul,ll,cl,dl,pl,hl;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(B=(y=(g=s.querySelector("BaseURL"))==null?void 0:g.textContent)==null?void 0:y.trim())!=null?B:"",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"),b=s.getElementsByTagName("vk:Attrs")[0],S=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=aS(h);else if(m){let ge=aS(m);rS(ge)&&(p=ge)}else S&&(p=parseInt(S,10));let v=0,I=(M=(L=s.getAttribute("profiles"))==null?void 0:L.split(","))!=null?M:[];for(let ge of u){let pg=(U=ge.getAttribute("id"))!=null?U:"id"+(v++).toString(10),Or=(H=ge.getAttribute("mimeType"))!=null?H:"",qs=(R=ge.getAttribute("codecs"))!=null?R:"",Us=(A=ge.getAttribute("contentType"))!=null?A:Or==null?void 0:Or.split("/")[0],hg=(Q=(j=ge.getAttribute("profiles"))==null?void 0:j.split(","))!=null?Q:[],fg=(w=ge.getAttribute("lang"))!=null?w:void 0,mg=(G=(_=(x=ge.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:_.trim())!=null?G:void 0,bg=ge.querySelectorAll("Representation"),Sg=ge.querySelector("SegmentTemplate"),Br=Us,X={id:pg,language:fg,label:mg,codecs:qs,hdr:Br==="video"&&pu(qs),mime:Or,representations:[]};for(let J of bg){let gg=(z=J.getAttribute("lang"))!=null?z:void 0,vg=(D=J.getAttribute("label"))!=null?D:void 0,yg=(ot=(Et=(Le=J.querySelector("BaseURL"))==null?void 0:Le.textContent)==null?void 0:Et.trim())!=null?ot:"",Hs=new URL(yg||o,e).toString(),tr=(F=J.getAttribute("mimeType"))!=null?F:Or,sa=(Se=(ne=J.getAttribute("codecs"))!=null?ne:qs)!=null?Se:"",js;if(Us==="text"){let Pt=J.getAttribute("id")||"",Gs=Pt.includes("_auto");js={id:Pt,isAuto:Gs,kind:"text",url:Hs}}else{let Pt=(ut=(Ee=J.getAttribute("contentType"))!=null?Ee:tr==null?void 0:tr.split("/")[0])!=null?ut:Us,Gs=(lt=(Zt=ge.getAttribute("profiles"))==null?void 0:Zt.split(","))!=null?lt:[],Tg=parseInt((xt=J.getAttribute("width"))!=null?xt:"",10),fl=parseInt((er=J.getAttribute("height"))!=null?er:"",10),ml=parseInt((Dr=J.getAttribute("bandwidth"))!=null?Dr:"",10)/1e3,bl=(Ku=J.getAttribute("frameRate"))!=null?Ku:"",Ig=(Ju=J.getAttribute("quality"))!=null?Ju:void 0,Eg=bl?tS(bl):void 0,xg=(Xu=J.getAttribute("id"))!=null?Xu:"id"+(v++).toString(10),Pg=Pt==="video"?`${fl}p`:Pt==="audio"?`${ml}Kbps`:sa,Ag=`${xg}@${Pg}`,wg=[...I,...hg,...Gs],Ys,kg=J.querySelector("SegmentBase"),At=(Zu=J.querySelector("SegmentTemplate"))!=null?Zu:Sg;if(kg){let wt=(tl=(el=J.querySelector("SegmentBase Initialization"))==null?void 0:el.getAttribute("range"))!=null?tl:"",[kt,Qs]=wt.split("-").map(rr=>parseInt(rr,10)),ct={from:kt,to:Qs},Vr=(rl=J.querySelector("SegmentBase"))==null?void 0:rl.getAttribute("indexRange"),[zs,na]=Vr?Vr.split("-").map(rr=>parseInt(rr,10)):[],_r=Vr?{from:zs,to:na}:void 0;Ys={type:"byteRange",url:Hs,initRange:ct,indexRange:_r}}else if(At){let wt={representationId:(il=J.getAttribute("id"))!=null?il:void 0,bandwidth:(al=J.getAttribute("bandwidth"))!=null?al:void 0},kt=parseInt((sl=At.getAttribute("timescale"))!=null?sl:"",10),Qs=(nl=At.getAttribute("initialization"))!=null?nl:"",ct=At.getAttribute("media"),Vr=(ul=parseInt((ol=At.getAttribute("startNumber"))!=null?ol:"",10))!=null?ul:1,zs=Yt(Qs,wt);if(!ct)throw new ReferenceError("No media attribute in SegmentTemplate");let na=(ll=At.querySelectorAll("SegmentTimeline S"))!=null?ll:[],_r=[],rr=0,Ks="",Js=0;if(na.length){let oa=Vr,Ce=0;for(let ir of na){let qe=parseInt((cl=ir.getAttribute("d"))!=null?cl:"",10),Rt=parseInt((dl=ir.getAttribute("r"))!=null?dl:"",10)||0,ua=parseInt((pl=ir.getAttribute("t"))!=null?pl:"",10);Ce=Number.isFinite(ua)?ua:Ce;let Xs=qe/kt*1e3,Zs=Ce/kt*1e3;for(let la=0;la<Rt+1;la++){let $g=Yt(ct,N(k({},wt),{segmentNumber:oa.toString(10),segmentTime:(Ce+la*qe).toString(10)})),Sl=(Zs!=null?Zs:0)+la*Xs,Lg=Sl+Xs;oa++,_r.push({time:{from:Sl,to:Lg},url:$g})}Ce+=(Rt+1)*qe,rr+=(Rt+1)*Xs}Js=Ce/kt*1e3,Ks=Yt(ct,N(k({},wt),{segmentNumber:oa.toString(10),segmentTime:Ce.toString(10)}))}else if(rS(p)){let Ce=parseInt((hl=At.getAttribute("duration"))!=null?hl:"",10)/kt*1e3,ir=Math.ceil(p/Ce),qe=0;for(let Rt=1;Rt<ir;Rt++){let ua=Yt(ct,N(k({},wt),{segmentNumber:Rt.toString(10),segmentTime:qe.toString(10)}));_r.push({time:{from:qe,to:qe+Ce},url:ua}),qe+=Ce}Js=qe,Ks=Yt(ct,N(k({},wt),{segmentNumber:ir.toString(10),segmentTime:qe.toString(10)}))}let Rg={time:{from:Js,to:1/0},url:Ks};Ys={type:"template",baseUrl:Hs,segmentTemplateUrl:ct,initUrl:zs,totalSegmentsDurationMs:rr,segments:_r,nextSegmentBeyondManifest:Rg,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!tr)continue;let Ws={video:"video",audio:"audio",text:"text"}[Pt];if(!Ws)continue;Br||(Br=Ws),js={id:Ag,kind:Ws,segmentReference:Ys,profiles:wg,duration:p,bitrate:ml,mime:tr,codecs:sa,width:Tg,height:fl,fps:Eg,quality:Ig}}X.language||(X.language=gg),X.label||(X.label=vg),X.mime||(X.mime=tr),X.codecs||(X.codecs=sa),X.hdr||(X.hdr=Br==="video"&&pu(sa)),X.representations.push(js)}Br&&a[Br].push(X)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:a}};var xu=He(ui(),1);import{videoSizeToQuality as $k}from"@vkontakte/videoplayer-shared";var oS=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?mt(s):void 0)!=null?o:$k({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},uS=({id:i,bitrate:e})=>({id:i,bitrate:e}),Ss=(i,e,t)=>{var a;let r=e.indexOf(i);return(a=(0,xu.default)(t,Math.round(t.length*r/e.length)))!=null?a:(0,xu.default)(t,-1)},lS=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Pu=i=>"url"in i,Wt=i=>i.type==="template",qi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Hi=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new Ui(0);this.onLastSegment$=new Ui(!1);this.fullyBuffered$=new Ui(!1);this.playingRepresentation$=new Ui(void 0);this.playingRepresentationInit$=new Ui(void 0);this.error$=new Ck;this.gaps=[];this.subscription=new Mk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new tt;this.destroyAbortController=new tt;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=kr(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){let t=this.representations.get(e);it(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Eb(this.sourceBuffer),this.subscription.add(Au(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:Rr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(Au(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Rr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,mu(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);it(r,"No init buffer for starting representation"),it(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=kr(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);it(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(at(a)||at(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),it(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();cS(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))})}.bind(this));this.seekLive=kr(this.destroyAbortController.signal,function(e){return Z(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||!Wt(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);it(a);let s=this.segments.get(r);it(s,"No segments for starting representation");let n=this.initData.get(r);if(it(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 tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(at(e)||at(this.downloadingRepresentationId)||at(this.playingRepresentationId)||at(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(it(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=gt(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)&&mu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=gt(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&&gt(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;cS(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].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||!Wt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>N(k({},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])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!Wt(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Yt(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:n})}}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 b=p<=r&&h>=r,S=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&S&&I&&this.sourceBuffer&&!vi(this.sourceBuffer.buffered,r))&&S&&I});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 $(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 $(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 kr(o,function(){return Z(this,null,function*(){let c=wu(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(this.isActiveLowLatency()){let p=t.segmentReference.timescale,h=Fi(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]),qi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return $(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 kr(n,function(){return Z(this,null,function*(){let u=wu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Au(window,"online").pipe(Lk()).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),qi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Wt(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:Rr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Wt(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:Rr.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 $(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=Fi(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}){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 b=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,v=b<a,I=S<=a;if(d.status==="downloading"&&v&&I){d.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(T,s).then(g=>g&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(c.loadedBytes=Math.min(h,a-b),c.loadedBytes>c.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===h?T:Fi(o.mime).parseFeedableSegmentChunk(T);g!=null&&g.byteLength&&(d.status="partially_fed",c.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,s).then(y=>{if(s.aborted)n();else if(y)c.fedBytes+=g.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;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",Pu(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.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=hu(()=>(0,dS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return $(this,null,function*(){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?kr(this.destroyAbortController.signal,function(){return Z(this,null,function*(){let o=wu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Fi(e.mime),a)).then(o=>$(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&&Wt(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:Rr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,r=!1){return $(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||at(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=Pu(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=hu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Rr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(at(this.sourceBuffer)||at(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 ji=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var pS=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}};import{abortable as Gi,assertNever as hS,fromEvent as fS,merge as Dk,now as ku,Subscription as Ok,ValueSubject as Ru}from"@vkontakte/videoplayer-shared";var gs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Ru(void 0);this.lastConnectionReused$=new Ru(void 0);this.lastRequestFirstBytes$=new Ru(void 0);this.abortAllController=new tt;this.subscription=new Ok;this.fetchManifest=Gi(this.abortAllController.signal,function(e){return Z(this,null,function*(){let t=e;this.requestQuic&&(t=ji(t));let r=yield et(t,{signal:this.abortAllController.signal}).catch(Yi);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=Gi(this.abortAllController.signal,function(l){return Z(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 U,H;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let R=new URL(c,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),c=R.toString();break}default:hS(t)}this.requestQuic&&(c=ji(c));let p=this.abortAllController.signal,h;if(n){let R=new tt;if(h=Dk(fS(this.abortAllController.signal,"abort"),fS(n,"abort")).subscribe(()=>{try{R.abort()}catch(A){Yi(A)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(A){Yi(A)}p=R.signal}let m=ku(),b=yield et(c,{priority:s,headers:d,signal:p}).catch(Yi),S=ku();if(!b)return h==null||h.unsubscribe(),null;if((U=this.throughputEstimator)==null||U.addRawRtt(S-m),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[v,I]=b.body.tee(),T=v.getReader();o&&((H=this.throughputEstimator)==null||H.trackStream(I,u));let g=0,y=new Uint8Array(0),B=!1,L=R=>{h==null||h.unsubscribe(),B=!0,Yi(R)},M=Gi(p,function(j){return Z(this,arguments,function*({done:R,value:A}){if(g===0&&this.lastRequestFirstBytes$.next(ku()-m),p.aborted){h==null||h.unsubscribe();return}if(!R&&A){let Q=new Uint8Array(y.length+A.length);Q.set(y),Q.set(A,y.length),y=Q,g+=A.byteLength,a==null||a(new DataView(y.buffer),g),yield T==null?void 0:T.read().then(M,L)}})}.bind(this));return yield T==null?void 0:T.read().then(M,L),h==null||h.unsubscribe(),B?null:y.buffer})}.bind(this));this.fetchByteRangeRepresentation=Gi(this.abortAllController.signal,function(e,t,r){return Z(this,null,function*(){var v;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=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let I=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=Gi(this.abortAllController.signal,function(e,t){return Z(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=>N(k({},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}=pS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return $(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:hS(a)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Yi=i=>{if(!qi(i))throw i};var Qt=(i,e,t)=>t*e+(1-t)*i,$u=(i,e)=>i.reduce((t,r)=>t+r,0)/e,mS=(i,e,t,r)=>{let a=0,s=t,n=$u(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};import{isNullable as Bk,ValueSubject as bS}from"@vkontakte/videoplayer-shared";var vt=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 bS(e.initial),this.debounced$=new bS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new se(`raw_${t}`),this.smoothedSeries$=new se(`smoothed_${t}`),this.reportedSeries$=new se(`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+=Ue(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)&&(Bk(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 vs=class extends vt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Qt(this.slow,t,this.params.emaAlphaSlow),this.fast=Qt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var ys=class extends vt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=$u(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Qt(this.emaSmoothed,t,this.params.emaAlpha);let a=mS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var Ts=class extends vt{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?Qt(this.smoothed,t,this.params.emaAlpha):t}};var zt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new vs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ys({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 Ts(k({initial:e,label:"liveEdgeDelay"},t))}};var SS=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var IS=["timeupdate","progress","play","seeked","stalled","waiting"];var Es=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new TS;this.representationSubscription=new TS;this.state$=new C("none");this.currentVideoRepresentation$=new be(void 0);this.currentVideoRepresentationInit$=new be(void 0);this.currentAudioRepresentation$=new be(void 0);this.currentVideoSegmentLength$=new be(0);this.currentAudioSegmentLength$=new be(0);this.error$=new yS;this.lastConnectionType$=new be(void 0);this.lastConnectionReused$=new be(void 0);this.lastRequestFirstBytes$=new be(void 0);this.isLive$=new be(!1);this.liveDuration$=new be(0);this.liveAvailabilityStartTime$=new be(void 0);this.bufferLength$=new be(0);this.liveLoadBufferLength$=new be(0);this.livePositionFromPlayer$=new be(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new yS;this.gapWatchdogActive=!1;this.destroyController=new tt;this.initManifest=Lu(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var a;this.element=e,this.manifestUrlString=ae(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:yt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Lu(this.destroyController.signal,function(){return Z(this,null,function*(){var s;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:yt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=nS(e!=null?e:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:yt.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!t)return null;let r=(n,o,u)=>{var l,c,d,p;return!!((c=(l=this.element)==null?void 0:l.canPlayType)!=null&&c.call(l,o)&&((p=(d=rt())==null?void 0:d.isTypeSupported)!=null&&p.call(d,`${o}; codecs="${u}"`))||n==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((s=t.duration)!=null?s:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>r(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=mb(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=bb(),p=this.tuning.preferHDR,h=a.video.some(b=>b.hdr),m=a.video.some(b=>!b.hdr);d&&p&&h?a.video=a.video.filter(b=>b.hdr):m&&(a.video=a.video.filter(b=>!b.hdr))}}return N(k({},t),{streams:a})})}.bind(this));this.initRepresentations=Lu(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var d;Kt(this.manifest),Kt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(Lr(p,"error").pipe(Is(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:yt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Km():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ls())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=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Hi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],vS(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Hi("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(Cu(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Yo(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(Cr(...IS.filter(p=>p!=="waiting").map(p=>Lr(this.element,p))).pipe(Mu(p=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),_k(),Is(p=>!!p),Nk(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(Is(h=>this.isActiveLowLatency&&!!h)).subscribe(h=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(h=>{if(!this.isActiveLowLatency||!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-m,I=1;Math.abs(v)>b&&(I=1+Math.sign(v)*S),SS(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let v=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var g,y;return(y=(g=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:g.to)!=null?y:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(gS({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Fk(1e3)).subscribe(b=>$(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(Kt(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,v=Yo(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),g=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,B=this.isActiveLowLatency?m:h,L=3;if(this.isActiveLowLatency?L=0:B<T+y&&B>=T?L=1:v!==0&&B<T&&(L=2),isFinite(h)&&(p=h>p?h:p),L===2||L===1){let M=p-(T+g),U=this.normolizeLiveOffset(Math.trunc(v+M/S)),H=Math.abs(U-v),R;!h||H<=this.tuning.dashCmafLive.offsetCalculationError?R=v:U>0&&H>this.tuning.dashCmafLive.offsetCalculationError?R=U:R=0,this.manifestUrlString=ae(this.manifestUrlString,R,2)}L!==3&&L!==0&&(p=0,this.updateLive())})))}let u=Cr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Mu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Cr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Mu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Cr(this.forceEnded$,gS({allBuffersFull:u,someBufferEnded:l}).pipe(Is(({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:yt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Cr(...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&&vS(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=Cu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:yt.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new gs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=zt.getLiveEstimatedDelaySmoothedValue(0,k({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return $(this,null,function*(){var r,a,s,n;Kt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=ae(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(){Kt(this.element),this.state$.setState("running"),this.subscription.add(Cr(...IS.map(e=>Lr(this.element,e)),Lr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:yt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Lr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Lr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&vi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Cu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:yt.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return $(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var a,s,n,o,u;Kt(this.element),Kt(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),vi(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 $(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&&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 xs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ps=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/Ue(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=k({},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*Ue(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 ES=`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 Gn=`#ifdef GL_ES
48
+ `;var xS=`#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 br=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 mr(this.params.fov,this.params.orientation),this.cameraRotationManager=new fr(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(Hn,this.gl.VERTEX_SHADER),i=this.createShader(Gn,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,n=e+i,u=t-r,d=e+i,c=t+r,l=e-i,p=t+r;return[a,s,n,u,d,c,l,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 bt=class{constructor(e){this.subscription=new xl;this.videoState=new L("stopped");this.elementSize$=new qn(void 0);this.textTracksManager=new me;this.droppedFramesManager=new rr;this.videoTracks$=new qn([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Zi;this.textTracks=[];this.syncPlayback=()=>{var s,n,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=(n=(s=this.liveOffset)==null?void 0:s.getTotalPausedTime())!=null?n: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"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&T(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"&&T(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"&&T(this.params.desiredState.playbackState,"paused");return;default:return bl(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new br(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=re(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(K(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new hr({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=ne(this.video),r=this.constructor.name,a=n=>{e.error$.next({id:r,category:Ma.WTF,message:`${r} internal logic error`,thrown:n})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(n,u)=>this.subscription.add(n.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(gr(d=>d.map(({track:c})=>c)))}),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(Sl(yl),El()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(gr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ke(this.video,t.isLooped,r)),this.subscription.add(se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(he(this.video,t.playbackRate,i.playbackRateState$,r)),a(Il(this.video),this.elementSize$),a(be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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})=>{var c;if(d==="manifest_ready"){let l=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();jn(p,"Manifest not loaded or empty");let h=Array.from(p.audio).sort((S,b)=>b.bitrate-S.bitrate),m=Array.from(p.video).sort((S,b)=>b.bitrate-S.bitrate),f=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let S of h){let b=Pn(S);b&&this.audioTracks.push({track:b,representation:S})}for(let S of m){let b=xn(S);if(b){l.push({track:b,representation:S});let $=!this.params.tuning.isAudioDisabled&&kn(h,m,S);$&&this.audioRepresentations.set(S.id,$)}}this.videoTracks$.next(l);for(let S of f){let b=An(S);b&&this.textTracks.push({track:b,representation:S})}this.params.output.availableVideoTracks$.next(l.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));let g=this.selectVideoRepresentation();jn(g),this.player.initRepresentations(g.id,(c=this.audioRepresentations.get(g.id))==null?void 0:c.id,this.params.sourceHls)}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:Ma.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(Sr(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,vl(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let h=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(l){let f=l.id;!this.params.output.elementVisible$.getValue()&&h&&(f=this.videoTracks$.getValue().map(S=>S.representation).sort((S,b)=>b.bitrate-S.bitrate).filter(S=>{let b=Yn(S),$=Yn(l);if(b&&$)return Wn(b,$)&&Wn(b,m)}).map(S=>S.id)[0]),this.player.switchRepresentation("video",f).catch(s);let g=this.audioRepresentations.get(l.id);g&&this.player.switchRepresentation("audio",g.id).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(Qn(),gr(d=>{var c;return d&&((c=this.videoTracks$.getValue().find(({representation:{id:l}})=>l===d))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var c,l;if(d!=null&&d.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.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(),(l=this.params.tuning.spherical)!=null&&l.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 n=t.playbackState.stateChangeStarted$.pipe(gr(({to:d})=>d==="ready"),Qn());this.subscription.add(Sr(n,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(Sr(n,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Sr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Tl(["init"])).pipe(gl(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var l,p,h,m,f,g,S;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(l=this.params.desiredState.videoTrack.getState())==null?void 0:l.id,i=(p=this.videoTracks$.getValue().find(({track:{id:b}})=>b===t))==null?void 0:p.track,r=this.params.output.currentVideoTrack$.getValue(),a=Be(this.video.buffered,this.video.currentTime*1e3),s=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,n=Math.min(a/Math.min(s,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(i&&!e&&(m=(h=this.audioRepresentations.get(i.id))==null?void 0:h.bitrate)!=null?m:0,r&&(g=(f=this.audioRepresentations.get(r.id))==null?void 0:f.bitrate)!=null?g:0),d=ze(this.videoTracks$.getValue().map(({track:b})=>b),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:n,current:r,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?d!=null?d:i:i!=null?i:d;return c&&((S=this.videoTracks$.getValue().find(({track:b})=>b===c))==null?void 0:S.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){oe(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ma.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),ae(this.video)}};var Pi=class extends bt{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)}};import{combine as zn,interval as Pl,map as kl}from"@vkontakte/videoplayer-shared";var ki=class extends bt{constructor(e){super(e),this.liveOffset=new De}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(zn({interval:Pl(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(zn({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(kl(({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 n;this.params.output.position$.next(e/1e3),(n=this.liveOffset)==null||n.resetTo(s,r)})}};import{assertNever as Ai,assertNonNullable as Kn,debounce as Al,ErrorCategory as vr,filter as wl,isNonNullable as $l,isNullable as Ll,map as yr,merge as Rl,Observable as Ml,observableFrom as Dl,Subscription as Cl,videoSizeToQuality as Bl}from"@vkontakte/videoplayer-shared";var Ee={};var Dt=(o,e)=>new Ml(t=>{let i=(r,a)=>t.next(a);return o.on(e,i),()=>o.off(e,i)}),wi=class{constructor(e){this.subscription=new Cl;this.videoState=new L("initializing");this.textTracksManager=new me;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:Ai(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ai(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ai(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ai(e)}break;default:Ai(t)}};this.video=re(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(K(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),ae(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:vr.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||(Ee.Hls=r.default,Ee.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){Kn(Ee.Hls,"hls.js not loaded"),this.hls=new Ee.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Kn(Ee.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:vr.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ne(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,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(ke(this.video,e.isLooped,i)),this.subscription.add(se(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(he(this.video,e.playbackRate,r.playbackRateState$,i)),a(be(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(yr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(Dt(this.hls,Ee.Events.ERROR).subscribe(d=>{var c;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:vr.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(c=d.err)==null?void 0:c.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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(Dt(this.hls,Ee.Events.MANIFEST_PARSED).pipe(yr(({levels:d})=>d.reduce((c,l)=>{var b,$;let p=l.name||l.height.toString(10),{width:h,height:m}=l,f=($=Ye((b=l.attrs.QUALITY)!=null?b:""))!=null?$:Bl({width:h,height:m});if(!f)return c;let g=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:f,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:S,level:l}),c.push(S),c},[]))),t.availableVideoTracks$),a(Dt(this.hls,Ee.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let c=[];for(let l of d.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang,f="internal";c.push({id:p,url:h,language:m,type:f})}e.internalTextTracks.startTransitionTo(c)}}),a(Dt(this.hls,Ee.Events.LEVEL_LOADING).pipe(yr(({url:d})=>K(d))),t.hostname$),a(Dt(this.hls,Ee.Events.FRAG_CHANGED),d=>{var p,h,m,f;let{video:c,audio:l}=d.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=l==null?void 0:l.endPTS)!=null?m:0)-((f=l==null?void 0:l.startPTS)!=null?f:0))*1e3)}),this.subscription.add(je(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 c;return(c=Array.from(this.trackLevels.values()).find(({level:l})=>l===d))==null?void 0:c.track},n=Dt(this.hls,Ee.Events.LEVEL_SWITCHED).pipe(yr(({level:d})=>s(this.hls.levels[d])));n.pipe(wl($l)).subscribe(t.currentVideoTrack$,i),this.subscription.add(je(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{var m;if(Ll(d))return;let c=(m=this.trackLevels.get(d.id))==null?void 0:m.level;if(!c)return;let l=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:n,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=Rl(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Dl(["init"])).pipe(Al(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 w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield oe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vr.DOM,thrown:t})))||(this.videoState.setState("paused"),T(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"),T(this.params.desiredState.playbackState,"stopped",!0)}};var Jn="X-Playback-Duration",Da=o=>w(void 0,null,function*(){var r;let e=yield fetch(o),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(Jn)?parseInt(e.headers.get(Jn),10):void 0});import{assertNever as Ul,combine as Hl,debounce as Gl,ErrorCategory as Ir,filter as jl,filterChanged as Ql,isNonNullable as Zn,isNullable as Er,map as eo,merge as Wl,observableFrom as Yl,Subscription as ql,ValueSubject as Ba,VideoQuality as zl}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as Vl,getExponentialDelay as Ol}from"@vkontakte/videoplayer-shared";var _l=o=>{let e=null;if(o.QUALITY&&(e=Ye(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Vl({width:t,height:i})}return e!=null?e:null},Nl=(o,e)=>{var a,s;let t=o.split(`
92
- `),i=[],r=[];for(let n=0;n<t.length;n++){let u=t[n],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!c)){if(d){let l=Object.fromEntries(d[1].split(",").map(b=>b.split("="))),p=(a=l.QUALITY)!=null?a:`stream-${l.BANDWIDTH}`,h=_l(l),m;l.BANDWIDTH&&(m=parseInt(l.BANDWIDTH,10)/1e3||void 0),!m&&l["AVERAGE-BANDWIDTH"]&&(m=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let f=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,g;if(l.RESOLUTION){let[b,$]=l.RESOLUTION.split("x").map(v=>parseInt(v,10));b&&$&&(g={width:b,height:$})}let S=new URL(t[++n],e).toString();h&&i.push({id:p,quality:h,url:S,bandwidth:m,size:g,fps:f})}if(c){let l=Object.fromEntries(c[1].split(",").map(f=>f.split("=")).map(([f,g])=>[f,g.replace(/^"|"$/g,"")])),p=(s=l.URI)==null?void 0:s.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,m=l.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Fl=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),Ca=0,Xn=(i,...r)=>w(void 0,[i,...r],function*(o,e=o,t){let s=yield(yield fetch(o)).text();Ca+=1;try{let{qualityManifests:n,textTracks:u}=Nl(s,e);return{qualityManifests:n,textTracks:u}}catch(n){if(Ca<=t.manifestRetryMaxCount)return yield Fl(Ol(Ca-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Xn(o,e,t)}return{qualityManifests:[],textTracks:[]}}),Tr=Xn;var $i=class{constructor(e){this.subscription=new ql;this.videoState=new L("stopped");this.textTracksManager=new me;this.manifests$=new Ba([]);this.liveOffset=new De;this.manifestStartTime$=new Ba(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(),n=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"),T(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||n){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.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"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(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"&&T(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 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(r==null?void 0:r.to)==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Ul(t)}};var t;this.params=e,this.video=re(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:zl.INVARIANT,url:this.params.source.url},Tr(X(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:Ir.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ir.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(K(this.params.source.url)),this.maxSeekBackTime$=new Ba((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,d,c,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(l=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(d=t.getState())==null?void 0:d.id)!=null?l:"master",s=this.manifests$.getValue();if(!s.length)return;let n=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:Ir.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=ne(this.video),a=(n,u)=>this.subscription.add(n.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(se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(he(this.video,t.playbackRate,r.playbackRateState$,i)),a(be(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(Ql(),eo(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Zn(d.to)){let l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(K(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,d,c;let n=(c=(d=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:d.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(Hl({startTime:this.manifestStartTime$.pipe(jl(Zn)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:u})=>this.params.output.liveTime$.next(n+u*1e3),i)),this.subscription.add(this.manifests$.pipe(eo(n=>n.map(({id:u,quality:d,size:c,bandwidth:l,fps:p})=>({id:u,quality:d,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let s=Wl(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Yl(["init"])).pipe(Gl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ae(this.video)}prepare(){var n,u;let e=this.selectManifest();if(Er(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:c}=(u=(n=t==null?void 0:t.to)!=null?n:i)!=null?u:{};for(let[l,p]of[[d,"mq"],[c,"lq"]]){let h=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=X(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),Da(s).then(d=>{var c;if(!Er(d))this.maxSeekBackTime$.next(d);else{let l=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Er(l)||!isFinite(l))try{fetch(s).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 f=new URL(h,s).toString();Da(f).then(g=>{Er(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ir.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()}};import{assertNever as Kl,debounce as Jl,ErrorCategory as Va,fromEvent as Oa,isNonNullable as Xl,isNullable as Zl,map as to,merge as io,observableFrom as ro,Subscription as ec,ValueSubject as tc,VideoQuality as ic,isIOS as rc}from"@vkontakte/videoplayer-shared";var Li=class{constructor(e){this.subscription=new ec;this.videoState=new L("stopped");this.textTracksManager=new me;this.manifests$=new tc([]);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(),n=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"),T(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||n){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:l}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Kl(t)}};this.params=e,this.video=re(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ic.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(K(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Tr(X(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:Va.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,d,c,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(l=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(d=t.getState())==null?void 0:d.id)!=null?l:"master",s=this.manifests$.getValue();if(!s.length)return;let n=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:Va.WTF,message:"HlsProvider internal logic error",thrown:n})},r=ne(this.video),a=(n,u)=>this.subscription.add(n.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(to(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ke(this.video,t.isLooped,i)),this.subscription.add(se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(he(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var l;let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Xl(d.to)){let p=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(K(h.url));let m=this.params.desiredState.playbackRate.getState(),f=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(m!==f){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(m),g.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n.state==="requested"&&this.seek(n.position)},i))),this.subscription.add(this.manifests$.pipe(to(n=>n.map(({id:u,quality:d,size:c,bandwidth:l,fps:p})=>({id:u,quality:d,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!rc()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(io(Oa(n,"addtrack"),Oa(n,"removetrack"),Oa(n,"change"),ro(["init"])).subscribe(()=>{for(let u=0;u<n.length;u++)n[u].mode="hidden"},i))}let s=io(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ro(["init"])).pipe(Jl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ae(this.video)}prepare(){var a,s;let e=this.selectManifest();if(Zl(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:n,min:u}=(s=(a=t==null?void 0:t.to)!=null?a:i)!=null?s:{};for(let[d,c]of[[n,"mq"],[u,"lq"]]){let l=String(parseFloat(d||""));c&&d&&r.searchParams.set(c,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Va.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as ac,assertNonNullable as ao,debounce as sc,ErrorCategory as so,isHigher as nc,isHigherOrEqual as oc,isInvariantQuality as no,isLowerOrEqual as uc,isNonNullable as dc,merge as lc,observableFrom as cc,Subscription as pc,map as hc}from"@vkontakte/videoplayer-shared";var Ri=class{constructor(e){this.subscription=new pc;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new me;this.syncPlayback=()=>{var u,d,c;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"),T(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(),n=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:l}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),s.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(d=this.trackUrls[s.to.id])==null?void 0:d.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return ac(e)}};this.params=e,this.video=re(e.container),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=n=>{e.error$.next({id:"MpegProvider",category:so.WTF,message:"MpegProvider internal logic error",thrown:n})},r=ne(this.video),a=(n,u)=>this.subscription.add(n.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(hc(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ke(this.video,t.isLooped,i)),this.subscription.add(se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(he(this.video,t.playbackRate,r.playbackRateState$,i)),a(be(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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 n=this.params.desiredState.videoTrack.getTransition();if(n&&dc(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let c=this.params.desiredState.playbackRate.getState(),l=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(c!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=lc(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,cc(["init"])).pipe(sc(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),ae(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;ao(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ao(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ti(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(K(t))}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:so.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,a,s,n;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(l=>!no(l.track.quality)&&uc(l.track.quality,e)))==null?void 0:a.track,d=(s=this.params.desiredState.videoTrack.getState())==null?void 0:s.id,c=(n=this.trackUrls[d!=null?d:"0"])==null?void 0:n.track;if(u&&c&&oc(c.quality,u.quality)&&(t=u),!t){let l=Object.values(this.trackUrls).filter(h=>!no(h.track.quality)&&nc(h.track.quality,e)),p=l.length;p&&(t=l[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(d=>d.track);t=ze(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})}};import{assertNever as uo,debounce as gc,merge as lo,observableFrom as Sc,Subscription as vc,map as co,ValueSubject as yc,ErrorCategory as Na,VideoQuality as Tc}from"@vkontakte/videoplayer-shared";import{ErrorCategory as mc}from"@vkontakte/videoplayer-shared";var oo=["stun:videostun.mycdn.me:80"],fc=1e3,bc=3,_a=()=>null,xr=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=_a;this.externalStopCallback=_a;this.externalErrorCallback=_a;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 w(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 w(this,null,function*(){try{let e={iceServers:[{urls:oo}]};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 w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(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:mc.WTF,message:e.message})}onPeerConnectionStream(e){return w(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 w(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),fc)}normalizeOptions(e={}){let t={stunServerList:oo,maxRetryNumber:bc,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Mi=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new yc(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"),T(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"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return uo(e)}};this.subscription=new vc,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=re(e.container),this.liveStreamClient=new xr(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),ae(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:Na.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};lo(this.videoState.stateChangeStarted$.pipe(co(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(co(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})});let r=ne(this.video),a=(s,n)=>this.subscription.add(s.subscribe(n,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(be(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(se(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 uo(s.to)}},i)).add(lo(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Sc(["init"])).pipe(gc(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(K(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:Tc.INVARIANT}),this.video.srcObject=e,T(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:Na.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Na.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Di=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Oi,assertNonNullable as Ze,ErrorCategory as Dr,filter as Nc,isNonNullable as Bo,isNullable as Fc,map as Uc,merge as Hc,once as Gc,Subject as ve,Subscription as Vo,ValueSubject as C}from"@vkontakte/videoplayer-shared";import{assertNever as Rr,CurrentClientBrowser as xc,CurrentClientDevice as Pc,getCurrentBrowser as po,isAndroid as kc}from"@vkontakte/videoplayer-shared";var Eo=kc(),Se=document.createElement("video"),Ac='video/mp4; codecs="avc1.42000a,mp4a.40.2"',wc='video/mp4; codecs="hev1.1.6.L93.B0"',xo='video/webm; codecs="vp09.00.10.08"',Po='video/webm; codecs="av01.0.00M.08"',$c='audio/mp4; codecs="mp4a.40.2"',Lc='audio/webm; codecs="opus"',ho,mo,gt={mms:lr(),mse:Cn(),hls:!!((ho=Se.canPlayType)!=null&&ho.call(Se,"application/x-mpegurl")||(mo=Se.canPlayType)!=null&&mo.call(Se,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},fo,bo,ge={mp4:!!((fo=Se.canPlayType)!=null&&fo.call(Se,"video/mp4")),webm:!!((bo=Se.canPlayType)!=null&&bo.call(Se,"video/webm")),cmaf:!0},Pr,go,kr,So,Ar,vo,wr,yo,$r,To,Lr,Io,Le={h264:!!((go=(Pr=Ve())==null?void 0:Pr.isTypeSupported)!=null&&go.call(Pr,Ac)),h265:!!((So=(kr=Ve())==null?void 0:kr.isTypeSupported)!=null&&So.call(kr,wc)),vp9:!!((vo=(Ar=Ve())==null?void 0:Ar.isTypeSupported)!=null&&vo.call(Ar,xo)),av1:!!((yo=(wr=Ve())==null?void 0:wr.isTypeSupported)!=null&&yo.call(wr,Po)),aac:!!((To=($r=Ve())==null?void 0:$r.isTypeSupported)!=null&&To.call($r,$c)),opus:!!((Io=(Lr=Ve())==null?void 0:Lr.isTypeSupported)!=null&&Io.call(Lr,Lc))},Ci=(Le.h264||Le.h265)&&Le.aac,St,Rc=()=>w(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(V(k({},o),{video:V(k({},o.video),{contentType:Po})})),window.navigator.mediaCapabilities.decodingInfo(V(k({},o),{video:V(k({},o.video),{contentType:xo})}))]);St={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Rc()}catch(o){console.error(o)}var Ct=gt.hls&&ge.mp4,ko=()=>Object.keys(Le).filter(o=>Le[o]),Ao=(o,e=!1,t=!1)=>{let i=gt.mse||gt.mms&&t;return o.filter(r=>{switch(r){case"DASH_SEP":return i&&ge.mp4&&Ci;case"DASH_WEBM":return i&&ge.webm&&Le.vp9&&Le.opus;case"DASH_WEBM_AV1":return i&&ge.webm&&Le.av1&&Le.opus;case"DASH_LIVE":return gt.mse&&ge.mp4&&Ci;case"DASH_LIVE_CMAF":return i&&ge.mp4&&Ci&&ge.cmaf;case"DASH_ONDEMAND":return i&&ge.mp4&&Ci;case"HLS":case"HLS_ONDEMAND":return Ct||e&&gt.mse&&ge.mp4&&Ci;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Ct;case"MPEG":return ge.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return gt.webrtc&&gt.ws&&Le.h264&&(ge.mp4||ge.webm);default:return Rr(r)}})},Xe=o=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(o){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return St?St[t].smooth?[t,e]:St[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return St?St[t].powerEfficient?[t,e]:St[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Rr(o)}return[e,t]},wo=({webmCodec:o,androidPreferredFormat:e})=>{if(Eo)switch(e){case"mpeg":return["MPEG",...Xe(o),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...Xe(o),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...Xe(o),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...Xe(o),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Xe(o),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Xe(o),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:Rr(e)}return Ct?[...Xe(o),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...Xe(o),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},$o=({androidPreferredFormat:o,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],n,u=po().device===Pc.Mac&&po().browser===xc.Safari;if(Eo)switch(o){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=a;break}case"hls":case"mpeg":{n=s;break}default:Rr(o)}else Ct&&!u?n=s:u?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=a;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},Fa=o=>o?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as Mc,map as Lo,Subscription as Dc,Subject as Cc}from"@vkontakte/videoplayer-shared";var Ro=o=>new Mc(e=>{let t=new Dc,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Lo(({from:d,to:c})=>`${d}-${c}`)),r=o.desiredPlaybackState$.stateChangeEnded$,a=o.providerChanged$.pipe(Lo(({type:d})=>d!==void 0)),s=new Cc,n=0,u="unknown";return t.add(i.subscribe(d=>{n&&window.clearTimeout(n),u=d,n=window.setTimeout(()=>s.next(d),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(n),u="unknown",n=0})),t.add(a.subscribe(d=>{n&&(window.clearTimeout(n),n=0,d&&(n=window.setTimeout(()=>s.next(u),o.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as Mo,Subscription as Bc,combine as Vc,filter as Do,once as Co}from"@vkontakte/videoplayer-shared";var Bi=null,Mr=null;function Ua(){return Bi||(Bi=new(window.AudioContext||window.webkitAudioContext)),Mr||(Mr=new GainNode(Bi,{gain:1}),Mr.connect(Bi.destination)),{audioCtx:Bi,gainNode:Mr}}import{getCurrentBrowser as Oc,CurrentClientBrowser as _c}from"@vkontakte/videoplayer-shared";var Bt=class Bt{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Bc;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(Do(s=>!!s.type),Co()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){let{browser:t}=Oc();t===_c.Safari&&e!=="MPEG"||this.subscriptions.add(Vc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Do(({playbackState:i,video:r,volume:{muted:a,volume:s}})=>i==="playing"&&!!r&&!a&&!!s),Co()).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}=Ua(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{var s;if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Bt.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(n){this.volumeMultiplierError$.next({id:Bt.errorId,category:Mo.VIDEO_PIPELINE,message:(s=n==null?void 0:n.message)!=null?s:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(s=>{var n;this.volumeMultiplierError$.next({id:Bt.errorId,category:Mo.VIDEO_PIPELINE,message:(n=s==null?void 0:s.message)!=null?n:"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=Ua();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Bt.errorId="VolumeMultiplierManager";var Vi=Bt;var jc={chunkDuration:5e3,maxParallelRequests:5},_i=class{constructor(e){this.current$=new C({type:void 0});this.providerError$=new ve;this.noAvailableProvidersError$=new ve;this.volumeMultiplierError$=new ve;this.providerOutput={position$:new C(0),duration$:new C(1/0),volume$:new C({muted:!1,volume:1}),currentVideoTrack$:new C(void 0),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0),availableVideoTracks$:new C([]),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),autoVideoTrackLimitingAvailable$:new C(!1),autoVideoTrackLimits$:new C(void 0),currentBuffer$:new C(void 0),isBuffering$:new C(!0),error$:new ve,warning$:new ve,willSeekEvent$:new ve,seekedEvent$:new ve,loopedEvent$:new ve,endedEvent$:new ve,firstBytesEvent$:new ve,firstFrameEvent$:new ve,canplay$:new ve,isLive$:new C(void 0),isLowLatency$:new C(!1),canChangePlaybackSpeed$:new C(!0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),inPiP$:new C(!1),inFullscreen$:new C(!1),element$:new C(void 0),elementVisible$:new C(!0),availableSources$:new C(void 0),is3DVideo$:new C(!1),playbackState$:new C("")};this.subscription=new Vo;var n;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Ao([...$o(this.params.tuning),...wo(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>Bo(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 Di(a);let s=[...Fa(!0),...Fa(!1)];this.chromecastFormatsIterator=new Di(s.filter(u=>Bo(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Vi(this.providerOutput,this.current$,this.volumeMultiplierError$,(n=this.params.volumeMultiplier)!=null?n: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(Fc(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Dr.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 Oi(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":{let n=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ze(n),new Pi(V(k({},s),{source:n,sourceHls:u}))}case"DASH_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return Ze(n),new ki(V(k({},s),{source:n}))}case"HLS":case"HLS_ONDEMAND":{let n=this.applyFailoverHost(t[e]);return Ze(n),Ct||!this.params.tuning.useHlsJs?new Li(V(k({},s),{source:n})):new wi(V(k({},s),{source:n}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return Ze(n),new $i(V(k({},s),{source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let n=this.applyFailoverHost(t[e]);return Ze(n),new Ri(V(k({},s),{source:n}))}case"DASH_LIVE":{let n=this.applyFailoverHost(t[e]);return Ze(n),new an(V(k({},s),{source:n,config:V(k({},jc),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let n=this.applyFailoverHost(t[e]);return Ze(n),new Mi({container:i,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return Oi(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ze(n),new Ft({connection:n,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 Oi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Oi(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 Oi(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 V(k({},e),{url:i(e.url)})}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new Vo,t=!1,i=0;return e.add(Hc(this.providerOutput.error$,Ro({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Uc(r=>({id:`ProviderHangup:${r}`,category:Dr.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(Nc(({to:a})=>a==="playing"),Gc()).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===Dr.NETWORK,n=r.category===Dr.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!n;u&&!n&&(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}};import{fromEvent as Cr,once as Qc,combine as Wc,Subscription as Oo,ValueSubject as Ha,map as Yc,filter as qc,isNonNullable as Br,now as le,safeStorage as Ga}from"@vkontakte/videoplayer-shared";var zc=5e3,_o="one_video_throughput",No="one_video_rtt",Oe=window.navigator.connection,Fo=()=>{let o=Oe==null?void 0:Oe.downlink;if(Br(o)&&o!==10)return o*1e3},Uo=()=>{let o=Oe==null?void 0:Oe.rtt;if(Br(o)&&o!==3e3)return o},Ho=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},ja=class o{constructor(e){this.subscription=new Oo;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=o.load(_o)||(e.useBrowserEstimation?Fo():void 0)||zc,i=(a=(r=o.load(No))!=null?r:e.useBrowserEstimation?Uo():void 0)!=null?a:0;if(this.throughput$=new Ha(t),this.rtt$=new Ha(i),this.rttAdjustedThroughput$=new Ha(Ho(t,i,e.rttPenaltyRequestSize)),this.throughput=mt.getSmoothedValue(t,-1,e),this.rtt=mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let s=()=>{let u=Fo();u&&this.throughput.next(u);let d=Uo();Br(d)&&this.rtt.next(d)};Oe&&"onchange"in Oe&&this.subscription.add(Cr(Oe,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{Ga.set(_o,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{Ga.set(No,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Wc({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Yc(({throughput:s,rtt:n})=>Ho(s,n,e.rttPenaltyRequestSize)),qc(s=>{let n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=le(),r=new Oo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Cr(e,"progress").pipe(Qc()).subscribe(a=>{t=a.loaded,i=le()}));break;case 1:case 0:r.add(Cr(e,"loadstart").subscribe(()=>{t=0,i=le()}));break}r.add(Cr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,n=le(),u=s-t,d=n-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=le(),s=0,n=le(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=p=>w(this,[p],function*({done:c,value:l}){if(c)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let h=le();if(h-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=n-a;f&&this.addRawSpeed(s,f,1,t),s=l.byteLength,a=le()}else s+=l.byteLength;n=le()}else r+=l.byteLength,s+=l.byteLength,s>=this.tuningConfig.streamMinSampleSize&&le()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,le()-n,this.concurrentDownloads.size),s=0,n=le());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(o.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=Ga.get(e);if(Br(t))return(i=parseInt(t,10))!=null?i:void 0}},Go=ja;import{fillWithDefault as Kc,VideoQuality as jo}from"@vkontakte/videoplayer-shared";var Qo={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:jo.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:jo.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:200,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Wo=o=>{var e;return V(k({},Kc(o,Qo)),{configName:[...(e=o.configName)!=null?e:[],...Qo.configName]})};import{assertNonNullable as Vr,combine as Or,ErrorCategory as _r,filter as Ni,filterChanged as ye,fromEvent as Wa,isNonNullable as rp,isNullable as ap,Logger as sp,map as D,mapTo as Ko,merge as et,now as Nr,once as _e,Subject as G,Subscription as Jo,tap as Xo,ValueSubject as E,isHigher as np,isInvariantQuality as Zo}from"@vkontakte/videoplayer-shared";import{merge as Jc,map as Xc,filter as Yo,isNonNullable as Zc}from"@vkontakte/videoplayer-shared";var Qa=({seekState:o,position$:e})=>Jc(o.stateChangeEnded$.pipe(Xc(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),Yo(Zc)),e.pipe(Yo(()=>o.getState().state==="none")));import{assertNonNullable as ep}from"@vkontakte/videoplayer-shared";var qo=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return ep(e,`Wrong container or containerId {${o.container}}`),e};import{filter as tp,once as ip}from"@vkontakte/videoplayer-shared";var zo=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(tp(r=>r.length>0),ip()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(o)};var Fr=class{constructor(e={configName:[]}){this.subscription=new Jo;this.logger=new sp;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableQualities$:new E([]),availableQualitiesFps$:new E({}),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,firstBytes$:new G,firstFrame$:new G,canplay$:new G,log$:new G};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:js};if(this.initLogs(),this.tuning=Wo(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ki({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Go(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(n){let u=s.map(l=>JSON.stringify(l,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:_r.WTF,message:c,thrown:n}),n}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=qo(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new _i({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&&!zt()?Wa(document,"visibilitychange").pipe(_e()).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}setQuality(e){Vr(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(Ni(i=>i.length>0),_e()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;Vr(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=>k({type:"external"},t))),this}selectTextTrack(e){var t;return zo(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(ap(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return rp(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(et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Ni(({from:e})=>e==="stopped"),_e()).subscribe(()=>{this.initedAt=Nr(),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(V(k({},s),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:_r.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(D(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(s=>s.destination),ye()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(D(s=>s.map(({quality:n})=>n).sort((n,u)=>Zo(n)?1:Zo(u)?-1:np(u,n)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let n={};for(let u of s)u.fps&&(n[u.quality]=u.fps);this.info.availableQualitiesFps$.next(n)})).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(ye()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ye()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ye()).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(D(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(Or({hasLiveOffsetByPaused:et(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(s=>s.to),ye(),D(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:n})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(n));return}this.hasLiveOffsetByPaused.next(!1)})).add(Or({atLiveEdge:Or({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Qa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:s,position:n,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(n)<d/1e3}),ye(),Xo(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:s,hasPausedTimeoutCase:n})=>s&&!n)).subscribe(this.info.atLiveEdge$)).add(Or({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:s,position:n,duration:u})=>s&&(Math.abs(u)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),ye(),Xo(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(s=>s.muted),ye()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(s=>s.volume),ye()).subscribe(this.info.volume$)).add(Qa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(et(e.providerOutput.endedEvent$.pipe(Ko(!0)),e.providerOutput.seekedEvent$.pipe(Ko(!1))).pipe(ye()).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(D(s=>({id:s?`No${s}`:"NoProviders",category:_r.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(_e(),D(s=>s!=null?s:Nr()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(_e(),D(()=>Nr()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(_e(),D(()=>Nr()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Ni(({to:s})=>s==="playing"),_e()).subscribe(()=>i.next(!1)));let r=0,a=et(e.providerOutput.isBuffering$,t,i).pipe(D(()=>{let s=e.providerOutput.isBuffering$.getValue(),n=t.getValue()||i.getValue();return s&&!n}),ye());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(et(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 n=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:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(et(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),l;c==="CONNECTED"?l="second_screen":u?d?s?l="pip":n?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(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 Jo;this.subscription.add(t),this.subscription.add(e.current$.pipe(ye((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Ni(i=>i.length>0),_e()).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=ze(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(et(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(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;Vr(this.providerContainer),Vr(e),Gs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Hs(i)),this.providerContainer.current$.subscribe(({type:i})=>jt("provider",i)),e.duration$.subscribe(i=>jt("duration",i)),e.availableVideoTracks$.pipe(Ni(i=>!!i.length),_e()).subscribe(i=>jt("tracks",i)),this.events.fatalError$.subscribe(new ee("fatalError")),this.events.managedError$.subscribe(new ee("managedError")),e.position$.subscribe(new ee("position")),e.currentVideoTrack$.pipe(D(i=>i==null?void 0:i.quality)).subscribe(new ee("quality")),this.info.currentBuffer$.subscribe(new ee("buffer")),e.isBuffering$.subscribe(new ee("isBuffering"))].forEach(i=>this.subscription.add(i)),jt("codecs",ko())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>w(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:_r.DOM,message:String(r)})})});this.subscription.add(et(Wa(document,"visibilitychange"),Wa(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}};import{Subscription as yP,Observable as TP,Subject as IP,ValueSubject as EP,VideoQuality as xP}from"@vkontakte/videoplayer-shared";var PP=`@vkontakte/videoplayer-core@${hs}`;export{qi as ChromecastState,Jr as HttpConnectionType,TP as Observable,ie as PlaybackState,Fr as Player,PP as SDK_VERSION,IP as Subject,yP as Subscription,Xr as Surface,hs as VERSION,EP as ValueSubject,Ge as VideoFormat,xP as VideoQuality};
91
+ `;var As=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 xs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ps(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(ES,this.gl.VERTEX_SHADER),r=this.createShader(xS,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 Xt=class{constructor(e){this.subscription=new eR;this.videoState=new C("stopped");this.elementSize$=new tR(void 0);this.textTracksManager=new Ae;this.droppedFramesManager=new ss;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ts;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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(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"&&E(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"&&E(this.params.desiredState.playbackState,"paused");return;default:return Gk(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new As(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=le(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Es({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=pe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Du.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(PS(l=>!!l.length),wS()).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(PS(zk),wS()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ye(this.video,t.isLooped,a)),this.subscription.add(de(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Pe(this.video,t.playbackRate,r.playbackRateState$,a)),s(Zk(this.video),this.elementSize$),s(ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(Yk(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push({id:h.id,language:h.language,label:h.label});let m=[];for(let b of h.representations){let S=uS(b);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push({id:p.id,language:p.language,hdr:p.hdr,label:p.label});let h=[];for(let m of p.representations){let b=oS(m);b&&(h.push(b),this.videoTracksMap.set(b,{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=lS(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:Du.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(ws(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$,Qk(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();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):(this.player.switchRepresentation("video",p.id).catch(n),h&&this.player.switchRepresentation("audio",h.id).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(Ou()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:d}])=>d.id===l);if(c){let[d,{stream:p}]=c;e.currentVideoTrack$.next(d),e.currentVideoStream$.next(p)}else e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0)},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ou()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:d}])=>d.id===l);if(c){let[,{stream:d}]=c;e.currentAudioStream$.next(d)}else e.currentAudioStream$.next(void 0)},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(Jk(({to:l})=>l==="ready"),Ou());this.subscription.add(ws(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(ws(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ws(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Xk(["init"])).pipe(Wk(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){var L,M,U,H,R,A,j,Q,w,x,_,G,z;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=(L=e.videoTrack.getState())==null?void 0:L.id,n=[...this.videoTracksMap.keys()].find(({id:D})=>D===a),o=t.currentVideoTrack$.getValue(),u=((H=(U=e.videoStream.getState())!=null?U:n&&((M=this.videoTracksMap.get(n))==null?void 0:M.stream))!=null?H:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:D})=>D===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=gt(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=(R=e.audioStream.getState())!=null?R:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=[...this.audioStreamsMap.keys()].find(({id:D})=>D===(m==null?void 0:m.id)),S=0;if(b){if(n&&!r){let D=Ss(n,c,(A=this.audioStreamsMap.get(b))!=null?A:[]);S=Math.max(S,(j=D==null?void 0:D.bitrate)!=null?j:-1/0)}if(o){let D=Ss(o,c,(Q=this.audioStreamsMap.get(b))!=null?Q:[]);S=Math.max(S,(w=D==null?void 0:D.bitrate)!=null?w:-1/0)}}let v=St(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:I}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(v=(x=c.filter(D=>!Kk(D.quality)).sort((D,Le)=>{var Et,ot;return((Et=Le.bitrate)!=null?Et:0)-((ot=D.bitrate)!=null?ot:0)}).filter(D=>AS(D.quality,v.quality)&&AS(D.quality,I))[0])!=null?x:v);let T=r?v!=null?v:n:n!=null?n:v,g=b&&Ss(T,c,(_=this.audioStreamsMap.get(b))!=null?_:[]),y=(G=this.videoTracksMap.get(T))==null?void 0:G.representation,B=g&&((z=this.audioTracksMap.get(g))==null?void 0:z.representation);if(y&&B)return[y,B];if(y&&!B&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){he(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Du.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),ce(this.video)}};var Wi=class extends Xt{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)}};import{combine as kS,interval as rR,map as iR}from"@vkontakte/videoplayer-shared";var Qi=class extends Xt{constructor(e){super(e),this.liveOffset=new Xe}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(kS({interval:rR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let n=e.position$.getValue()+(a-1);e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(kS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(iR(({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 $S=He(Xa(),1);import{assertNever as zi,assertNonNullable as RS,debounce as aR,ErrorCategory as ks,filter as sR,isNonNullable as nR,isNullable as oR,map as Bu,merge as uR,Observable as lR,observableFrom as cR,Subscription as dR,videoSizeToQuality as pR}from"@vkontakte/videoplayer-shared";var Ne={};var Mr=(i,e)=>new lR(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ki=class{constructor(e){this.subscription=new dR;this.videoState=new C("initializing");this.textTracksManager=new Ae;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:zi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:zi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:zi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:zi(e)}break;default:zi(t)}};this.video=le(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(te(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),ce(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:ks.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,$S.default)(import("hls.js").then(a=>{e||(Ne.Hls=a.default,Ne.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){RS(Ne.Hls,"hls.js not loaded"),this.hls=new Ne.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){RS(Ne.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:ks.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=pe(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(Ye(this.video,e.isLooped,r)),this.subscription.add(de(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pe(this.video,e.playbackRate,a.playbackRateState$,r)),s(ke(this.video),t.elementVisible$),this.subscription.add(Mr(this.hls,Ne.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:ks.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"),E(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(Mr(this.hls,Ne.Events.MANIFEST_PARSED).pipe(Bu(({levels:l})=>l.reduce((c,d)=>{var I,T;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(T=mt((I=d.attrs.QUALITY)!=null?I:""))!=null?T:pR({width:h,height:m});if(!b)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(Mr(this.hls,Ne.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,b="internal";c.push({id:p,url:h,language:m,type:b})}e.internalTextTracks.startTransitionTo(c)}}),s(Mr(this.hls,Ne.Events.LEVEL_LOADING).pipe(Bu(({url:l})=>te(l))),t.hostname$),s(Mr(this.hls,Ne.Events.FRAG_CHANGED),l=>{var p,h,m,b;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)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(pt(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=Mr(this.hls,Ne.Events.LEVEL_SWITCHED).pipe(Bu(({level:l})=>n(this.hls.levels[l])));o.pipe(sR(nR)).subscribe(t.currentVideoTrack$,r),this.subscription.add(pt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(oR(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=uR(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cR(["init"])).pipe(aR(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 $(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield he(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ks.DOM,thrown:t})))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var LS="X-Playback-Duration",Vu=i=>$(void 0,null,function*(){var a;let e=yield et(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(LS)?parseInt(e.headers.get(LS),10):void 0});import{assertNever as gR,combine as vR,debounce as yR,ErrorCategory as $s,filter as TR,filterChanged as IR,isNonNullable as MS,isNullable as Ls,map as DS,merge as ER,observableFrom as xR,Subscription as PR,ValueSubject as Fu,VideoQuality as AR}from"@vkontakte/videoplayer-shared";var Nu=He(no(),1);import{videoSizeToQuality as hR,getExponentialDelay as fR}from"@vkontakte/videoplayer-shared";var mR=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=hR({width:t,height:r})}return e!=null?e:null},bR=(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,Nu.default)(l[1].split(",").map(I=>I.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=mR(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 b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[I,T]=d.RESOLUTION.split("x").map(g=>parseInt(g,10));I&&T&&(S={width:I,height:T})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:m,size:S,fps:b})}if(c){let d=(0,Nu.default)(c[1].split(",").map(b=>b.split("=")).map(([b,S])=>[b,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}},SR=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),_u=0,CS=(r,...a)=>$(void 0,[r,...a],function*(i,e=i,t){let n=yield(yield et(i)).text();_u+=1;try{let{qualityManifests:o,textTracks:u}=bR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(_u<=t.manifestRetryMaxCount)return yield SR(fR(_u-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),CS(i,e,t)}return{qualityManifests:[],textTracks:[]}}),Rs=CS;var Ji=class{constructor(e){this.subscription=new PR;this.videoState=new C("stopped");this.textTracksManager=new Ae;this.manifests$=new Fu([]);this.liveOffset=new Xe;this.manifestStartTime$=new Fu(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"),E(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"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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"&&E(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"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gR(t)}};var t;this.params=e,this.video=le(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:AR.INVARIANT,url:this.params.source.url},Rs(ae(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:$s.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:$s.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(te(this.params.source.url)),this.maxSeekBackTime$=new Fu((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:$s.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=pe(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(de(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,a.playbackRateState$,r)),s(ke(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(IR(),DS(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&&MS(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(te(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(vR({startTime:this.manifestStartTime$.pipe(TR(MS)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(DS(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=ER(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,xR(["init"])).pipe(yR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ce(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ls(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=ae(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Vu(n).then(l=>{var c;if(!Ls(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Ls(d)||!isFinite(d))try{et(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 b=new URL(h,n).toString();Vu(b).then(S=>{Ls(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){he(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$s.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()}};import{assertNever as wR,debounce as kR,ErrorCategory as qu,fromEvent as Uu,isNonNullable as RR,isNullable as $R,map as LR,merge as OS,observableFrom as BS,Subscription as CR,ValueSubject as MR,VideoQuality as DR,isIOS as OR}from"@vkontakte/videoplayer-shared";var Xi=class{constructor(e){this.subscription=new CR;this.videoState=new C("stopped");this.textTracksManager=new Ae;this.manifests$=new MR([]);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"),E(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"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return wR(t)}};this.params=e,this.video=le(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:DR.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(te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rs(ae(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:qu.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:qu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=pe(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$),this.subscription.add(Ye(this.video,t.isLooped,r)),this.subscription.add(de(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&RR(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(te(h.url));let m=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==b){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(LR(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)),!OR()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(OS(Uu(o,"addtrack"),Uu(o,"removetrack"),Uu(o,"change"),BS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=OS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,BS(["init"])).pipe(kR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ce(this.video)}prepare(){var s,n;let e=this.selectManifest();if($R(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(){he(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as BR,assertNonNullable as VS,debounce as VR,ErrorCategory as _S,isHigher as _R,isHigherOrEqual as NR,isInvariantQuality as NS,isLowerOrEqual as FR,isNonNullable as qR,merge as UR,observableFrom as HR,Subscription as jR}from"@vkontakte/videoplayer-shared";var Zi=class{constructor(e){this.subscription=new jR;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Ae;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"),E(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"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return BR(e)}};this.params=e,this.video=le(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:_S.WTF,message:"MpegProvider internal logic error",thrown:o})},a=pe(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$),this.subscription.add(Ye(this.video,t.isLooped,r)),this.subscription.add(de(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pe(this.video,t.playbackRate,a.playbackRateState$,r)),s(ke(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&qR(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=UR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,HR(["init"])).pipe(VR(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),ce(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;VS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];VS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ji(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(te(t))}playIfAllowed(){he(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_S.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=>!NS(d.track.quality)&&FR(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&&NR(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!NS(h.track.quality)&&_R(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=St(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})}};import{assertNever as qS,debounce as QR,merge as US,observableFrom as zR,Subscription as KR,map as HS,ValueSubject as JR,ErrorCategory as ju,VideoQuality as XR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as GR}from"@vkontakte/videoplayer-shared";var FS=["stun:videostun.mycdn.me:80"],YR=1e3,WR=3,Hu=()=>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=Hu;this.externalStopCallback=Hu;this.externalErrorCallback=Hu;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 $(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 $(this,null,function*(){try{let e={iceServers:[{urls:FS}]};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 $(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return $(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:GR.WTF,message:e.message})}onPeerConnectionStream(e){return $(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 $(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),YR)}normalizeOptions(e={}){let t={stunServerList:FS,maxRetryNumber:WR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ea=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new JR(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"),E(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"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return qS(e)}};this.subscription=new KR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=le(e.container),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),ce(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ju.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};US(this.videoState.stateChangeStarted$.pipe(HS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(HS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=pe(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(ke(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(de(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 qS(n.to)}},r)).add(US(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,zR(["init"])).pipe(QR(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(te(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:XR.INVARIANT}),this.video.srcObject=e,E(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:ju.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){he(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ju.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ta=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}};import{assertNever as ra,assertNonNullable as Tt,ErrorCategory as Ms,filter as r$,isNonNullable as YS,isNullable as i$,map as a$,merge as s$,once as n$,Subject as Fe,Subscription as WS,ValueSubject as O}from"@vkontakte/videoplayer-shared";import{Observable as ZR,map as jS,Subscription as e$,Subject as t$}from"@vkontakte/videoplayer-shared";var GS=i=>new ZR(e=>{let t=new e$,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(jS(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(jS(({type:l})=>l!==void 0)),n=new t$,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 o$={chunkDuration:5e3,maxParallelRequests:5},ia=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new Fe;this.noAvailableProvidersError$=new Fe;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new Fe,warning$:new Fe,willSeekEvent$:new Fe,seekedEvent$:new Fe,loopedEvent$:new Fe,endedEvent$:new Fe,firstBytesEvent$:new Fe,firstFrameEvent$:new Fe,canplay$:new Fe,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1)};this.subscription=new WS;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=pb([...fb(this.params.tuning),...hb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>YS(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new ta(s);let n=[...du(!0),...du(!1)];this.chromecastFormatsIterator=new ta(n.filter(o=>YS(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(i$(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Ms.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 ra(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 Tt(o),new Wi(N(k({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Qi(N(k({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Tt(o),xr||!this.params.tuning.useHlsJs?new Xi(N(k({},n),{source:o})):new Ki(N(k({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Ji(N(k({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Zi(N(k({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Wm(N(k({},n),{source:o,config:N(k({},o$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Tt(o),new ea({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 ra(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 Tt(o),new ai({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 ra(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ra(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 ra(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 N(k({},e),{url:r(e.url)})}return(0,QS.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new WS,t=!1,r=0;return e.add(s$(this.providerOutput.error$,GS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a$(a=>({id:`ProviderHangup:${a}`,category:Ms.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(r$(({to:s})=>s==="playing"),n$()).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===Ms.NETWORK,o=a.category===Ms.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}};import{fromEvent as Ds,once as u$,combine as l$,Subscription as zS,ValueSubject as Gu,map as c$,filter as d$,isNonNullable as Os,now as Ie,safeStorage as Yu}from"@vkontakte/videoplayer-shared";var p$=5e3,KS="one_video_throughput",JS="one_video_rtt",st=window.navigator.connection,XS=()=>{let i=st==null?void 0:st.downlink;if(Os(i)&&i!==10)return i*1e3},ZS=()=>{let i=st==null?void 0:st.rtt;if(Os(i)&&i!==3e3)return i},eg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Wu=class i{constructor(e){this.subscription=new zS;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(KS)||(e.useBrowserEstimation?XS():void 0)||p$,r=(s=(a=i.load(JS))!=null?a:e.useBrowserEstimation?ZS():void 0)!=null?s:0;if(this.throughput$=new Gu(t),this.rtt$=new Gu(r),this.rttAdjustedThroughput$=new Gu(eg(t,r,e.rttPenaltyRequestSize)),this.throughput=zt.getSmoothedValue(t,-1,e),this.rtt=zt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=XS();u&&this.throughput.next(u);let l=ZS();Os(l)&&this.rtt.next(l)};st&&"onchange"in st&&this.subscription.add(Ds(st,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Yu.set(KS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Yu.set(JS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(l$({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(c$(({throughput:n,rtt:o})=>eg(n,o,e.rttPenaltyRequestSize)),d$(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=Ie(),a=new zS;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Ds(e,"progress").pipe(u$()).subscribe(s=>{t=s.loaded,r=Ie()}));break;case 1:case 0:a.add(Ds(e,"loadstart").subscribe(()=>{t=0,r=Ie()}));break}a.add(Ds(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ie(),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=Ie(),n=0,o=Ie(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>$(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(a,Ie()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(Ie()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=Ie()}o=Ie()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ie()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ie()-o,this.concurrentDownloads.size),n=0,o=Ie());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=Yu.get(e);if(Os(t))return(r=parseInt(t,10))!=null?r:void 0}},tg=Wu;import{fillWithDefault as h$,VideoQuality as rg}from"@vkontakte/videoplayer-shared";var ig={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:rg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:rg.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:200,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:!0,preferHDR:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},ag=i=>{var e;return N(k({},h$(i,ig)),{configName:[...(e=i.configName)!=null?e:[],...ig.configName]})};import{assertNonNullable as Bs,combine as Vs,ErrorCategory as _s,filter as aa,filterChanged as $e,fromEvent as zu,isNonNullable as y$,isNullable as T$,Logger as I$,map as V,mapTo as ug,merge as It,now as Ns,once as nt,Subject as Y,Subscription as lg,tap as cg,ValueSubject as P,isHigher as E$,isInvariantQuality as dg}from"@vkontakte/videoplayer-shared";import{merge as f$,map as m$,filter as sg,isNonNullable as b$}from"@vkontakte/videoplayer-shared";var Qu=({seekState:i,position$:e})=>f$(i.stateChangeEnded$.pipe(m$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),sg(b$)),e.pipe(sg(()=>i.getState().state==="none")));import{assertNonNullable as S$}from"@vkontakte/videoplayer-shared";var ng=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return S$(e,`Wrong container or containerId {${i.container}}`),e};import{filter as g$,once as v$}from"@vkontakte/videoplayer-shared";var og=(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(g$(a=>a.length>0),v$()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var Fs=class{constructor(e={configName:[]}){this.subscription=new lg;this.logger=new I$;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,firstBytes$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Mm};if(this.initLogs(),this.tuning=ag(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new pa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new tg(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:_s.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=ng(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new ia({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}),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&&!fi()?zu(document,"visibilitychange").pipe(nt()).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){Bs(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(aa(r=>r.length>0),nt()).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;Bs(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=>k({type:"external"},t))),this}selectTextTrack(e){var t;return og(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(T$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return y$(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(It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(aa(({from:e})=>e==="stopped"),nt()).subscribe(()=>{this.initedAt=Ns(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(N(k({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_s.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(V(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(n=>n.destination),$e()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(V(n=>n.map(({quality:o})=>o).sort((o,u)=>dg(o)?1:dg(u)?-1:E$(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($e()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe($e()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe($e()).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(V(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(Vs({hasLiveOffsetByPaused:It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(n=>n.to),$e(),V(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(Vs({atLiveEdge:Vs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),$e(),cg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Vs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),$e(),cg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(n=>n.muted),$e()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(n=>n.volume),$e()).subscribe(this.info.volume$)).add(Qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(It(e.providerOutput.endedEvent$.pipe(ug(!0)),e.providerOutput.seekedEvent$.pipe(ug(!1))).pipe($e()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(V(n=>({id:n?`No${n}`:"NoProviders",category:_s.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(nt(),V(n=>n!=null?n:Ns()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(nt(),V(()=>Ns()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(nt(),V(()=>Ns()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(aa(({to:n})=>n==="playing"),nt()).subscribe(()=>r.next(!1)));let a=0,s=It(e.providerOutput.isBuffering$,t,r).pipe(V(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),$e());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(It(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(It(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(V(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 lg;this.subscription.add(t),this.subscription.add(e.current$.pipe($e((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(aa(r=>r.length>0),nt()).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=St(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(It(this.desiredState.videoTrack.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(V(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Bs(this.providerContainer),Bs(e),Cm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Lm(r)),this.providerContainer.current$.subscribe(({type:r})=>li("provider",r)),e.duration$.subscribe(r=>li("duration",r)),e.availableVideoTracks$.pipe(aa(r=>!!r.length),nt()).subscribe(r=>li("tracks",r)),this.events.fatalError$.subscribe(new se("fatalError")),this.events.managedError$.subscribe(new se("managedError")),e.position$.subscribe(new se("position")),e.currentVideoTrack$.pipe(V(r=>r==null?void 0:r.quality)).subscribe(new se("quality")),this.info.currentBuffer$.subscribe(new se("buffer")),e.isBuffering$.subscribe(new se("isBuffering"))].forEach(r=>this.subscription.add(r)),li("codecs",db())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>$(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:_s.DOM,message:String(a)})})});this.subscription.add(It(zu(document,"visibilitychange"),zu(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}};import{Subscription as uG,Observable as lG,Subject as cG,ValueSubject as dG,VideoQuality as pG}from"@vkontakte/videoplayer-shared";var hG=`@vkontakte/videoplayer-core@${Tl}`;export{ca as ChromecastState,tn as HttpConnectionType,lG as Observable,ve as PlaybackState,Fs as Player,hG as SDK_VERSION,cG as Subject,uG as Subscription,rn as Surface,Tl as VERSION,dG as ValueSubject,$t as VideoFormat,pG as VideoQuality};