@vkontakte/videoplayer-core 2.0.128-dev.699ea99e.0 → 2.0.128-dev.6c63bff4.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/evergreen.esm.js CHANGED
@@ -1,18 +1,18 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.128-dev.699ea99e.0
3
- * Tue, 04 Mar 2025 11:03:36 GMT
2
+ * @vkontakte/videoplayer-core v2.0.128-dev.6c63bff4.0
3
+ * Tue, 04 Mar 2025 10:51:50 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-128/doc/
5
5
  */
6
- var hs="2.0.128-dev.699ea99e.0";var se=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(se||{}),Ze=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(Ze||{});var ur=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ur||{}),sa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(sa||{});var na=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(na||{}),lr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(lr||{});import{assertNever as vs,assertNonNullable as lu,isNonNullable as dr,ValueSubject as oa,Subject as du,Subscription as cu,merge as pu,observableFrom as hu,fromEvent as fs,map as bs,tap as gs,filterChanged as mu,isNullable as ua,ErrorCategory as Ss}from"@vkontakte/videoplayer-shared/evergreen";var ms=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var cr=class{constructor(e){this.connection$=new oa(void 0);this.castState$=new oa("NOT_AVAILABLE");this.errorEvent$=new du;this.realCastState$=new oa("NOT_AVAILABLE");this.subscription=new cu;this.isDestroyed=!1;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=dr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&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(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){dr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ua(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ua(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,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=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return vs(r.sessionState)}})).add(pu(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)),hu([i.getCastState()])).pipe(mu(),bs(fu),gs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=dr(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();lu(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(ua(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?dr(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Ss.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},fu=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return vs(n)}};import{assertNever as ys}from"@vkontakte/videoplayer-shared/evergreen";var X=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:ys(t)}return n},pr=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:ys(e)}};var v=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as bu,Subject as hr,merge as Ts}from"@vkontakte/videoplayer-shared/evergreen";var w=class{constructor(e){this.transitionStarted$=new hr;this.transitionEnded$=new hr;this.transitionUpdated$=new hr;this.forceChanged$=new hr;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||bu(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 gu}from"@vkontakte/videoplayer-shared/evergreen";var Is=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return gu(n)}};import{assertNever as Ct,assertNonNullable as ft,debounce as Es,ErrorCategory as xs,fromEvent as bt,isNonNullable as ks,map as Ps,merge as As,observableFrom as Su,Subject as vu,Subscription as la,timeout as yu,getHighestQuality as Tu}from"@vkontakte/videoplayer-shared/evergreen";var Iu=5,Eu=5,xu=500,Ls=7e3,zt=class{constructor(e){this.subscription=new la;this.loadMediaTimeoutSubscription=new la;this.videoState=new w("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?.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:Ct(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:Ct(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:Ct(e)}break}default:Ct(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 la;this.subscription.add(e),this.subscription.add(As(this.videoState.stateChangeStarted$.pipe(Ps(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ps(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 vu;e.add(r.pipe(Es(xu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>Iu)&&r.next(o),a=o})),e.add(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Eu&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),v(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:Ct(s)}}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(bt(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$,Su(["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"),v(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),v(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&v(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];ft(l);let c=Tu(Object.keys(l));ft(c);let d=l[c];ft(d),i=d,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];ft(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];ft(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];ft(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];ft(l),i=X(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:xs.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ct(e)}let s=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return ks(o)&&(s.metadata.title=o),ks(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(yu(Ls).subscribe(()=>a(`timeout(${Ls})`)))});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)}`})}};import{clearVideoElement as $s}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as ku}from"@vkontakte/videoplayer-shared/evergreen";var ws=n=>{try{n.pause(),n.playbackRate=0,ku(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Pu,Subscription as Au}from"@vkontakte/videoplayer-shared/evergreen";var da=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)}},ca=window.WeakMap?new WeakMap:new da,pa=window.WeakMap?new WeakMap:new Map,Lu=(n,e=20)=>{let t=0;return Pu(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ne=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?$s(i):(i=document.createElement("video"),n.appendChild(i)),ca.set(i,r);let a=new Au;return a.add(Lu(i,e)),pa.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},oe=n=>{pa.get(n)?.unsubscribe(),pa.delete(n);let t=ca.get(n);ca.delete(n),t?$s(n):ws(n)};import{assertNonNullable as Yt,isNonNullable as Ve,isNullable as Mu,fromEvent as Vt,merge as Ms,observableFrom as Rs,filterChanged as Ds,map as Kt,Subject as Cs,Subscription as Ru,ValueSubject as Du,ErrorCategory as Cu}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as ha,isNullable as wu,Subscription as $u}from"@vkontakte/videoplayer-shared/evergreen";var mr=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=wu(r),l=new $u;return r&&l.add(r.subscribe(c=>{let d=n.getState();i(c,d)&&n.setState(c)},a)),i(o,s)||(t(s),u&&n.setState(s)),l.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),u&&n.setState(c.to)},a)),l},Ce=(n,e,t)=>mr(e,()=>n.loop,i=>{ha(i)&&(n.loop=i)},{onError:t}),ue=(n,e,t,i)=>mr(e,()=>({muted:n.muted,volume:n.volume}),r=>{ha(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),ye=(n,e,t,i)=>mr(e,()=>n.playbackRate,r=>{ha(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),et=mr;var Vu=n=>["__",n.language,n.label].join("|"),Bu=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},ma=class n{constructor(e){this.available$=new Cs;this.current$=new Du(void 0);this.error$=new Cs;this.subscription=new Ru;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:Cu.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(et(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ve(a)&&this.setInternal(a)},{equal:(a,s)=>Ve(a)&&Ve(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Kt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(et(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ve(a)&&this.setExternal(a)},{equal:(a,s)=>Ve(a)&&Ve(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Kt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(et(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(et(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Yt(this.video);let{textTracks:e}=this.video;this.subscription.add(Vt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ms(Vt(e,"addtrack"),Vt(e,"removetrack"),Rs(["init"])).pipe(Kt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Ds((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(Ms(Vt(e,"change"),Rs(["init"])).pipe(Kt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Kt(i=>i&&this.htmlTextTrackToITextTrack(i).id),Ds()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Vt(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Vt(e,"removetrack").subscribe(i=>{i.track?.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;Ve(t.align)&&(r.align=t.align),Ve(t.position)&&(r.position=t.position),Ve(t.size)&&(r.size=t.size),Ve(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Yt(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Vu(e),a=this.externalTracks.has(r),s=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){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){Yt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Mu(e)||!Bu(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){Yt(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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){Yt(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)}},Te=ma;var Qe=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 Vs=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},fa=n=>{let e=Vs(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Bs=n=>{let e=Vs(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as Ie,map as tt,merge as Ns,filterChanged as Nu,isNonNullable as Fs,Subject as Fu,filter as _s,mapTo as Us,combine as _u,once as Uu,ErrorCategory as Hu,ValueSubject as Hs,clientChecker as Qu}from"@vkontakte/videoplayer-shared/evergreen";var Ou=3,Os=(n,e,t=Ou)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var le=n=>{let e=E=>Ie(n,E).pipe(Us(void 0)),i=Ns(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>Ie(n,E))).pipe(tt(E=>E.type==="ended"?n.readyState<2:n.readyState<3),Nu()),r=Ns(Ie(n,"progress"),Ie(n,"timeupdate")).pipe(tt(()=>Os(n.buffered,n.currentTime))),a=Qu.isSafari?_u({play:e("play").pipe(Uu()),playing:e("playing")}).pipe(Us(void 0)):e("playing"),s=Ie(n,"volumechange").pipe(tt(()=>({muted:n.muted,volume:n.volume}))),o=Ie(n,"ratechange").pipe(tt(()=>n.playbackRate)),u=Ie(n,"error").pipe(_s(()=>!!(n.error||n.played.length)),tt(()=>{let E=n.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:Hu.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=Ie(n,"timeupdate").pipe(tt(()=>n.currentTime)),c=new Fu,d=.3,p;l.subscribe(E=>{n.loop&&Fs(p)&&Fs(E)&&p>=n.duration-d&&E<=d&&c.next(p),p=E});let h=e("pause").pipe(_s(()=>!n.error&&p!==n.duration)),m=Ie(n,"enterpictureinpicture"),f=Ie(n,"leavepictureinpicture"),g=new Hs(Bs(n));m.subscribe(()=>g.next(!0)),f.subscribe(()=>g.next(!1));let y=new Hs(fa(n));return Ie(n,"fullscreenchange").pipe(tt(()=>fa(n))).subscribe(y),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ie(n,"durationchange").pipe(tt(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:g,inFullscreen$:y,enterPip$:m,leavePip$:f}};import{VideoQuality as it}from"@vkontakte/videoplayer-shared/evergreen";var rt=n=>{switch(n){case"mobile":return it.Q_144P;case"lowest":return it.Q_240P;case"low":return it.Q_360P;case"sd":case"medium":return it.Q_480P;case"hd":case"high":return it.Q_720P;case"fullhd":case"full":return it.Q_1080P;case"quadhd":case"quad":return it.Q_1440P;case"ultrahd":case"ultra":return it.Q_2160P}};import{isNonNullable as me,isNullable as zs,now as Js,isHigher as Ys,isHigherOrEqual as va,isInvariantQuality as Ks,isLowerOrEqual as ya,videoSizeToQuality as Gu,assertNotEmptyArray as Zs,assertNonNullable as Wu}from"@vkontakte/videoplayer-shared/evergreen";var ba=!1,je={},Qs=n=>{ba=n},js=()=>{je={}},qs=n=>{n(je)},Xt=(n,e)=>{ba&&(je.meta=je.meta??{},je.meta[n]=e)},te=class{constructor(e){this.name=e}next(e){if(!ba)return;je.series=je.series??{};let t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}};import{isHigher as ju,isHigherOrEqual as _h,isLower as Gs,isLowerOrEqual as Uh,isNonNullable as fr,isNullable as qu,videoHeightToQuality as br}from"@vkontakte/videoplayer-shared/evergreen";function ga({limits:n,highQualityLimit:e,trafficSavingLimit:t}){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function Sa({limits:n,highQualityLimit:e,trafficSavingLimit:t}){return!!n&&ga({limits:n,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Jt({limits:n,highestAvailableQuality:e,lowestAvailableQuality:t}){return qu(n)||fr(n.min)&&fr(n.max)&&Gs(n.max,n.min)||fr(n.min)&&e&&ju(n.min,e)||fr(n.max)&&t&&Gs(n.max,t)}function Ws({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return Jt({limits:{max:n?.max?br(n.max):void 0,min:n?.min?br(n.min):void 0},highestAvailableQuality:e?br(e):void 0,lowestAvailableQuality:t?br(t):void 0})}var zu=new te("best_bitrate"),en=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var Ta=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),Zt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Js()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},tn='Assertion "ABR Tracks is empty array" failed',gr=(n,e,t,i)=>{let r=[...e].sort(Ta(1)),a=[...t].sort(Ta(1)),s=a.filter(u=>me(u.bitrate)&&me(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=a.at(Math.round(a.length*r.indexOf(n)/(r.length+1)))??a.at(-1);return o&&s.includes(o)?o:s.length?s.at(-1):a.at(0)},Xs=n=>"quality"in n,rn=(n,e,t,i)=>{let r=me(i?.last?.bitrate)&&me(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Js()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let s=i.last;i?.recordSwitch(s);let o=Xs(s)?"video":"audio",u=Xs(s)?s.quality:s.bitrate;return e({message:`
6
+ var Ts="2.0.128-dev.6c63bff4.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ge||{}),et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(et||{});var dr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(dr||{}),la=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(la||{});var da=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(da||{}),cr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(cr||{});import{assertNever as As,assertNonNullable as fu,isNonNullable as pr,ValueSubject as ca,Subject as bu,Subscription as gu,merge as Su,observableFrom as vu,fromEvent as Es,map as xs,tap as ks,filterChanged as yu,isNullable as pa,ErrorCategory as Ps}from"@vkontakte/videoplayer-shared/evergreen";var Is=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var hr=class{constructor(e){this.connection$=new ca(void 0);this.castState$=new ca("NOT_AVAILABLE");this.errorEvent$=new bu;this.realCastState$=new ca("NOT_AVAILABLE");this.subscription=new gu;this.isDestroyed=!1;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=pr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Is("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ps.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){pr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();pa(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();pa(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Es(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return As(r.sessionState)}})).add(Su(Es(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ks(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),xs(r=>r.castState)),vu([i.getCastState()])).pipe(yu(),xs(Tu),ks(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=pr(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();fu(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(pa(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?pr(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Ps.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Tu=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return As(n)}};import{assertNever as $s}from"@vkontakte/videoplayer-shared/evergreen";var J=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:$s(t)}return n},mr=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:$s(e)}};var y=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as Iu,Subject as fr,merge as Ls}from"@vkontakte/videoplayer-shared/evergreen";var $=class{constructor(e){this.transitionStarted$=new fr;this.transitionEnded$=new fr;this.transitionUpdated$=new fr;this.forceChanged$=new fr;this.stateChangeStarted$=Ls(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ls(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||Iu(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 Eu}from"@vkontakte/videoplayer-shared/evergreen";var ws=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Eu(n)}};import{assertNever as Dt,assertNonNullable as bt,debounce as Ms,ErrorCategory as Rs,fromEvent as gt,isNonNullable as Ds,map as Cs,merge as Vs,observableFrom as xu,Subject as ku,Subscription as ha,timeout as Pu,getHighestQuality as Au}from"@vkontakte/videoplayer-shared/evergreen";var $u=5,Lu=5,wu=500,Bs=7e3,zt=class{constructor(e){this.subscription=new ha;this.loadMediaTimeoutSubscription=new ha;this.videoState=new $("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?.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:Dt(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:Dt(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:Dt(e)}break}default:Dt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ws(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 ha;this.subscription.add(e),this.subscription.add(Vs(this.videoState.stateChangeStarted$.pipe(Cs(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Cs(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 ku;e.add(r.pipe(Ms(wu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>$u)&&r.next(o),a=o})),e.add(gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Lu&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),y(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:Dt(s)}}),t(gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(gt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Vs(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xu(["init"])).pipe(Ms(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"),y(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),y(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&y(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];bt(l);let c=Au(Object.keys(l));bt(c);let d=l[c];bt(d),i=d,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];bt(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];bt(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];bt(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];bt(l),i=J(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Rs.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Dt(e)}let s=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Ds(o)&&(s.metadata.title=o),Ds(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(Pu(Bs).subscribe(()=>a(`timeout(${Bs})`)))});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:Rs.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Ns}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Mu}from"@vkontakte/videoplayer-shared/evergreen";var Os=n=>{try{n.pause(),n.playbackRate=0,Mu(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Ru,Subscription as Du}from"@vkontakte/videoplayer-shared/evergreen";var ma=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)}},fa=window.WeakMap?new WeakMap:new ma,ba=window.WeakMap?new WeakMap:new Map,Cu=(n,e=20)=>{let t=0;return Ru(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ue=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?Ns(i):(i=document.createElement("video"),n.appendChild(i)),fa.set(i,r);let a=new Du;return a.add(Cu(i,e)),ba.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},le=n=>{ba.get(n)?.unsubscribe(),ba.delete(n);let t=fa.get(n);fa.delete(n),t?Ns(n):Os(n)};import{assertNonNullable as Kt,isNonNullable as Oe,isNullable as Ou,fromEvent as Ct,merge as Fs,observableFrom as _s,filterChanged as Us,map as Xt,Subject as Hs,Subscription as Nu,ValueSubject as Fu,ErrorCategory as _u}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as ga,isNullable as Vu,Subscription as Bu}from"@vkontakte/videoplayer-shared/evergreen";var br=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=Vu(r),l=new Bu;return r&&l.add(r.subscribe(c=>{let d=n.getState();i(c,d)&&n.setState(c)},a)),i(o,s)||(t(s),u&&n.setState(s)),l.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),u&&n.setState(c.to)},a)),l},Be=(n,e,t)=>br(e,()=>n.loop,i=>{ga(i)&&(n.loop=i)},{onError:t}),de=(n,e,t,i)=>br(e,()=>({muted:n.muted,volume:n.volume}),r=>{ga(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),xe=(n,e,t,i)=>br(e,()=>n.playbackRate,r=>{ga(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),tt=br;var Uu=n=>["__",n.language,n.label].join("|"),Hu=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Sa=class n{constructor(e){this.available$=new Hs;this.current$=new Fu(void 0);this.error$=new Hs;this.subscription=new Nu;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:_u.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(tt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Oe(a)&&this.setInternal(a)},{equal:(a,s)=>Oe(a)&&Oe(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Xt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(tt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Oe(a)&&this.setExternal(a)},{equal:(a,s)=>Oe(a)&&Oe(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Xt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(tt(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(tt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Kt(this.video);let{textTracks:e}=this.video;this.subscription.add(Ct(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Fs(Ct(e,"addtrack"),Ct(e,"removetrack"),_s(["init"])).pipe(Xt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Us((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(Fs(Ct(e,"change"),_s(["init"])).pipe(Xt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Xt(i=>i&&this.htmlTextTrackToITextTrack(i).id),Us()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Ct(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Ct(e,"removetrack").subscribe(i=>{i.track?.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;Oe(t.align)&&(r.align=t.align),Oe(t.position)&&(r.position=t.position),Oe(t.size)&&(r.size=t.size),Oe(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Kt(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Uu(e),a=this.externalTracks.has(r),s=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){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){Kt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Ou(e)||!Hu(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){Kt(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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){Kt(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)}},ke=Sa;var St=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 Qs=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},va=n=>{let e=Qs(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},js=n=>{let e=Qs(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as Pe,map as it,merge as Ws,filterChanged as ju,isNonNullable as Gs,Subject as qu,filter as Ys,mapTo as zs,combine as Wu,once as Gu,ErrorCategory as Yu,ValueSubject as Ks,clientChecker as zu}from"@vkontakte/videoplayer-shared/evergreen";var Qu=3,qs=(n,e,t=Qu)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var ce=n=>{let e=v=>Pe(n,v).pipe(zs(void 0)),i=Ws(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>Pe(n,v))).pipe(it(v=>v.type==="ended"?n.readyState<2:n.readyState<3),ju()),r=Ws(Pe(n,"progress"),Pe(n,"timeupdate")).pipe(it(()=>qs(n.buffered,n.currentTime))),a=zu.isSafari?Wu({play:e("play").pipe(Gu()),playing:e("playing")}).pipe(zs(void 0)):e("playing"),s=Pe(n,"volumechange").pipe(it(()=>({muted:n.muted,volume:n.volume}))),o=Pe(n,"ratechange").pipe(it(()=>n.playbackRate)),u=Pe(n,"error").pipe(Ys(()=>!!(n.error||n.played.length)),it(()=>{let v=n.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:Yu.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=Pe(n,"timeupdate").pipe(it(()=>n.currentTime)),c=new qu,d=.3,p;l.subscribe(v=>{n.loop&&Gs(p)&&Gs(v)&&p>=n.duration-d&&v<=d&&c.next(p),p=v});let h=e("pause").pipe(Ys(()=>!n.error&&p!==n.duration)),m=Pe(n,"enterpictureinpicture"),f=Pe(n,"leavepictureinpicture"),g=new Ks(js(n));m.subscribe(()=>g.next(!0)),f.subscribe(()=>g.next(!1));let S=new Ks(va(n));return Pe(n,"fullscreenchange").pipe(it(()=>va(n))).subscribe(S),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Pe(n,"durationchange").pipe(it(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:m,leavePip$:f}};import{VideoQuality as rt}from"@vkontakte/videoplayer-shared/evergreen";var at=n=>{switch(n){case"mobile":return rt.Q_144P;case"lowest":return rt.Q_240P;case"low":return rt.Q_360P;case"sd":case"medium":return rt.Q_480P;case"hd":case"high":return rt.Q_720P;case"fullhd":case"full":return rt.Q_1080P;case"quadhd":case"quad":return rt.Q_1440P;case"ultrahd":case"ultra":return rt.Q_2160P}};import{isNonNullable as Se,isNullable as rn,now as on,isHigher as an,isHigherOrEqual as Ea,isInvariantQuality as sn,isLowerOrEqual as xa,videoSizeToQuality as Ju,assertNotEmptyArray as un,assertNonNullable as Zu}from"@vkontakte/videoplayer-shared/evergreen";var ya=!1,Qe={},Xs=n=>{ya=n},Js=()=>{Qe={}},Zs=n=>{n(Qe)},Jt=(n,e)=>{ya&&(Qe.meta=Qe.meta??{},Qe.meta[n]=e)},ie=class{constructor(e){this.name=e}next(e){if(!ya)return;Qe.series=Qe.series??{};let t=Qe.series[this.name]??[];t.push([Date.now(),e]),Qe.series[this.name]=t}};import{isHigher as Ku,isHigherOrEqual as jh,isLower as en,isLowerOrEqual as qh,isNonNullable as gr,isNullable as Xu,videoHeightToQuality as Sr}from"@vkontakte/videoplayer-shared/evergreen";function Ta({limits:n,highQualityLimit:e,trafficSavingLimit:t}){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function Ia({limits:n,highQualityLimit:e,trafficSavingLimit:t}){return!!n&&Ta({limits:n,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Zt({limits:n,highestAvailableQuality:e,lowestAvailableQuality:t}){return Xu(n)||gr(n.min)&&gr(n.max)&&en(n.max,n.min)||gr(n.min)&&e&&Ku(n.min,e)||gr(n.max)&&t&&en(n.max,t)}function tn({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return Zt({limits:{max:n?.max?Sr(n.max):void 0,min:n?.min?Sr(n.min):void 0},highestAvailableQuality:e?Sr(e):void 0,lowestAvailableQuality:t?Sr(t):void 0})}var el=new ie("best_bitrate"),ln=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var ka=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),ei=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=on()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},dn='Assertion "ABR Tracks is empty array" failed',vr=(n,e,t,i)=>{let r=[...e].sort(ka(1)),a=[...t].sort(ka(1)),s=a.filter(u=>Se(u.bitrate)&&Se(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=a.at(Math.round(a.length*r.indexOf(n)/(r.length+1)))??a.at(-1);return o&&s.includes(o)?o:s.length?s.at(-1):a.at(0)},nn=n=>"quality"in n,cn=(n,e,t,i)=>{let r=Se(i?.last?.bitrate)&&Se(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&on()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let s=i.last;i?.recordSwitch(s);let o=nn(s)?"video":"audio",u=nn(s)?s.quality:s.bitrate;return e({message:`
7
7
  [last ${o} selected] ${u}
8
- `}),s}return i?.recordSwitch(t),t},Yu=(n,e)=>Math.log(e)/Math.log(n),Ku=({tuning:n,container:e,limits:t})=>{let i=n.containerSizeFactor;if(n.usePixelRatio&&window.devicePixelRatio){let r=window.devicePixelRatio;if(n.pixelRatioMultiplier)i*=n.pixelRatioMultiplier*(r-1)+1;else{let a=n.pixelRatioLogBase,[s=0,o=0,u=0]=n.pixelRatioLogCoefficients,l=Yu(a,s*r+o)+u;Number.isFinite(l)&&(i*=l)}}return Sa({highQualityLimit:n.highQualityLimit,trafficSavingLimit:n.trafficSavingLimit,limits:t})&&(i*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*i,height:e.height*i}:void 0,containerSizeFactor:i}},at=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{Zs(n,tn);let{containerSizeFactor:f,containerSizeLimit:g}=Ku({container:e,tuning:i,limits:r}),y=i.considerPlaybackRate&&me(o)?o:1,R=n.filter(b=>!Ks(b.quality)).sort((b,x)=>Ys(b.quality,x.quality)?-1:1),E=R.at(-1)?.quality,L=R.at(0)?.quality,S=Jt({limits:r,lowestAvailableQuality:E,highestAvailableQuality:L}),T=y*en(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},N=R.filter(b=>{let x=!0;if(g)if(b.size)x=b.size.width<=g.width&&b.size.height<=g.height;else{let Se=g&&Gu(g);x=Se?ya(b.quality,Se):!0}if(!x)return A[b.quality]="FitsContainer",!1;let U=h||t,be=me(U)&&isFinite(U)&&me(b.bitrate)?U-a>=b.bitrate*T:!0,ge=Sa({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&r?.min===b.quality;if(!be&&!ge)return A[b.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&me(i.minBufferToSwitchUp)&&u&&!Ks(u.quality)&&(s??0)<i.minBufferToSwitchUp&&Ys(b.quality,u.quality))return A[b.quality]="Buffer",!1;if(!!d&&va(b.quality,d)&&!ge)return A[b.quality]="DroppedFramesLimit",!1;if(!!p&&va(b.quality,p)&&!ge)return A[b.quality]="StallsLimit",!1;let k=S||(zs(r?.max)||ya(b.quality,r.max))&&(zs(r?.min)||va(b.quality,r.min)),H=me(c)&&!c?ya(b.quality,i.backgroundVideoQualityLimit):!0;return!k||!H?(A[b.quality]="FitsQualityLimits",!1):!0})[0];N&&N.bitrate&&zu.next(N.bitrate);let _=N??R.at(-1)??n[0];return _.quality!==l?.last?.quality&&m({message:`
8
+ `}),s}return i?.recordSwitch(t),t},tl=(n,e)=>Math.log(e)/Math.log(n),il=({tuning:n,container:e,limits:t})=>{let i=n.containerSizeFactor;if(n.usePixelRatio&&window.devicePixelRatio){let r=window.devicePixelRatio;if(n.pixelRatioMultiplier)i*=n.pixelRatioMultiplier*(r-1)+1;else{let a=n.pixelRatioLogBase,[s=0,o=0,u=0]=n.pixelRatioLogCoefficients,l=tl(a,s*r+o)+u;Number.isFinite(l)&&(i*=l)}}return Ia({highQualityLimit:n.highQualityLimit,trafficSavingLimit:n.trafficSavingLimit,limits:t})&&(i*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*i,height:e.height*i}:void 0,containerSizeFactor:i}},st=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{un(n,dn);let{containerSizeFactor:f,containerSizeLimit:g}=il({container:e,tuning:i,limits:r}),S=i.considerPlaybackRate&&Se(o)?o:1,D=n.filter(b=>!sn(b.quality)).sort((b,E)=>an(b.quality,E.quality)?-1:1),v=D.at(-1)?.quality,A=D.at(0)?.quality,I=Zt({limits:r,lowestAvailableQuality:v,highestAvailableQuality:A}),M=S*ln(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),P={},w=D.filter(b=>{let E=!0;if(g)if(b.size)E=b.size.width<=g.width&&b.size.height<=g.height;else{let X=g&&Ju(g);E=X?xa(b.quality,X):!0}if(!E)return P[b.quality]="FitsContainer",!1;let _=h||t,ne=Se(_)&&isFinite(_)&&Se(b.bitrate)?_-a>=b.bitrate*M:!0,ye=Ia({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&r?.min===b.quality;if(!ne&&!ye)return P[b.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Se(i.minBufferToSwitchUp)&&u&&!sn(u.quality)&&(s??0)<i.minBufferToSwitchUp&&an(b.quality,u.quality))return P[b.quality]="Buffer",!1;if(!!d&&Ea(b.quality,d)&&!ye)return P[b.quality]="DroppedFramesLimit",!1;if(!!p&&Ea(b.quality,p)&&!ye)return P[b.quality]="StallsLimit",!1;let j=I||(rn(r?.max)||xa(b.quality,r.max))&&(rn(r?.min)||Ea(b.quality,r.min)),W=Se(c)&&!c?xa(b.quality,i.backgroundVideoQualityLimit):!0;return!j||!W?(P[b.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&el.next(w.bitrate);let x=w??D.at(-1)??n[0];return x.quality!==l?.last?.quality&&m({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
11
  ${n.map(b=>`{ id: ${b.id}, quality: ${b.quality}, bitrate: ${b.bitrate}, size: ${b.size?.width}:${b.size?.height} }`).join(`
12
12
  `)}
13
13
 
14
14
  [tuning]
15
- ${Object.entries(i??{}).map(([b,x])=>`${b}: ${x}`).join(`
15
+ ${Object.entries(i??{}).map(([b,E])=>`${b}: ${E}`).join(`
16
16
  `)}
17
17
 
18
18
  [limit params]
@@ -22,30 +22,30 @@ var hs="2.0.128-dev.699ea99e.0";var se=(r=>(r.STOPPED="stopped",r.READY="ready",
22
22
  stallsPredictedThroughput: ${h},
23
23
  reserve: ${a},
24
24
  playbackRate: ${o},
25
- playbackRateFactor: ${y},
25
+ playbackRateFactor: ${S},
26
26
  forwardBufferHealth: ${s},
27
- bitrateFactor: ${T},
27
+ bitrateFactor: ${M},
28
28
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
29
29
  droppedVideoMaxQualityLimit: ${d},
30
30
  stallsVideoMaxQualityLimit: ${p},
31
- limitsAreInvalid: ${S},
31
+ limitsAreInvalid: ${I},
32
32
  maxQualityLimit: ${r?.max},
33
33
  minQualityLimit: ${r?.min},
34
34
 
35
35
  [limited video tracks]
36
- ${Object.entries(A).map(([b,x])=>`${b}: ${x}`).join(`
36
+ ${Object.entries(P).map(([b,E])=>`${b}: ${E}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
- [best video track] ${N?.quality}
40
- [selected video track] ${_?.quality}
41
- `}),rn(i,m,_,l)},an=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:s,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Zs(t,tn);let c=r.considerPlaybackRate&&me(a)?a:1,d=[...t].sort(Ta(-1)),p=n.bitrate;Wu(p);let h=c*en(s??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=gr(n,e,t,r.minVideoAudioRatio),g=l||i;return me(g)&&isFinite(g)&&(m=d.find(y=>me(y.bitrate)&&me(f?.bitrate)?g-p>=y.bitrate*h&&y.bitrate>=f.bitrate:!1)),m||(m=f),m?.bitrate!==o?.last?.bitrate&&u({message:`
39
+ [best video track] ${w?.quality}
40
+ [selected video track] ${x?.quality}
41
+ `}),cn(i,m,x,l)},pn=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:s,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{un(t,dn);let c=r.considerPlaybackRate&&Se(a)?a:1,d=[...t].sort(ka(-1)),p=n.bitrate;Zu(p);let h=c*ln(s??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=vr(n,e,t,r.minVideoAudioRatio),g=l||i;return Se(g)&&isFinite(g)&&(m=d.find(S=>Se(S.bitrate)&&Se(f?.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=f.bitrate:!1)),m||(m=f),m?.bitrate!==o?.last?.bitrate&&u({message:`
42
42
  [AUDIO TRACKS ABR]
43
43
  [available audio tracks]
44
- ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
44
+ ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
45
45
  `)}
46
46
 
47
47
  [tuning]
48
- ${Object.entries(r??{}).map(([y,R])=>`${y}: ${R}`).join(`
48
+ ${Object.entries(r??{}).map(([S,D])=>`${S}: ${D}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
@@ -59,14 +59,14 @@ var hs="2.0.128-dev.699ea99e.0";var se=(r=>(r.STOPPED="stopped",r.READY="ready",
59
59
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
60
60
 
61
61
  [selected audio track] ${m?.id}
62
- `}),m&&rn(r,u,m,o)};var W=n=>new URL(n).hostname;import{assertNever as dn,assertNonNullable as cn,combine as gl,debounce as Sl,ErrorCategory as pn,filter as hn,filterChanged as vl,isNonNullable as Pa,map as Ir,merge as mn,observableFrom as yl,once as Tl,Subscription as Il,ValueSubject as Aa,videoQualityToHeight as fn,videoSizeToQuality as El}from"@vkontakte/videoplayer-shared/evergreen";var sn=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},de=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!sn(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return sn(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as vr,isNullable as Zu,assertNonNullable as ii}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as nn,assertNonNullable as Sr,now as Xu}from"@vkontakte/videoplayer-shared/evergreen";function z(){return Xu()}function Ia(n){return z()-n}function Ea(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let l=s.indexOf("?")>-1?"&":"?";return u&&(s+=l+"lowLat=1",l="&"),o&&(s+=l+"_rnd="+Math.floor(999999999*Math.random())),s}}}function on(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Bt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,f=2e3,g=()=>{if(u)return;Sr(c);let x=Ia(c),U;if(x<f){U=f-x,setTimeout(g,U);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,T()},y=x=>(a=x,b),R=x=>(d=x,b),E=()=>(h="json",b),L=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},S=x=>(p=x,b),T=()=>{c=z(),s=new r,s.open("get",n);let x=0,U,be=0,ge=()=>(Sr(c),Math.max(c,Math.max(U||0,be||0)));if(a&&s.addEventListener("progress",P=>{let M=z();a.updateChunk&&P.loaded>x&&(a.updateChunk(ge(),P.loaded-x),x=P.loaded,U=M)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>L())),s.addEventListener("load",()=>{if(u)return;Sr(s);let P=s.status;if(P>=200&&P<300){let{response:M,responseType:B}=s,k=M?.byteLength;if(typeof k=="number"&&a){let H=k-x;H&&a.updateChunk&&a.updateChunk(ge(),H)}B==="json"&&(!M||!Object.values(M).length)?L():(d&&d(),e(M))}else L()}),s.addEventListener("error",()=>{L()}),p){let P=()=>{Sr(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(be=z(),s.removeEventListener("readystatechange",P))};s.addEventListener("readystatechange",P)}return s.responseType=h,s.send(),b},b={withBitrateReporting:y,withParallel:S,withJSONResponse:E,withRetryCount:x=>(l=x,b),withRetryInterval:(x,U)=>(nn(x)&&(f=x),nn(U)&&(m=U),b),withTimeout:x=>(o=x,b),withFinally:R,send:T,abort:()=>{s&&(s.abort(),s=void 0),u=!0,d&&d()}};return b}var ei=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ti=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=z(),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=z()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Bt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=z()}_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=z();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as el}from"@vkontakte/videoplayer-shared/evergreen";var yr=1e4,xa=3;var tl=6e4,il=10,rl=1,al=500,ri=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.soundProhibitedEvent$=new el,this.chunkRateEstimator=new ei(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ea(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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=Ea(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Ws({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(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||vr(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=()=>{on(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 ti(xa,yr,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,l=null,c=!1,d=()=>{let L=a&&(!c||c===this.rep);return L||t("Not running!"),L},p=(L,S,T)=>{u&&u.abort(),u=Bt(this.urlResolver.resolve(L,!1),S,T,()=>this._retryCallback()).withTimeout(yr).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xa).withFinally(()=>{u=null}).send()},h=(L,S,T)=>{ii(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(L,!1),S,T,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=L=>{let S=i.playbackRate;i.playbackRate!==L&&(t(`Playback rate switch: ${S}=>${L}`),i.playbackRate=L)},f=L=>{this.lowLatency=L,t(`lowLatency changed to ${L}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let L=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let T=z()-1e4,A=0;for(let N=0;N<this.bufferStates.length;N++){let _=this.bufferStates[N];L=Math.min(L,_.buf),_.ts<T&&A++}this.bufferStates.splice(0,A),t(`update playback rate; minBuffer=${L} drop=${A} jitter=${this.sourceJitter}`);let j=L-rl;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?m(1.15):j>1?m(1.1):j>.3?m(1.05):m(1)}},y=L=>{let S,T=()=>S&&S.start?S.start.length:0,A=P=>S.start[P]/1e3,j=P=>S.dur[P]/1e3,N=P=>S.fragIndex+P,_=(P,M)=>({chunkIdx:N(P),startTS:A(P),dur:j(P),discontinuity:M}),b=()=>{let P=0;if(S&&S.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,B=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,k=M;this.sourceJitter>1&&(k+=this.sourceJitter-1);let H=S.dur.length-1;for(;H>=0&&(k-=S.dur[H],!(k<=0));--H);P=Math.min(H,S.dur.length-1-B),P=Math.max(P,0)}return _(P,!0)},x=P=>{let M=T();if(!(M<=0)){if(vr(P)){for(let B=0;B<M;B++)if(A(B)>P)return _(B)}return b()}},U=P=>{let M=T(),B=P?P.chunkIdx+1:0,k=B-S.fragIndex;if(!(M<=0)){if(!P||k<0||k-M>il)return t(`Resync: offset=${k} bChunks=${M} chunk=`+JSON.stringify(P)),b();if(!(k>=M))return _(B-S.fragIndex,!1)}},be=(P,M,B)=>{l&&l.abort(),l=Bt(this.urlResolver.resolve(P,!0,this.lowLatency),M,B,()=>this._retryCallback()).withTimeout(yr).withRetryCount(xa).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,M)=>{be(L,B=>{if(!d())return;S=B;let k=!!S.lowLatency;k!==this.lowLatency&&f(k);let H=0;for(let Se=0;Se<S.dur.length;++Se)H+=S.dur[Se];H>0&&(ii(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(H/S.dur.length)),r({name:"index",zeroTime:S.zeroTime,shiftDuration:S.shiftDuration}),this.sourceJitter=S.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,S.jitter/1e3)):1,P(x(M))},()=>this._handleNetworkError())},nextChunk:U}},R=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ii(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:L=>{let{videoElement:S,logger:T}=this.params,A=y(e.jidxUrl),j,N,_,b,x=0,U,be,ge,P=()=>{U&&(clearTimeout(U),U=void 0);let D=Math.max(al,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),K=x+D,Z=z(),G=Math.min(1e4,K-Z);x=Z;let Me=()=>{l||d()&&A.seek(()=>{d()&&(x=z(),M(),P())})};G>0?U=window.setTimeout(()=>{this.paused?P():Me()},G):Me()},M=()=>{let D;for(;D=A.nextChunk(b);)b=D,Lt(D);let K=A.nextChunk(_);if(K){if(_&&K.discontinuity){T("Detected discontinuity; restarting playback"),this.paused?P():(R(),this._initPlayerWith(e));return}Se(K)}else P()},B=(D,K)=>{if(!d()||!this.sourceBuffer)return;let Z,G,Me,xe=ke=>{window.setTimeout(()=>{d()&&B(D,K)},ke)};if(this.sourceBuffer.updating)T("Source buffer is updating; delaying appendBuffer"),xe(100);else{let ke=z(),Fe=S.currentTime;!this.paused&&S.buffered.length>1&&be===Fe&&ke-ge>500&&(T("Stall suspected; trying to fix"),this._fixupStall()),be!==Fe&&(be=Fe,ge=ke);let Ke=this._getBufferSizeSec();if(Ke>30)T(`Buffered ${Ke} seconds; delaying appendBuffer`),xe(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:ke,buf:Ke}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),K&&K()}catch(_e){if(_e.name==="QuotaExceededError")T("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(Z=this.sourceBuffer.buffered.start(0),G=Fe,G-Z>4&&this.sourceBuffer.remove(Z,G-3)),xe(1e3);else throw _e}}},k=()=>{N&&j&&(T([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(_)]),B(N,function(){N=null,M()}))},H=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),Se=D=>{d()&&h(H(D),(K,Z)=>{if(d()){if(Z/=1e3,N=K,_=D,s=D.startTS,Z){let G=Math.min(10,D.dur/Z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*G:G}k()}},()=>this._handleNetworkError())},Lt=D=>{d()&&(ii(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(H(D),!1)))},$e=D=>{d()&&(e.cachedHeader=D,B(D,()=>{j=!0,k()}))};a=!0,A.seek(D=>{if(d()){if(x=z(),!D){P();return}b=D,!Zu(L)||D.startTS>L?Se(D):(_=D,M())}},L),e.cachedHeader?$e(e.cachedHeader):p(e.headerUrl,$e,()=>this._handleNetworkError())},stop:R,getTimestampSec:()=>s},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),vr(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,ii(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return vr(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=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}`)},a={updateChunk:(p,h)=>{let m=z();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,o,u=!0,l=()=>{let d=a.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Ia(s)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=a.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=z();d<o&&(s=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Bt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(yr).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;de(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((u,l)=>{u.video&&r.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):(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))},tl))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as sl,filter as un,fromEvent as nl,interval as ol,isHigher as ul,isInvariantQuality as ll,isLower as dl,merge as cl,Subject as ln,Subscription as pl}from"@vkontakte/videoplayer-shared/evergreen";var ka=class{constructor(){this.onDroopedVideoFramesLimit$=new ln;this.subscription=new pl;this.playing=!1;this.tracks=[];this.forceChecker$=new ln;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!ll(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{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&&ul(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.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(nl(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=ol(this.droppedFramesChecker.checkTime).pipe(un(()=>this.playing),un(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(sl(this.droppedFramesChecker.checkTime)),i=cl(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){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>dl(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Tr=ka;import{map as hl,Observable as ml}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as fl}from"@vkontakte/videoplayer-shared/evergreen";var ai=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var bl=(n,e)=>new ml(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||ai()))},{...i,...e});r.observe(n);let a=fl(document,"visibilitychange").pipe(hl(s=>!document.hidden||ai())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),Ee=bl;var xl=["paused","playing","ready"],kl=["paused","playing","ready"],si=class{constructor(e){this.subscription=new Il;this.videoState=new w("stopped");this.representations$=new Aa([]);this.droppedFramesManager=new Tr;this.maxSeekBackTime$=new Aa(1/0);this.zeroTime$=new Aa(void 0);this.liveOffset=new Qe;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:pn.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=rt(r.name)??El(r.video),o=r.bitrate/1e3,u={...r.video};if(!s)continue;let l={id:a,quality:s,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Pa(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(kl.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&xl.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?.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 dn(e)}};this.textTracksManager=new Te(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:pn.WTF,message:"DashLiveProvider internal logic error",thrown:r})};mn(this.videoState.stateChangeStarted$.pipe(Ir(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ir(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),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(W(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=le(this.video);this.subscription.add(this.representations$.pipe(Ir(r=>r.map(({track:a})=>a)),hn(r=>!!r.length),Tl()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(vl(),Ir(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(gl({zeroTime:this.zeroTime$.pipe(hn(Pa)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ce(this.video,this.params.desiredState.isLooped,t)).add(ue(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ye(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).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(Ee(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&fn(r),min:a&&fn(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{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":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return dn(r.to)}},t)).add(mn(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,yl(["init"])).pipe(Sl(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),oe(this.video)}createLiveDashPlayer(){let e=new ri({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Pa(t)?t:at(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let l=e.find(({track:c})=>c.id===a)?.representation;cn(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;cn(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 bn=si;var Be=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Dd,assertNonNullable as Cd,debounce as Vd,ErrorCategory as co,filter as po,filterChanged as Qi,fromEvent as Bd,isNonNullable as ho,map as Xa,merge as _r,observableFrom as Ja,once as mo,Subscription as Od}from"@vkontakte/videoplayer-shared/evergreen";var qe=()=>window.ManagedMediaSource||window.MediaSource,Er=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),gn=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Sn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ar,clientChecker as kr}from"@vkontakte/videoplayer-shared/evergreen";var Pr=document.createElement("video"),Ll='video/mp4; codecs="avc1.42000a,mp4a.40.2"',wl='video/mp4; codecs="hev1.1.6.L93.B0"',vn='video/webm; codecs="vp09.00.10.08"',yn='video/webm; codecs="av01.0.00M.08"',$l='audio/mp4; codecs="mp4a.40.2"',Ml='audio/webm; codecs="opus"',ni={mms:Er(),mse:gn(),hls:!!(Pr.canPlayType?.("application/x-mpegurl")||Pr.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ce={mp4:!!Pr.canPlayType?.("video/mp4"),webm:!!Pr.canPlayType?.("video/webm"),cmaf:!0},pe={h264:!!qe()?.isTypeSupported?.(Ll),h265:!!qe()?.isTypeSupported?.(wl),vp9:!!qe()?.isTypeSupported?.(vn),av1:!!qe()?.isTypeSupported?.(yn),aac:!!qe()?.isTypeSupported?.($l),opus:!!qe()?.isTypeSupported?.(Ml)},Ot=(pe.h264||pe.h265)&&pe.aac,gt,Rl=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:yn}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:vn}})]);gt={DASH_WEBM_AV1:e,DASH_WEBM:t}};Rl().catch(n=>{console.error(n)});var Nt=ni.hls&&ce.mp4,Tn=()=>Object.keys(pe).filter(n=>pe[n]),In=(n,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let r=ni.mse&&(!i||!!window.MediaStreamTrack)||ni.mms&&t;return n.filter(a=>{switch(a){case"DASH_SEP":return r&&ce.mp4&&Ot;case"DASH_WEBM":return r&&ce.webm&&pe.vp9&&pe.opus;case"DASH_WEBM_AV1":return r&&ce.webm&&pe.av1&&pe.opus;case"DASH_STREAMS":return r&&(ce.mp4&&Ot||ce.webm&&(pe.vp9||pe.av1)&&(pe.opus||pe.aac));case"DASH_LIVE":return r&&ce.mp4&&Ot;case"DASH_LIVE_CMAF":return r&&ce.mp4&&Ot&&ce.cmaf;case"DASH_ONDEMAND":return r&&ce.mp4&&Ot;case"HLS":case"HLS_ONDEMAND":return Nt||e&&r&&ce.mp4&&Ot;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Nt;case"MPEG":return ce.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ni.webrtc&&ni.ws&&pe.h264&&(ce.mp4||ce.webm);default:return Ar(a)}})},xr=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return gt?gt[t].smooth?[t,e]:gt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return gt?gt[t].powerEfficient?[t,e]:gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ar(n)}return[e,t]},En=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...xr(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(kr.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...xr(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...xr(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...xr(n),...r,"HLS","HLS_ONDEMAND"];default:Ar(e)}return Nt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},xn=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=kr.isMac&&kr.isSafari;if(kr.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:Ar(n)}else Nt&&!u?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},La=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],kn=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)};import{ErrorCategory as oi}from"@vkontakte/videoplayer-shared/evergreen";var Pn=n=>{if(!n)return{id:"EmptyResponse",category:oi.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:oi.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:oi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:oi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:oi.PARSER,message:"Response is valid XML, but parser failed"}};var st=(n,e,t=0)=>{for(let i=0;i<n.length;i++)if(n.start(i)*1e3-t<=e&&n.end(i)*1e3+t>e)return!0;return!1};import{abortable as qa,assertNonNullable as Et,clientChecker as hd,combine as xt,ErrorCategory as Oe,filter as _i,filterChanged as Ga,flattenObject as Ui,fromEvent as kt,getTraceSubscriptionMethod as md,interval as Wa,isNonNullable as io,isNullable as ro,map as Ht,merge as Pt,now as fd,Subject as Cr,Subscription as ao,tap as bd,throttle as gd,ValueSubject as q}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Dl,ErrorCategory as An,clientChecker as wa,Subject as Ln}from"@vkontakte/videoplayer-shared/evergreen";var Cl=18,wn=!1;try{wn=wa.isSafari&&!!wa.macVersion&&wa.macVersion<=Cl}catch(n){console.error(n)}var $a=class{constructor(e){this.bufferFull$=new Ln;this.error$=new Ln;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:An.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};wn&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:An.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){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:Dl(t)}}},$n=$a;var Ma=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as ot,assertNonNullable as he,clientChecker as id,ErrorCategory as ze,fromEvent as _a,getExponentialDelay as Ua,isNonNullable as _t,isNullable as J,now as Lr,once as rd,Subject as ad,Subscription as sd,ValueSubject as yt}from"@vkontakte/videoplayer-shared/evergreen";var C=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)}get id(){return this.type}get size(){return this.size32}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 Ft=class extends C{};var ui=class extends C{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,s=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(s);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var li=class extends C{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var di=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Q=class extends C{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ci=class extends Q{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var pi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hi=class extends C{constructor(e,t){super(e,t),this.data=this.content}};var St=class extends Q{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,s=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:s,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var mi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var bi=class extends Q{constructor(e,t){switch(super(e,t),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 gi=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Si=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var vi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var yi=class extends Q{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ti=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ii=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ei=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var xi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ki=class extends Q{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Pi=class extends Q{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ai=class extends Q{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 Li=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wi=class extends Q{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var $i=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Bl={ftyp:li,moov:di,mvhd:ci,moof:pi,mdat:hi,sidx:St,trak:mi,mdia:vi,mfhd:Ei,tkhd:yi,traf:xi,tfhd:ki,tfdt:Pi,trun:Ai,minf:Ti,sv3d:fi,st3d:bi,prhd:gi,proj:Ii,equi:Si,uuid:ui,stbl:Li,stsd:wi,avc1:$i,unknown:Ft},Ge=class n{constructor(e={}){this.options={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{break}return t}createBox(e,t){let i=Bl[e];return i?new i(t,new n):new Ft(t,new n)}};var nt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Nl=new TextDecoder("ascii"),Fl=n=>Nl.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",_l=n=>{let e=new St(n,new Ge),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},Ul=(n,e)=>{let i=new Ge().parse(n),r=new nt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,d)},Hl=n=>{let t=new Ge().parse(n),i=new nt(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},Ql=n=>{let t=new Ge().parse(n);return new nt(t).find("sidx")?.timescale},jl=(n,e)=>{let i=new Ge().parse(n),a=new nt(i).findAll("traf"),s=a[a.length-1].children.find(d=>d.type==="tfhd"),o=a[a.length-1].children.find(d=>d.type==="tfdt"),u=a[a.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},ql=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Ge().parse(n),r=new nt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Mn={validateData:Fl,parseInit:ql,getIndexRange:()=>{},parseSegments:_l,parseFeedableSegmentChunk:Ul,getChunkEndTime:jl,getServerLatencyTimestamps:Hl,getTimescaleFromIndex:Ql};import{assertNonNullable as Da,isNonNullable as Vn,isNullable as Wl}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Gl}from"@vkontakte/videoplayer-shared/evergreen";var Rn={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"}},Dn=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Mi(n,t),r=i in Rn,a=r?Rn[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),l=s&255>>o,c=Mi(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Mi=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Le=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return Mi(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:Gl(e)}},vt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Dn(i);if(!e(r))return;r.type==="master"&&vt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Cn=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Dn(n);return vt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=Le(o,s):a===17026?t=Le(o,s):a===17029&&(i=Le(o,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],zl=[231,22612,22743,167,171,163,160,175],Yl=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,l,c=!1,d=0;return vt(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let g=Le(m,h);l=Mi(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=Le(m,h):p===17545?r=Le(m,h):p===21420&&l===475249515?u=Le(m,h):p===374648427?vt(m,({tag:g,type:y,value:R})=>g===30321?(c=Le(R,y)===1,!1):!0):a&&s&&Bn.includes(p)&&(o=!0),!o}),Da(e,"Failed to parse webm Segment start"),Da(t,"Failed to parse webm Segment end"),Da(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Kl=n=>{if(Wl(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Xl=(n,e)=>{let t=!1,i=!1,r=o=>Vn(o.time)&&Vn(o.position),a=[],s;return vt(n,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Le(l,u));break;case 183:break;case 241:s&&(s.position=Le(l,u));break;default:t&&Bn.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:l,position:c}=o,d=a[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}}})},Jl=n=>{let e=0,t=!1;try{vt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):zl.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},On={validateData:Cn,parseInit:Yl,getIndexRange:Kl,parseSegments:Xl,parseFeedableSegmentChunk:Jl};var Ri=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return On;case"mp4":return Mn}}throw new ReferenceError(`Unsupported mime type ${n}`)};var Ca=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as td,isNullable as jn}from"@vkontakte/videoplayer-shared/evergreen";var Nn=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Fn=n=>{try{let e=Zl(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),s={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(s).forEach(o=>{let u=s[o];(typeof u>"u"||u==="")&&delete s[o]}),s}return null}catch{return null}};function Zl(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
62
+ `}),m&&cn(r,u,m,o)};var Y=n=>new URL(n).hostname;import{assertNever as Sn,assertNonNullable as vn,combine as El,debounce as xl,ErrorCategory as yn,filter as Tn,filterChanged as kl,isNonNullable as wa,map as xr,merge as In,observableFrom as Pl,once as Al,Subscription as $l,ValueSubject as Ma,videoQualityToHeight as En,videoSizeToQuality as Ll}from"@vkontakte/videoplayer-shared/evergreen";var hn=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},pe=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!hn(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return hn(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Tr,isNullable as sl,assertNonNullable as ri}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as mn,assertNonNullable as yr,now as rl}from"@vkontakte/videoplayer-shared/evergreen";function z(){return rl()}function Pa(n){return z()-n}function Aa(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let l=s.indexOf("?")>-1?"&":"?";return u&&(s+=l+"lowLat=1",l="&"),o&&(s+=l+"_rnd="+Math.floor(999999999*Math.random())),s}}}function fn(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Vt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,f=2e3,g=()=>{if(u)return;yr(c);let E=Pa(c),_;if(E<f){_=f-E,setTimeout(g,_);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,M()},S=E=>(a=E,b),D=E=>(d=E,b),v=()=>(h="json",b),A=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},I=E=>(p=E,b),M=()=>{c=z(),s=new r,s.open("get",n);let E=0,_,ne=0,ye=()=>(yr(c),Math.max(c,Math.max(_||0,ne||0)));if(a&&s.addEventListener("progress",k=>{let B=z();a.updateChunk&&k.loaded>E&&(a.updateChunk(ye(),k.loaded-E),E=k.loaded,_=B)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>A())),s.addEventListener("load",()=>{if(u)return;yr(s);let k=s.status;if(k>=200&&k<300){let{response:B,responseType:H}=s,j=B?.byteLength;if(typeof j=="number"&&a){let W=j-E;W&&a.updateChunk&&a.updateChunk(ye(),W)}H==="json"&&(!B||!Object.values(B).length)?A():(d&&d(),e(B))}else A()}),s.addEventListener("error",()=>{A()}),p){let k=()=>{yr(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ne=z(),s.removeEventListener("readystatechange",k))};s.addEventListener("readystatechange",k)}return s.responseType=h,s.send(),b},b={withBitrateReporting:S,withParallel:I,withJSONResponse:v,withRetryCount:E=>(l=E,b),withRetryInterval:(E,_)=>(mn(E)&&(f=E),mn(_)&&(m=_),b),withTimeout:E=>(o=E,b),withFinally:D,send:M,abort:()=>{s&&(s.abort(),s=void 0),u=!0,d&&d()}};return b}var ti=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ii=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=z(),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=z()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Vt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=z()}_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=z();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as nl}from"@vkontakte/videoplayer-shared/evergreen";var Ir=1e4,$a=3;var ol=6e4,ul=10,ll=1,dl=500,ai=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.soundProhibitedEvent$=new nl,this.chunkRateEstimator=new ti(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Aa(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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=Aa(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!tn({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(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=()=>{fn(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ii($a,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,o=null,u=null,l=null,c=!1,d=()=>{let A=a&&(!c||c===this.rep);return A||t("Not running!"),A},p=(A,I,M)=>{u&&u.abort(),u=Vt(this.urlResolver.resolve(A,!1),I,M,()=>this._retryCallback()).withTimeout(Ir).withBitrateReporting(this.bitrateSwitcher).withRetryCount($a).withFinally(()=>{u=null}).send()},h=(A,I,M)=>{ri(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),I,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=A=>{let I=i.playbackRate;i.playbackRate!==A&&(t(`Playback rate switch: ${I}=>${A}`),i.playbackRate=A)},f=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let M=z()-1e4,P=0;for(let w=0;w<this.bufferStates.length;w++){let x=this.bufferStates[w];A=Math.min(A,x.buf),x.ts<M&&P++}this.bufferStates.splice(0,P),t(`update playback rate; minBuffer=${A} drop=${P} jitter=${this.sourceJitter}`);let q=A-ll;this.sourceJitter>=0?q-=this.sourceJitter/2:this.sourceJitter-=1,q>3?m(1.15):q>1?m(1.1):q>.3?m(1.05):m(1)}},S=A=>{let I,M=()=>I&&I.start?I.start.length:0,P=k=>I.start[k]/1e3,q=k=>I.dur[k]/1e3,w=k=>I.fragIndex+k,x=(k,B)=>({chunkIdx:w(k),startTS:P(k),dur:q(k),discontinuity:B}),b=()=>{let k=0;if(I&&I.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=B;this.sourceJitter>1&&(j+=this.sourceJitter-1);let W=I.dur.length-1;for(;W>=0&&(j-=I.dur[W],!(j<=0));--W);k=Math.min(W,I.dur.length-1-H),k=Math.max(k,0)}return x(k,!0)},E=k=>{let B=M();if(!(B<=0)){if(Tr(k)){for(let H=0;H<B;H++)if(P(H)>k)return x(H)}return b()}},_=k=>{let B=M(),H=k?k.chunkIdx+1:0,j=H-I.fragIndex;if(!(B<=0)){if(!k||j<0||j-B>ul)return t(`Resync: offset=${j} bChunks=${B} chunk=`+JSON.stringify(k)),b();if(!(j>=B))return x(H-I.fragIndex,!1)}},ne=(k,B,H)=>{l&&l.abort(),l=Vt(this.urlResolver.resolve(k,!0,this.lowLatency),B,H,()=>this._retryCallback()).withTimeout(Ir).withRetryCount($a).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,B)=>{ne(A,H=>{if(!d())return;I=H;let j=!!I.lowLatency;j!==this.lowLatency&&f(j);let W=0;for(let X=0;X<I.dur.length;++X)W+=I.dur[X];W>0&&(ri(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(W/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,k(E(B))},()=>this._handleNetworkError())},nextChunk:_}},D=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ri(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:A=>{let{videoElement:I,logger:M}=this.params,P=S(e.jidxUrl),q,w,x,b,E=0,_,ne,ye,k=()=>{_&&(clearTimeout(_),_=void 0);let R=Math.max(dl,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),oe=E+R,ee=z(),G=Math.min(1e4,oe-ee);E=ee;let Ie=()=>{l||d()&&P.seek(()=>{d()&&(E=z(),B(),k())})};G>0?_=window.setTimeout(()=>{this.paused?k():Ie()},G):Ie()},B=()=>{let R;for(;R=P.nextChunk(b);)b=R,Te(R);let oe=P.nextChunk(x);if(oe){if(x&&oe.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?k():(D(),this._initPlayerWith(e));return}X(oe)}else k()},H=(R,oe)=>{if(!d()||!this.sourceBuffer)return;let ee,G,Ie,Ke=Re=>{window.setTimeout(()=>{d()&&H(R,oe)},Re)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),Ke(100);else{let Re=z(),be=I.currentTime;!this.paused&&I.buffered.length>1&&ne===be&&Re-ye>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),ne!==be&&(ne=be,ye=Re);let Xe=this._getBufferSizeSec();if(Xe>30)M(`Buffered ${Xe} seconds; delaying appendBuffer`),Ke(2e3);else try{this.sourceBuffer.appendBuffer(R),this.videoPlayStarted?(this.bufferStates.push({ts:Re,buf:Xe}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),oe&&oe()}catch(De){if(De.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),Ie=this.sourceBuffer.buffered.length,Ie!==0&&(ee=this.sourceBuffer.buffered.start(0),G=be,G-ee>4&&this.sourceBuffer.remove(ee,G-3)),Ke(1e3);else throw De}}},j=()=>{w&&q&&(M([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(x)]),H(w,function(){w=null,B()}))},W=R=>e.fragUrlTemplate.replace("%%id%%",R.chunkIdx),X=R=>{d()&&h(W(R),(oe,ee)=>{if(d()){if(ee/=1e3,w=oe,x=R,s=R.startTS,ee){let G=Math.min(10,R.dur/ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*G:G}j()}},()=>this._handleNetworkError())},Te=R=>{d()&&(ri(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(W(R),!1)))},N=R=>{d()&&(e.cachedHeader=R,H(R,()=>{q=!0,j()}))};a=!0,P.seek(R=>{if(d()){if(E=z(),!R){k();return}b=R,!sl(A)||R.startTS>A?X(R):(x=R,B())}},A),e.cachedHeader?N(e.cachedHeader):p(e.headerUrl,N,()=>this._handleNetworkError())},stop:D,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,ri(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=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}`)},a={updateChunk:(p,h)=>{let m=z();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,o,u=!0,l=()=>{let d=a.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Pa(s)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=a.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=z();d<o&&(s=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Vt(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;pe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((u,l)=>{u.video&&r.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):(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))},ol))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as cl,filter as bn,fromEvent as pl,interval as hl,isHigher as ml,isInvariantQuality as fl,isLower as bl,merge as gl,Subject as gn,Subscription as Sl}from"@vkontakte/videoplayer-shared/evergreen";var La=class{constructor(){this.onDroopedVideoFramesLimit$=new gn;this.subscription=new Sl;this.playing=!1;this.tracks=[];this.forceChecker$=new gn;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!fl(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{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&&ml(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.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(pl(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=hl(this.droppedFramesChecker.checkTime).pipe(bn(()=>this.playing),bn(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(cl(this.droppedFramesChecker.checkTime)),i=gl(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){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>bl(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Er=La;import{map as vl,Observable as yl}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as Tl}from"@vkontakte/videoplayer-shared/evergreen";var si=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Il=(n,e)=>new yl(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||si()))},{...i,...e});r.observe(n);let a=Tl(document,"visibilitychange").pipe(vl(s=>!document.hidden||si())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),Ae=Il;var wl=["paused","playing","ready"],Ml=["paused","playing","ready"],ni=class{constructor(e){this.subscription=new $l;this.videoState=new $("stopped");this.representations$=new Ma([]);this.droppedFramesManager=new Er;this.maxSeekBackTime$=new Ma(1/0);this.zeroTime$=new Ma(void 0);this.liveOffset=new St;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:yn.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=at(r.name)??Ll(r.video),o=r.bitrate/1e3,u={...r.video};if(!s)continue;let l={id:a,quality:s,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),wa(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Ml.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&wl.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(J(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?.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(J(this.params.source.url,u))}return;default:return Sn(e)}};this.textTracksManager=new ke(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:yn.WTF,message:"DashLiveProvider internal logic error",thrown:r})};In(this.videoState.stateChangeStarted$.pipe(xr(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(xr(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),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(Y(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ce(this.video);this.subscription.add(this.representations$.pipe(xr(r=>r.map(({track:a})=>a)),Tn(r=>!!r.length),Al()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(kl(),xr(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(El({zeroTime:this.zeroTime$.pipe(Tn(wa)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Be(this.video,this.params.desiredState.isLooped,t)).add(de(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(xe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).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(Ae(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&En(r),min:a&&En(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{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":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Sn(r.to)}},t)).add(In(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Pl(["init"])).pipe(xl(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),le(this.video)}createLiveDashPlayer(){let e=new ai({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&wa(t)?t:st(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let l=e.find(({track:c})=>c.id===a)?.representation;vn(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;vn(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(J(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var xn=ni;var Ne=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Nd,assertNonNullable as Fd,debounce as _d,ErrorCategory as vo,filter as yo,filterChanged as Qi,fromEvent as Ud,isNonNullable as To,map as is,merge as jr,observableFrom as rs,once as Io,Subscription as Hd}from"@vkontakte/videoplayer-shared/evergreen";var je=()=>window.ManagedMediaSource||window.MediaSource,kr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),kn=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Pn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Lr,clientChecker as Ar}from"@vkontakte/videoplayer-shared/evergreen";var $r=document.createElement("video"),Cl='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Vl='video/mp4; codecs="hev1.1.6.L93.B0"',An='video/webm; codecs="vp09.00.10.08"',$n='video/webm; codecs="av01.0.00M.08"',Bl='audio/mp4; codecs="mp4a.40.2"',Ol='audio/webm; codecs="opus"',oi={mms:kr(),mse:kn(),hls:!!($r.canPlayType?.("application/x-mpegurl")||$r.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},he={mp4:!!$r.canPlayType?.("video/mp4"),webm:!!$r.canPlayType?.("video/webm"),cmaf:!0},me={h264:!!je()?.isTypeSupported?.(Cl),h265:!!je()?.isTypeSupported?.(Vl),vp9:!!je()?.isTypeSupported?.(An),av1:!!je()?.isTypeSupported?.($n),aac:!!je()?.isTypeSupported?.(Bl),opus:!!je()?.isTypeSupported?.(Ol)},Bt=(me.h264||me.h265)&&me.aac,vt,Nl=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:$n}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:An}})]);vt={DASH_WEBM_AV1:e,DASH_WEBM:t}};Nl().catch(n=>{console.error(n)});var Ot=oi.hls&&he.mp4,Ln=()=>Object.keys(me).filter(n=>me[n]),wn=(n,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let r=oi.mse&&(!i||!!window.MediaStreamTrack)||oi.mms&&t;return n.filter(a=>{switch(a){case"DASH_SEP":return r&&he.mp4&&Bt;case"DASH_WEBM":return r&&he.webm&&me.vp9&&me.opus;case"DASH_WEBM_AV1":return r&&he.webm&&me.av1&&me.opus;case"DASH_STREAMS":return r&&(he.mp4&&Bt||he.webm&&(me.vp9||me.av1)&&(me.opus||me.aac));case"DASH_LIVE":return r&&he.mp4&&Bt;case"DASH_LIVE_CMAF":return r&&he.mp4&&Bt&&he.cmaf;case"DASH_ONDEMAND":return r&&he.mp4&&Bt;case"HLS":case"HLS_ONDEMAND":return Ot||e&&r&&he.mp4&&Bt;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Ot;case"MPEG":return he.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return oi.webrtc&&oi.ws&&me.h264&&(he.mp4||he.webm);default:return Lr(a)}})},Pr=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return vt?vt[t].smooth?[t,e]:vt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return vt?vt[t].powerEfficient?[t,e]:vt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Lr(n)}return[e,t]},Mn=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Pr(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ar.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Pr(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Pr(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Pr(n),...r,"HLS","HLS_ONDEMAND"];default:Lr(e)}return Ot?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Rn=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=Ar.isMac&&Ar.isSafari;if(Ar.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:Lr(n)}else Ot&&!u?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ra=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Dn=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)};import{ErrorCategory as ui}from"@vkontakte/videoplayer-shared/evergreen";var Cn=n=>{if(!n)return{id:"EmptyResponse",category:ui.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:ui.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ui.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ui.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ui.PARSER,message:"Response is valid XML, but parser failed"}};var nt=(n,e,t=0)=>{for(let i=0;i<n.length;i++)if(n.start(i)*1e3-t<=e&&n.end(i)*1e3+t>e)return!0;return!1};import{abortable as Ka,assertNonNullable as Ut,clientChecker as yd,combine as Ht,ErrorCategory as Fe,filter as Br,filterChanged as Or,flattenObject as Ui,fromEvent as Ye,getTraceSubscriptionMethod as Td,interval as Xa,isNonNullable as co,isNullable as po,map as Hi,merge as kt,now as Ja,Subject as Nr,Subscription as ho,tap as Id,throttle as Ed,ValueSubject as Q}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Fl,ErrorCategory as Vn,clientChecker as Da,Subject as Bn}from"@vkontakte/videoplayer-shared/evergreen";var _l=18,On=!1;try{On=Da.isSafari&&!!Da.macVersion&&Da.macVersion<=_l}catch(n){console.error(n)}var Ca=class{constructor(e){this.bufferFull$=new Bn;this.error$=new Bn;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Vn.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};On&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Vn.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){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:Fl(t)}}},Nn=Ca;var Va=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as ut,assertNonNullable as fe,clientChecker as ud,ErrorCategory as Ge,fromEvent as ja,getExponentialDelay as qa,isNonNullable as Ft,isNullable as Z,now as wr,once as ld,Subject as dd,Subscription as cd,ValueSubject as It}from"@vkontakte/videoplayer-shared/evergreen";var C=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)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Nt=class extends C{};var li=class extends C{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,s=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(s);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var di=class extends C{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ci=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var U=class extends C{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var pi=class extends U{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var hi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var mi=class extends C{constructor(e,t){super(e,t),this.data=this.content}};var yt=class extends U{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,s=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:s,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var fi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var bi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gi=class extends U{constructor(e,t){switch(super(e,t),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 Si=class extends U{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var vi=class extends U{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var yi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ti=class extends U{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ii=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ei=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xi=class extends U{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ki=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pi=class extends U{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ai=class extends U{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 $i=class extends U{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 Li=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wi=class extends U{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Mi=class extends C{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Hl={ftyp:di,moov:ci,mvhd:pi,moof:hi,mdat:mi,sidx:yt,trak:fi,mdia:yi,mfhd:xi,tkhd:Ti,traf:ki,tfhd:Pi,tfdt:Ai,trun:$i,minf:Ii,sv3d:bi,st3d:gi,prhd:Si,proj:Ei,equi:vi,uuid:li,stbl:Li,stsd:wi,avc1:Mi,unknown:Nt},qe=class n{constructor(e={}){this.options={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{break}return t}createBox(e,t){let i=Hl[e];return i?new i(t,new n):new Nt(t,new n)}};var ot=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var jl=new TextDecoder("ascii"),ql=n=>jl.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Wl=n=>{let e=new yt(n,new qe),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},Gl=(n,e)=>{let i=new qe().parse(n),r=new ot(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,d)},Yl=n=>{let t=new qe().parse(n),i=new ot(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},zl=n=>{let t=new qe().parse(n);return new ot(t).find("sidx")?.timescale},Kl=(n,e)=>{let i=new qe().parse(n),a=new ot(i).findAll("traf"),s=a[a.length-1].children.find(d=>d.type==="tfhd"),o=a[a.length-1].children.find(d=>d.type==="tfdt"),u=a[a.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Xl=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new qe().parse(n),r=new ot(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Fn={validateData:ql,parseInit:Xl,getIndexRange:()=>{},parseSegments:Wl,parseFeedableSegmentChunk:Gl,getChunkEndTime:Kl,getServerLatencyTimestamps:Yl,getTimescaleFromIndex:zl};import{assertNonNullable as Oa,isNonNullable as Qn,isNullable as Zl}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Jl}from"@vkontakte/videoplayer-shared/evergreen";var _n={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"}},Un=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ri(n,t),r=i in _n,a=r?_n[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),l=s&255>>o,c=Ri(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ri=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},we=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return Ri(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:Jl(e)}},Tt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Un(i);if(!e(r))return;r.type==="master"&&Tt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Hn=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Un(n);return Tt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=we(o,s):a===17026?t=we(o,s):a===17029&&(i=we(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var jn=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ed=[231,22612,22743,167,171,163,160,175],td=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,l,c=!1,d=0;return Tt(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let g=we(m,h);l=Ri(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=we(m,h):p===17545?r=we(m,h):p===21420&&l===475249515?u=we(m,h):p===374648427?Tt(m,({tag:g,type:S,value:D})=>g===30321?(c=we(D,S)===1,!1):!0):a&&s&&jn.includes(p)&&(o=!0),!o}),Oa(e,"Failed to parse webm Segment start"),Oa(t,"Failed to parse webm Segment end"),Oa(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},id=n=>{if(Zl(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},rd=(n,e)=>{let t=!1,i=!1,r=o=>Qn(o.time)&&Qn(o.position),a=[],s;return Tt(n,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=we(l,u));break;case 183:break;case 241:s&&(s.position=we(l,u));break;default:t&&jn.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:l,position:c}=o,d=a[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}}})},ad=n=>{let e=0,t=!1;try{Tt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ed.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},qn={validateData:Hn,parseInit:td,getIndexRange:id,parseSegments:rd,parseFeedableSegmentChunk:ad};var Di=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return qn;case"mp4":return Fn}}throw new ReferenceError(`Unsupported mime type ${n}`)};var Na=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as od,isNullable as Jn}from"@vkontakte/videoplayer-shared/evergreen";var Wn=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Gn=n=>{try{let e=sd(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),s={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(s).forEach(o=>{let u=s[o];(typeof u>"u"||u==="")&&delete s[o]}),s}return null}catch{return null}};function sd(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
63
63
  (?<language>${`(?:[a-z]{2,3}(?:-${n})?|[a-z]{4}|[a-z]{5,8})`})
64
64
  (-(?<script>[a-z]{4}))?
65
65
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
66
66
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
67
67
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
68
68
  (?:-(?<privateuse>(?:${e})))?
69
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}import{videoSizeToQuality as ed}from"@vkontakte/videoplayer-shared/evergreen";var _n=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:s})=>{let o=(a?rt(a):void 0)??ed({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:s}},Un=({id:n,bitrate:e})=>({id:n,bitrate:e}),Hn=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Qn=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Ba=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Oa=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Na=n=>"url"in n,ie=n=>n.type==="template",Di=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var qn=n=>{if(!n?.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},We=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>jn(a)?o:jn(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Gn=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(S=>S.textContent?.trim()??""),o=s.at(0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=a.getAttribute("mediaPresentationDuration"),m=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,f=[...a.getElementsByTagName("Period")],g=f.reduce((S,T)=>({...S,[T.id]:T.children}),{}),y=f.reduce((S,T)=>({...S,[T.id]:T.getAttribute("duration")}),{});p?d=qn(p):Object.values(y).filter(S=>S).length&&!u?d=Object.values(y).reduce((S,T)=>S+(qn(T)??0),0):m&&(d=parseInt(m,10));let R=0,E=a.getAttribute("profiles")?.split(",")??[];for(let S of f.map(T=>T.id))for(let T of g[S]){let A=T.getAttribute("id")??"id"+(R++).toString(10),j=T.getAttribute("mimeType")??"",N=T.getAttribute("codecs")??"",_=T.getAttribute("contentType")??j?.split("/")[0],b=T.getAttribute("profiles")?.split(",")??[],x=Fn(T.getAttribute("lang")??"")??{},U=T.querySelector("Label")?.textContent?.trim()??void 0,be=T.querySelectorAll("Representation"),ge=T.querySelector("SegmentTemplate"),P=T.querySelector("Role")?.getAttribute("value")??void 0,M=_,B={id:A,language:x.language,isDefault:P==="main",label:U,codecs:N,hdr:M==="video"&&Ca(N),mime:j,representations:[]};for(let k of be){let H=k.getAttribute("lang")??void 0,Se=U??T.getAttribute("label")??k.getAttribute("label")??void 0,Lt=k.querySelector("BaseURL")?.textContent?.trim()??"",$e=new URL(Lt||o,e).toString(),D=k.getAttribute("mimeType")??j,K=k.getAttribute("codecs")??N??"",Z;if(_==="text"){let G=k.getAttribute("id")||"",Me=x.privateuse?.includes("x-auto")||G.includes("_auto"),xe=k.querySelector("SegmentTemplate");if(xe){let ke={representationId:k.getAttribute("id")??void 0,bandwidth:k.getAttribute("bandwidth")??void 0},Fe=parseInt(k.getAttribute("bandwidth")??"",10)/1e3,Ke=parseInt(xe.getAttribute("startNumber")??"",10)??1,_e=parseInt(xe.getAttribute("timescale")??"",10),ra=xe.querySelectorAll("SegmentTimeline S")??[],wt=xe.getAttribute("media");if(!wt)continue;let ir=[],rr=0,ar="",$t=0,qt=Ke,ee=0;for(let Pe of ra){let pt=parseInt(Pe.getAttribute("d")??"",10),ve=parseInt(Pe.getAttribute("r")??"",10)||0,Xe=parseInt(Pe.getAttribute("t")??"",10);ee=Number.isFinite(Xe)?Xe:ee;let ht=pt/_e*1e3,Mt=ee/_e*1e3;for(let Re=0;Re<ve+1;Re++){let Je=We(wt,{...ke,segmentNumber:qt.toString(10),segmentTime:(ee+Re*pt).toString(10)}),Rt=(Mt??0)+Re*ht,Wt=Rt+ht;qt++,ir.push({time:{from:Rt,to:Wt},url:Je})}ee+=(ve+1)*pt,rr+=(ve+1)*ht}$t=ee/_e*1e3,ar=We(wt,{...ke,segmentNumber:qt.toString(10),segmentTime:ee.toString(10)});let Gt={time:{from:$t,to:1/0},url:ar},Ue={type:"template",baseUrl:$e,segmentTemplateUrl:wt,initUrl:"",totalSegmentsDurationMs:rr,segments:ir,nextSegmentBeyondManifest:Gt,timescale:_e};Z={id:G,kind:"text",segmentReference:Ue,profiles:[],duration:d,bitrate:Fe,mime:"",codecs:"",width:0,height:0,isAuto:Me}}else Z={id:G,isAuto:Me,kind:"text",url:$e}}else{let G=k.getAttribute("contentType")??D?.split("/")[0]??_,Me=T.getAttribute("profiles")?.split(",")??[],xe=parseInt(k.getAttribute("width")??"",10),ke=parseInt(k.getAttribute("height")??"",10),Fe=parseInt(k.getAttribute("bandwidth")??"",10)/1e3,Ke=k.getAttribute("frameRate")??"",_e=k.getAttribute("quality")??void 0,ra=Ke?Nn(Ke):void 0,wt=k.getAttribute("id")??"id"+(R++).toString(10),ir=G==="video"?`${ke}p`:G==="audio"?`${Fe}Kbps`:K,rr=`${wt}@${ir}`,ar=[...E,...b,...Me],$t,qt=k.querySelector("SegmentBase"),ee=k.querySelector("SegmentTemplate")??ge;if(qt){let Ue=k.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Pe,pt]=Ue.split("-").map(Je=>parseInt(Je,10)),ve={from:Pe,to:pt},Xe=k.querySelector("SegmentBase")?.getAttribute("indexRange"),[ht,Mt]=Xe?Xe.split("-").map(Je=>parseInt(Je,10)):[],Re=Xe?{from:ht,to:Mt}:void 0;$t={type:"byteRange",url:$e,initRange:ve,indexRange:Re}}else if(ee){let Ue={representationId:k.getAttribute("id")??void 0,bandwidth:k.getAttribute("bandwidth")??void 0},Pe=parseInt(ee.getAttribute("timescale")??"",10),pt=ee.getAttribute("initialization")??"",ve=ee.getAttribute("media"),Xe=parseInt(ee.getAttribute("startNumber")??"",10)??1,ht=We(pt,Ue);if(!ve)throw new ReferenceError("No media attribute in SegmentTemplate");let Mt=ee.querySelectorAll("SegmentTimeline S")??[],Re=[],Je=0,Rt="",Wt=0;if(Mt.length){let sr=Xe,Ae=0;for(let Dt of Mt){let De=parseInt(Dt.getAttribute("d")??"",10),mt=parseInt(Dt.getAttribute("r")??"",10)||0,nr=parseInt(Dt.getAttribute("t")??"",10);Ae=Number.isFinite(nr)?nr:Ae;let aa=De/Pe*1e3,nu=Ae/Pe*1e3;for(let or=0;or<mt+1;or++){let ou=We(ve,{...Ue,segmentNumber:sr.toString(10),segmentTime:(Ae+or*De).toString(10)}),ps=(nu??0)+or*aa,uu=ps+aa;sr++,Re.push({time:{from:ps,to:uu},url:ou})}Ae+=(mt+1)*De,Je+=(mt+1)*aa}Wt=Ae/Pe*1e3,Rt=We(ve,{...Ue,segmentNumber:sr.toString(10),segmentTime:Ae.toString(10)})}else if(td(d)){let Ae=parseInt(ee.getAttribute("duration")??"",10)/Pe*1e3,Dt=Math.ceil(d/Ae),De=0;for(let mt=1;mt<Dt;mt++){let nr=We(ve,{...Ue,segmentNumber:mt.toString(10),segmentTime:De.toString(10)});Re.push({time:{from:De,to:De+Ae},url:nr}),De+=Ae}Wt=De,Rt=We(ve,{...Ue,segmentNumber:Dt.toString(10),segmentTime:De.toString(10)})}let su={time:{from:Wt,to:1/0},url:Rt};$t={type:"template",baseUrl:$e,segmentTemplateUrl:ve,initUrl:ht,totalSegmentsDurationMs:Je,segments:Re,nextSegmentBeyondManifest:su,timescale:Pe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!G||!D)continue;let Gt={video:"video",audio:"audio",text:"text"}[G];if(!Gt)continue;M||=Gt,Z={id:rr,kind:Gt,segmentReference:$t,profiles:ar,duration:d,bitrate:Fe,mime:D,codecs:K,width:xe,height:ke,fps:ra,quality:_e}}B.language||=H,B.label||=Se,B.mime||=D,B.codecs||=K,B.hdr||=M==="video"&&Ca(K),B.representations.push(Z)}if(M){let k=r[M].find(H=>H.id===B.id);if(k&&B.representations.every(H=>ie(H.segmentReference)))for(let H of k.representations){let Lt=B.representations.find(D=>D.id===H.id)?.segmentReference,$e=H.segmentReference;$e.segments.push(...Lt.segments),$e.nextSegmentBeyondManifest=Lt.nextSegmentBeyondManifest}else r[M].push(B)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:r,baseUrls:s}};import{isNonNullable as Wn}from"@vkontakte/videoplayer-shared/evergreen";var re=(n,e)=>Wn(n)&&Wn(e)&&n.readyState==="open"&&[...n.activeSourceBuffers].includes(e);var Ci=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new yt(0);this.currentLowLatencySegmentLength$=new yt(0);this.currentSegmentLength$=new yt(0);this.onLastSegment$=new yt(!1);this.fullyBuffered$=new yt(!1);this.playingRepresentation$=new yt(void 0);this.playingRepresentationInit$=new yt(void 0);this.error$=new ad;this.gaps=[];this.subscription=new sd;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=ot(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);he(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new $n(this.sourceBuffer),this.subscription.add(_a(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:ze.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:ze.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(_a(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ze.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!re(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ma(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Be(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,s*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),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);he(i,"No init buffer for starting representation"),he(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=ot(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);he(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(J(a)||J(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),he(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let s=this.getCurrentPosition();_t(s)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(s,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ot(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);he(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(J(a)||J(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),he(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();_t(s)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ot(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!ie(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);he(r);let a=this.segments.get(i);he(a,"No segments for starting representation");let s=this.initData.get(i);if(he(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,ot(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);he(a,`No such representation ${i}`);let s=this.segments.get(i),o=this.initData.get(i);if(J(o)||J(s)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),s=this.segments.get(i),he(s,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();_t(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!J(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(J(e)||J(this.downloadingRepresentationId)||J(this.playingRepresentationId)||J(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer)||_t(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(he(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);_t(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Be(this.sourceBuffer.buffered,e),d=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(a=d)}if(isFinite(this.bufferLimit)&&Ma(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Be(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{let c=o.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.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))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}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;_t(t.duration)&&t.duration-i>0&&!this.isLive&&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?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!ie(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,s=this.segments.get(i.id)??[],o=s.at(-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...s,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;he(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!ie(r))return;let a=this.segments.get(i.id)??[],s=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to,t=s.time.to-s.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=We(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.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:d,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,g=p>i||f||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),R=this.preloadOnly&&p<=i+y||h<=i+y;return(d==="none"||d==="partially_ejected"&&g&&R&&this.sourceBuffer&&re(this.mediaSource,this.sourceBuffer)&&!(st(this.sourceBuffer.buffered,p)&&st(this.sourceBuffer.buffered,h)))&&g&&R});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<a.length&&(s<=l||o<=c);d++){let p=a[d];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){ie(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ot(o,async function*(){let c=Ua(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Lr(),!c)return;let d=new DataView(c),p=Ri(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Di(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ie(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await ot(s,async function*(){let u=Ua(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),_a(window,"online").pipe(rd()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.lastDataObtainedTimestampMs=Lr(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Di(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ie(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:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Lr(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ze.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ie(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?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Lr();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:ze.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}: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)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let s=this.representations.get(t);if(s)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Ri(s.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await s();continue}let c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<r,m=d<=r;if(!h)continue;let f=Ri(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),y=u.loadedBytes===p?g:f.parseFeedableSegmentChunk(g);y?.byteLength&&(l.status="partially_fed",u.feedingBytes+=y.byteLength,await this.sourceBufferTaskQueue.append(y,a)&&!a.aborted?(u.fedBytes+=y.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await s())}}}onSegmentFullyAppended(e,t){if(!(J(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer))){!this.isLive&&id.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(st(this.sourceBuffer.buffered,e.segment.time.from,100)&&st(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ze.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Na(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;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)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?ot(this.destroyAbortController.signal,async function*(){let o=Ua(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ri(e.mime),r)).then(async o=>{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&&ie(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:ze.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||J(e))return!1;let r=[],a=0,s=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=s(r);let l=Na(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||J(e)?0:Be(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ze.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(J(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer)||J(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=s&&c.to+t>=o),l=e.filter(c=>s>=c.from&&s<c.to-t||o>c.from+t&&o<=c.to);u||(l.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")}}handleAsyncError(e,t){this.error$.next({id:t,category:ze.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Vi=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var zn=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as Bi,assertNever as Kn,fromEvent as Xn,merge as nd,now as Oi,Subscription as od,Subject as Jn,ValueSubject as Ha,flattenObject as Ut,ErrorCategory as Ni}from"@vkontakte/videoplayer-shared/evergreen";var Yn=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var $r=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Ha(void 0);this.lastConnectionReused$=new Ha(void 0);this.lastRequestFirstBytes$=new Ha(void 0);this.recoverableError$=new Jn;this.error$=new Jn;this.abortAllController=new AbortController;this.subscription=new od;this.fetchManifest=Bi(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Vi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Yn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(wr);return r?(t.log("success",Ut({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Ut({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Bi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let b=new URL(l,location.href);b.searchParams.append("bytes",`${i.from}-${i.to}`),l=b.toString();break}default:Kn(t)}this.requestQuic&&(l=Vi(l));let p=this.abortAllController.signal,h;if(s){let b=new AbortController;if(h=nd(Xn(this.abortAllController.signal,"abort"),Xn(s,"abort")).subscribe(()=>{try{b.abort()}catch(x){wr(x)}}),this.abortAllController.signal.aborted||s.aborted)try{b.abort()}catch(x){wr(x)}p=b.signal}let m=Oi();d.log("startRequest",Ut({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:a,headers:c,signal:p}),g=Oi();if(!f)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!f.ok||!f.body){h?.unsubscribe();let b=`Fetch error ${f.status}: ${f.statusText}`;return d.error("error",{message:b}),d.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let b=Oi(),x={requestStartedAt:m,requestEndedAt:b,duration:b-m};return d.log("endRequest",Ut(x)),d.end(),f.arrayBuffer()}let[y,R]=f.body.tee(),E=y.getReader();o&&this.throughputEstimator?.trackStream(R,u);let L=0,S=new Uint8Array(0),T=!1,A=b=>{h?.unsubscribe(),T=!0,wr(b)},j=Bi(p,async function*({done:b,value:x}){if(L===0&&this.lastRequestFirstBytes$.next(Oi()-m),p.aborted){h?.unsubscribe();return}if(!b&&x){let U=new Uint8Array(S.length+x.length);U.set(S),U.set(x,S.length),S=U,L+=x.byteLength,r?.(new DataView(S.buffer),L),yield E?.read().then(j,A)}}.bind(this));yield E?.read().then(j,A),h?.unsubscribe();let N=Oi(),_={failed:T,requestStartedAt:m,requestEndedAt:N,duration:N-m};return T?(d.error("endRequest",Ut(_)),d.end(),null):(d.log("endRequest",Ut(_)),d.end(),S.buffer)}.bind(this));this.fetchByteRangeRepresentation=Bi(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(s=Math.min(l,r),o=Math.max(c,a))),s=Math.min(s,0);let d=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(d,m.from-s,m.to-m.from+1);else{let y=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!y)return null;f=new DataView(y)}let g=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Bi(this.abortAllController.signal,async function*(e,t){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=>({...s,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Kn(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ni.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ni.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ni.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ni.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Ni.FATAL})}}},wr=n=>{if(!Di(n))throw n};var Tt=(n,e,t)=>t*e+(1-t)*n,Qa=(n,e)=>n.reduce((t,i)=>t+i,0)/e,Zn=(n,e,t,i)=>{let r=0,a=t,s=Qa(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as ud,ValueSubject as eo}from"@vkontakte/videoplayer-shared/evergreen";var ut=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new eo(e.initial),this.debounced$=new eo(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new te(`raw_${t}`),this.smoothedSeries$=new te(`smoothed_${t}`),this.reportedSeries$=new te(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(ud(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 Mr=class extends ut{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Tt(this.slow,e,this.params.emaAlphaSlow),this.fast=Tt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Rr=class extends ut{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Qa(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Tt(this.emaSmoothed,e,this.params.emaAlpha);let i=Zn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Dr=class extends ut{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?Tt(this.smoothed,t,this.params.emaAlpha):t}};var It=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Mr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Rr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Dr({initial:e,label:"liveEdgeDelay",...t})}};var ja=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as ld,ValueSubject as dd}from"@vkontakte/videoplayer-shared/evergreen";var Fi=class n{constructor(e,t){this.currentRepresentation$=new dd(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!ld(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,s=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<s||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ie(t.segmentReference))}};var Sd=["timeupdate","progress","play","seeked","stalled","waiting"],vd=["timeupdate","progress","loadeddata","playing","seeked"];var Vr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new ao;this.representationSubscription=new ao;this.state$=new w("none");this.currentVideoRepresentation$=new q(void 0);this.currentVideoRepresentationInit$=new q(void 0);this.currentAudioRepresentation$=new q(void 0);this.currentVideoSegmentLength$=new q(0);this.currentAudioSegmentLength$=new q(0);this.error$=new Cr;this.lastConnectionType$=new q(void 0);this.lastConnectionReused$=new q(void 0);this.lastRequestFirstBytes$=new q(void 0);this.currentLiveTextRepresentation$=new q(null);this.isLive$=new q(!1);this.isActiveLive$=new q(!1);this.isLowLatency$=new q(!1);this.liveDuration$=new q(0);this.liveAvailabilityStartTime$=new q(void 0);this.bufferLength$=new q(0);this.liveLatency$=new q(void 0);this.liveLoadBufferLength$=new q(0);this.livePositionFromPlayer$=new q(0);this.currentStallDuration$=new q(0);this.videoLastDataObtainedTimestamp$=new q(0);this.fetcherRecoverableError$=new Cr;this.fetcherError$=new Cr;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Cr;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=qa(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=X(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Oe.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=qa(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Oe.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t=null;try{t=Gn(e??"",this.manifestUrlString)}catch(s){let o=Pn(e)??{id:"ManifestParsing",category:Oe.PARSER,message:"Failed to parse MPD manifest",thrown:s};this.error$.next(o)}if(!t)return null;let i=(s,o,u)=>!!(this.element?.canPlayType?.(o)&&qe()?.isTypeSupported?.(`${o}; codecs="${u}"`)||s==="text");if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let s=(t.duration??0)/1e3;this.liveDuration$.next(-1*s)}let r={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let u=t.streams[s].filter(({mime:d,codecs:p})=>i(s,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=kn(l);if(c&&(r[s]=u.filter(({codecs:d})=>d.startsWith(c))),s==="video"){let d=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);hd.isHDR&&d&&p?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",Ui(a)),a}.bind(this));this.initRepresentations=qa(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ui({initialVideo:e,initialAudio:t,sourceHls:i})),Et(this.manifest),Et(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(kt(d,"error").pipe(_i(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Oe.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Sn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Er())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new Ci("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],io(t)){let d=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Ci("audio",this.source,d,s),this.bufferManagers.push(this.audioBufferManager)}Fi.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Fi(this.manifest.streams.text,s)),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(Wa(1e3).subscribe(d=>{if(this.element?.paused){let p=pr(this.manifestUrlString,2);this.manifestUrlString=X(this.manifestUrlString,p+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Pt(...vd.map(d=>kt(this.element,d))).pipe(Ht(d=>this.element?Be(this.element.buffered,this.element.currentTime*1e3):0),Ga(),bd(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Pt(kt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(xt({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ht(({isActiveLive:p,isLowLatency:h})=>p&&h),Ga()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||ja(this.element,1)})),this.representationSubscription.add(xt({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(_i(({bufferLength:p,isActiveLive:h,isLowLatency:m})=>h&&m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(xt({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(_i(({isActiveLive:p,isLowLatency:h,currentLowLatencySegmentLength:m})=>p&&h&&!!m)).subscribe(({currentLowLatencySegmentLength:p})=>{let h=this.liveDuration$.getValue()-p/1e3;this.liveDuration$.next(Math.min(h,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(xt({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(_i(({isLive:p})=>p),Ht(p=>({...p})),Ga((p,h)=>h.bufferLength<p.bufferLength),Ht(({rtt:p,bufferLength:h,segmentServerLatency:m})=>{let f=pr(this.manifestUrlString,2);return(p/2+h+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(xt({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:h,isLowLatency:m})=>{if(!m||!h)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,R=p-f;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(R)>g&&(E=1+Math.sign(R)*y),ja(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let d=0;this.representationSubscription.add(xt({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gd(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(Et(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,f=pr(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),R=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,L=isFinite(p)?p:h,S=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),T=g<=this.tuning.live.activeLiveDelay&&f===0;this.isActiveLive$.next(T);let A="none";if(S?A="active_low_latency":this.isLowLatency$.getValue()&&T?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),A="active_low_latency"):f!==0&&L<y?A="live_forward_buffering":L<y+E&&(A="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),A==="live_forward_buffering"||A==="live_with_target_offset"){let j=d-(y+R),N=this.normolizeLiveOffset(Math.trunc(f+j/m)),_=Math.abs(N-f),b;!p||_<=this.tuning.dashCmafLive.offsetCalculationError?b=f:N>0&&_>this.tuning.dashCmafLive.offsetCalculationError?b=N:b=0,this.manifestUrlString=X(this.manifestUrlString,b,2)}A!=="none"&&A!=="active_low_latency"&&(d=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Oe.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Pt(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Ht(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=Pt(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Ht(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));if(this.representationSubscription.add(Pt(this.forceEnded$,xt({allBuffersFull:l,someBufferEnded:c}).pipe(_i(({allBuffersFull:d,someBufferEnded:p})=>d&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream(),this.bufferManagers.forEach(d=>d.warmUpMediaSource())}catch(d){this.error$.next({id:"EndOfStream",category:Oe.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Pt(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(d=>this.source?.addEventListener("sourceopen",d))),!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),ie(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&io(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Wa(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Oe.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new $r({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=It.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Et(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=X(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Et(this.element),this.state$.setState("running"),this.subscription.add(Pt(...Sd.map(e=>kt(this.element,e)),kt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Oe.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(kt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(kt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&st(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=fd(),a=100,s=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(s);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<a&&r-s>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<a&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset).catch(p=>{this.error$.next({id:"stallIntervalCallback",category:Oe.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:p})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",Ui(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Wa(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Oe.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Et(this.element),Et(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),st(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ro(this.element)||ro(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ui({requestedPosition:e,forcePrecise:t,position:i})))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=md(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-s<=r&&u.to+s>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ui(i)))}}};var Br=class{constructor(e,t){this.fov=e,this.orientation=t}};var Or=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,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??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){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={...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*(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 so=`attribute vec2 a_vertex;
69
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}import{videoSizeToQuality as nd}from"@vkontakte/videoplayer-shared/evergreen";var Yn=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:s})=>{let o=(a?at(a):void 0)??nd({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:s}},zn=({id:n,bitrate:e})=>({id:n,bitrate:e}),Kn=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Xn=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),_a=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Ua=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Ha=n=>"url"in n,re=n=>n.type==="template",Ci=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Zn=n=>{if(!n?.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},We=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>Jn(a)?o:Jn(u)?a:a.padStart(parseInt(u,10),"0"))}return t},eo=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(w=>w.textContent?.trim()??""),o=s.at(0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=a.getAttribute("publishTime"),d=a.getElementsByTagName("vk:Attrs")[0],p=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,D=a.getAttribute("mediaPresentationDuration"),v=[...a.getElementsByTagName("Period")],A=v.reduce((w,x)=>({...w,[x.id]:x.children}),{}),I=v.reduce((w,x)=>({...w,[x.id]:x.getAttribute("duration")}),{});D?S=Zn(D):Object.values(I).filter(w=>w).length&&!u?S=Object.values(I).reduce((w,x)=>w+(Zn(x)??0),0):f&&(S=parseInt(f,10));let M=0,P=a.getAttribute("profiles")?.split(",")??[];for(let w of v.map(x=>x.id))for(let x of A[w]){let b=x.getAttribute("id")??"id"+(M++).toString(10),E=x.getAttribute("mimeType")??"",_=x.getAttribute("codecs")??"",ne=x.getAttribute("contentType")??E?.split("/")[0],ye=x.getAttribute("profiles")?.split(",")??[],k=Gn(x.getAttribute("lang")??"")??{},B=x.querySelector("Label")?.textContent?.trim()??void 0,H=x.querySelectorAll("Representation"),j=x.querySelector("SegmentTemplate"),W=x.querySelector("Role")?.getAttribute("value")??void 0,X=ne,Te={id:b,language:k.language,isDefault:W==="main",label:B,codecs:_,hdr:X==="video"&&Na(_),mime:E,representations:[]};for(let N of H){let R=N.getAttribute("lang")??void 0,oe=B??x.getAttribute("label")??N.getAttribute("label")??void 0,ee=N.querySelector("BaseURL")?.textContent?.trim()??"",G=new URL(ee||o,e).toString(),Ie=N.getAttribute("mimeType")??E,Ke=N.getAttribute("codecs")??_??"",Re;if(ne==="text"){let be=N.getAttribute("id")||"",Xe=k.privateuse?.includes("x-auto")||be.includes("_auto"),De=N.querySelector("SegmentTemplate");if(De){let qt={representationId:N.getAttribute("id")??void 0,bandwidth:N.getAttribute("bandwidth")??void 0},ir=parseInt(N.getAttribute("bandwidth")??"",10)/1e3,rr=parseInt(De.getAttribute("startNumber")??"",10)??1,At=parseInt(De.getAttribute("timescale")??"",10),oa=De.querySelectorAll("SegmentTimeline S")??[],$t=De.getAttribute("media");if(!$t)continue;let ar=[],sr=0,nr="",Lt=0,Wt=rr,te=0;for(let $e of oa){let ht=parseInt($e.getAttribute("d")??"",10),Ee=parseInt($e.getAttribute("r")??"",10)||0,Je=parseInt($e.getAttribute("t")??"",10);te=Number.isFinite(Je)?Je:te;let mt=ht/At*1e3,wt=te/At*1e3;for(let Ce=0;Ce<Ee+1;Ce++){let Ze=We($t,{...qt,segmentNumber:Wt.toString(10),segmentTime:(te+Ce*ht).toString(10)}),Mt=(wt??0)+Ce*mt,Yt=Mt+mt;Wt++,ar.push({time:{from:Mt,to:Yt},url:Ze})}te+=(Ee+1)*ht,sr+=(Ee+1)*mt}Lt=te/At*1e3,nr=We($t,{...qt,segmentNumber:Wt.toString(10),segmentTime:te.toString(10)});let Gt={time:{from:Lt,to:1/0},url:nr},Ue={type:"template",baseUrl:G,segmentTemplateUrl:$t,initUrl:"",totalSegmentsDurationMs:sr,segments:ar,nextSegmentBeyondManifest:Gt,timescale:At};Re={id:be,kind:"text",segmentReference:Ue,profiles:[],duration:S,bitrate:ir,mime:"",codecs:"",width:0,height:0,isAuto:Xe}}else Re={id:be,isAuto:Xe,kind:"text",url:G}}else{let be=N.getAttribute("contentType")??Ie?.split("/")[0]??ne,Xe=x.getAttribute("profiles")?.split(",")??[],De=parseInt(N.getAttribute("width")??"",10),qt=parseInt(N.getAttribute("height")??"",10),ir=parseInt(N.getAttribute("bandwidth")??"",10)/1e3,rr=N.getAttribute("frameRate")??"",At=N.getAttribute("quality")??void 0,oa=rr?Wn(rr):void 0,$t=N.getAttribute("id")??"id"+(M++).toString(10),ar=be==="video"?`${qt}p`:be==="audio"?`${ir}Kbps`:Ke,sr=`${$t}@${ar}`,nr=[...P,...ye,...Xe],Lt,Wt=N.querySelector("SegmentBase"),te=N.querySelector("SegmentTemplate")??j;if(Wt){let Ue=N.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[$e,ht]=Ue.split("-").map(Ze=>parseInt(Ze,10)),Ee={from:$e,to:ht},Je=N.querySelector("SegmentBase")?.getAttribute("indexRange"),[mt,wt]=Je?Je.split("-").map(Ze=>parseInt(Ze,10)):[],Ce=Je?{from:mt,to:wt}:void 0;Lt={type:"byteRange",url:G,initRange:Ee,indexRange:Ce}}else if(te){let Ue={representationId:N.getAttribute("id")??void 0,bandwidth:N.getAttribute("bandwidth")??void 0},$e=parseInt(te.getAttribute("timescale")??"",10),ht=te.getAttribute("initialization")??"",Ee=te.getAttribute("media"),Je=parseInt(te.getAttribute("startNumber")??"",10)??1,mt=We(ht,Ue);if(!Ee)throw new ReferenceError("No media attribute in SegmentTemplate");let wt=te.querySelectorAll("SegmentTimeline S")??[],Ce=[],Ze=0,Mt="",Yt=0;if(wt.length){let or=Je,Le=0;for(let Rt of wt){let Ve=parseInt(Rt.getAttribute("d")??"",10),ft=parseInt(Rt.getAttribute("r")??"",10)||0,ur=parseInt(Rt.getAttribute("t")??"",10);Le=Number.isFinite(ur)?ur:Le;let ua=Ve/$e*1e3,pu=Le/$e*1e3;for(let lr=0;lr<ft+1;lr++){let hu=We(Ee,{...Ue,segmentNumber:or.toString(10),segmentTime:(Le+lr*Ve).toString(10)}),ys=(pu??0)+lr*ua,mu=ys+ua;or++,Ce.push({time:{from:ys,to:mu},url:hu})}Le+=(ft+1)*Ve,Ze+=(ft+1)*ua}Yt=Le/$e*1e3,Mt=We(Ee,{...Ue,segmentNumber:or.toString(10),segmentTime:Le.toString(10)})}else if(od(S)){let Le=parseInt(te.getAttribute("duration")??"",10)/$e*1e3,Rt=Math.ceil(S/Le),Ve=0;for(let ft=1;ft<Rt;ft++){let ur=We(Ee,{...Ue,segmentNumber:ft.toString(10),segmentTime:Ve.toString(10)});Ce.push({time:{from:Ve,to:Ve+Le},url:ur}),Ve+=Le}Yt=Ve,Mt=We(Ee,{...Ue,segmentNumber:Rt.toString(10),segmentTime:Ve.toString(10)})}let cu={time:{from:Yt,to:1/0},url:Mt};Lt={type:"template",baseUrl:G,segmentTemplateUrl:Ee,initUrl:mt,totalSegmentsDurationMs:Ze,segments:Ce,nextSegmentBeyondManifest:cu,timescale:$e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!be||!Ie)continue;let Gt={video:"video",audio:"audio",text:"text"}[be];if(!Gt)continue;X||=Gt,Re={id:sr,kind:Gt,segmentReference:Lt,profiles:nr,duration:S,bitrate:ir,mime:Ie,codecs:Ke,width:De,height:qt,fps:oa,quality:At}}Te.language||=R,Te.label||=oe,Te.mime||=Ie,Te.codecs||=Ke,Te.hdr||=X==="video"&&Na(Ke),Te.representations.push(Re)}if(X){let N=r[X].find(R=>R.id===Te.id);if(N&&Te.representations.every(R=>re(R.segmentReference)))for(let R of N.representations){let ee=Te.representations.find(Ie=>Ie.id===R.id)?.segmentReference,G=R.segmentReference;G.segments.push(...ee.segments),G.nextSegmentBeyondManifest=ee.nextSegmentBeyondManifest}else r[X].push(Te)}}return{duration:S,streams:r,baseUrls:s,live:g}};import{isNonNullable as to}from"@vkontakte/videoplayer-shared/evergreen";var ae=(n,e)=>to(n)&&to(e)&&n.readyState==="open"&&[...n.activeSourceBuffers].includes(e);var Vi=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new It(0);this.currentLowLatencySegmentLength$=new It(0);this.currentSegmentLength$=new It(0);this.onLastSegment$=new It(!1);this.fullyBuffered$=new It(!1);this.playingRepresentation$=new It(void 0);this.playingRepresentationInit$=new It(void 0);this.error$=new dd;this.gaps=[];this.subscription=new cd;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=ut(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Nn(this.sourceBuffer),this.subscription.add(ja(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ge.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:Ge.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(ja(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ge.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ae(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Va(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ne(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,s*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),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);fe(i,"No init buffer for starting representation"),fe(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=ut(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);fe(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Z(a)||Z(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),fe(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let s=this.getCurrentPosition();Ft(s)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(s,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ut(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);fe(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Z(a)||Z(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),fe(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();Ft(s)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ut(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!re(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);fe(r);let a=this.segments.get(i);fe(a,"No segments for starting representation");let s=this.initData.get(i);if(fe(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,ut(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);fe(a,`No such representation ${i}`);let s=this.segments.get(i),o=this.initData.get(i);if(Z(o)||Z(s)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),s=this.segments.get(i),fe(s,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ft(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Z(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Z(e)||Z(this.downloadingRepresentationId)||Z(this.playingRepresentationId)||Z(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer)||Ft(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(fe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);Ft(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Ne(this.sourceBuffer.buffered,e),d=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(a=d)}if(isFinite(this.bufferLimit)&&Va(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Ne(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{let c=o.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Ne(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))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}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;Ft(t.duration)&&t.duration-i>0&&!this.isLive&&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?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!re(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,s=this.segments.get(i.id)??[],o=s.at(-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...s,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;fe(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!re(r))return;let a=this.segments.get(i.id)??[],s=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to,t=s.time.to-s.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=We(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.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:d,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),D=this.preloadOnly&&p<=i+S||h<=i+S;return(d==="none"||d==="partially_ejected"&&g&&D&&this.sourceBuffer&&ae(this.mediaSource,this.sourceBuffer)&&!(nt(this.sourceBuffer.buffered,p)&&nt(this.sourceBuffer.buffered,h)))&&g&&D});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<a.length&&(s<=l||o<=c);d++){let p=a[d];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){re(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ut(o,async function*(){let c=qa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=wr(),!c)return;let d=new DataView(c),p=Di(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ci(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await ut(s,async function*(){let u=qa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ja(window,"online").pipe(ld()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.lastDataObtainedTimestampMs=wr(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ci(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(re(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:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=wr(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ge.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!re(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?(l,c)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=wr();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ge.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}: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)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let s=this.representations.get(t);if(s)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Di(s.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await s();continue}let c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<r,m=d<=r;if(!h)continue;let f=Di(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:f.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await s())}}}onSegmentFullyAppended(e,t){if(!(Z(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer))){!this.isLive&&ud.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(nt(this.sourceBuffer.buffered,e.segment.time.from,100)&&nt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ge.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ha(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;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)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?ut(this.destroyAbortController.signal,async function*(){let o=qa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Di(e.mime),r)).then(async o=>{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&&re(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ge.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Z(e))return!1;let r=[],a=0,s=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=s(r);let l=Ha(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Z(e)?0:Ne(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Ge.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Z(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer)||Z(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=s&&c.to+t>=o),l=e.filter(c=>s>=c.from&&s<c.to-t||o>c.from+t&&o<=c.to);u||(l.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")}}handleAsyncError(e,t){this.error$.next({id:t,category:Ge.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Bi=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var io=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as Oi,assertNever as ao,fromEvent as so,merge as pd,now as Ni,Subscription as hd,Subject as no,ValueSubject as Wa,flattenObject as _t,ErrorCategory as Fi}from"@vkontakte/videoplayer-shared/evergreen";var ro=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Rr=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Wa(void 0);this.lastConnectionReused$=new Wa(void 0);this.lastRequestFirstBytes$=new Wa(void 0);this.recoverableError$=new no;this.error$=new no;this.abortAllController=new AbortController;this.subscription=new hd;this.fetchManifest=Oi(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Bi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ro(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Mr);return r?(t.log("success",_t({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",_t({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Oi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let b=new URL(l,location.href);b.searchParams.append("bytes",`${i.from}-${i.to}`),l=b.toString();break}default:ao(t)}this.requestQuic&&(l=Bi(l));let p=this.abortAllController.signal,h;if(s){let b=new AbortController;if(h=pd(so(this.abortAllController.signal,"abort"),so(s,"abort")).subscribe(()=>{try{b.abort()}catch(E){Mr(E)}}),this.abortAllController.signal.aborted||s.aborted)try{b.abort()}catch(E){Mr(E)}p=b.signal}let m=Ni();d.log("startRequest",_t({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:a,headers:c,signal:p}),g=Ni();if(!f)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!f.ok||!f.body){h?.unsubscribe();let b=`Fetch error ${f.status}: ${f.statusText}`;return d.error("error",{message:b}),d.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let b=Ni(),E={requestStartedAt:m,requestEndedAt:b,duration:b-m};return d.log("endRequest",_t(E)),d.end(),f.arrayBuffer()}let[S,D]=f.body.tee(),v=S.getReader();o&&this.throughputEstimator?.trackStream(D,u);let A=0,I=new Uint8Array(0),M=!1,P=b=>{h?.unsubscribe(),M=!0,Mr(b)},q=Oi(p,async function*({done:b,value:E}){if(A===0&&this.lastRequestFirstBytes$.next(Ni()-m),p.aborted){h?.unsubscribe();return}if(!b&&E){let _=new Uint8Array(I.length+E.length);_.set(I),_.set(E,I.length),I=_,A+=E.byteLength,r?.(new DataView(I.buffer),A),yield v?.read().then(q,P)}}.bind(this));yield v?.read().then(q,P),h?.unsubscribe();let w=Ni(),x={failed:M,requestStartedAt:m,requestEndedAt:w,duration:w-m};return M?(d.error("endRequest",_t(x)),d.end(),null):(d.log("endRequest",_t(x)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Oi(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=a+1===l,u&&(s=Math.min(l,r),o=Math.max(c,a))),s=Math.min(s,0);let d=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(d,m.from-s,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let g=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Oi(this.abortAllController.signal,async function*(e,t){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=>({...s,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=io(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:ao(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t),r=await i.text(),a=parseInt(r);if(i.ok||isNaN(a))return i;switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Fi.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Fi.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Fi.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Fi.FATAL});break;default:console.log(JSON.stringify(i)),console.log(a),this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Fi.FATAL})}}},Mr=n=>{if(!Ci(n))throw n};var Et=(n,e,t)=>t*e+(1-t)*n,Ga=(n,e)=>n.reduce((t,i)=>t+i,0)/e,oo=(n,e,t,i)=>{let r=0,a=t,s=Ga(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as md,ValueSubject as uo}from"@vkontakte/videoplayer-shared/evergreen";var lt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new uo(e.initial),this.debounced$=new uo(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ie(`raw_${t}`),this.smoothedSeries$=new ie(`smoothed_${t}`),this.reportedSeries$=new ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(md(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 Dr=class extends lt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Et(this.slow,e,this.params.emaAlphaSlow),this.fast=Et(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Cr=class extends lt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ga(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Et(this.emaSmoothed,e,this.params.emaAlpha);let i=oo(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Vr=class extends lt{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?Et(this.smoothed,t,this.params.emaAlpha):t}};var xt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Dr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Cr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Vr({initial:e,label:"liveEdgeDelay",...t})}};var Ya=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as fd,ValueSubject as bd}from"@vkontakte/videoplayer-shared/evergreen";var _i=class n{constructor(e,t){this.currentRepresentation$=new bd(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!fd(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,s=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<s||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&re(t.segmentReference))}};var xd=["timeupdate","progress","play","seeked","stalled","waiting"],kd=["timeupdate","progress","loadeddata","playing","seeked"];var Fr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new ho;this.representationSubscription=new ho;this.state$=new $("none");this.currentVideoRepresentation$=new Q(void 0);this.currentVideoRepresentationInit$=new Q(void 0);this.currentAudioRepresentation$=new Q(void 0);this.currentVideoSegmentLength$=new Q(0);this.currentAudioSegmentLength$=new Q(0);this.error$=new Nr;this.lastConnectionType$=new Q(void 0);this.lastConnectionReused$=new Q(void 0);this.lastRequestFirstBytes$=new Q(void 0);this.currentLiveTextRepresentation$=new Q(null);this.isLive$=new Q(!1);this.isActiveLive$=new Q(!1);this.isLowLatency$=new Q(!1);this.liveDuration$=new Q(0);this.liveSeekableDuration$=new Q(0);this.liveAvailabilityStartTime$=new Q(0);this.liveStreamStatus$=new Q(void 0);this.bufferLength$=new Q(0);this.liveLatency$=new Q(void 0);this.liveLoadBufferLength$=new Q(0);this.livePositionFromPlayer$=new Q(0);this.currentStallDuration$=new Q(0);this.videoLastDataObtainedTimestamp$=new Q(0);this.fetcherRecoverableError$=new Nr;this.fetcherError$=new Nr;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Nr;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Ka(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=J(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Fe.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ka(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Fe.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t=null;try{t=eo(e??"",this.manifestUrlString)}catch(s){let o=Cn(e)??{id:"ManifestParsing",category:Fe.PARSER,message:"Failed to parse MPD manifest",thrown:s};this.error$.next(o)}if(!t)return null;let i=(s,o,u)=>!!(this.element?.canPlayType?.(o)&&je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||s==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:s,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((o-s)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let d="active";l||(d=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(d)}let r={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let u=t.streams[s].filter(({mime:d,codecs:p})=>i(s,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=Dn(l);if(c&&(r[s]=u.filter(({codecs:d})=>d.startsWith(c))),s==="video"){let d=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);yd.isHDR&&d&&p?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",Ui(a)),a}.bind(this));this.initRepresentations=Ka(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ui({initialVideo:e,initialAudio:t,sourceHls:i})),Ut(this.manifest),Ut(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Ye(d,"error").pipe(Br(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Fe.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Pn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&kr())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new Vi("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],co(t)){let d=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Vi("audio",this.source,d,s),this.bufferManagers.push(this.audioBufferManager)}_i.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new _i(this.manifest.streams.text,s)),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$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(kt(...kd.map(d=>Ye(this.element,d))).pipe(Hi(d=>this.element?Ne(this.element.buffered,this.element.currentTime*1e3):0),Or(),Id(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(kt(Ye(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Or()).subscribe(p=>this.liveStreamEndTimestamp=Ja())),this.subscription.add(Ye(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Xa(1e3).subscribe(p=>{let h=mr(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,h+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add(Ye(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ht({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Hi(({isActiveLive:p,isLowLatency:h})=>p&&h),Or()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||Ya(this.element,1)})),this.representationSubscription.add(Ht({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Br(({bufferLength:p,isActiveLive:h,isLowLatency:m})=>h&&m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let h=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(Ht({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Br(({isLive:p})=>p),Or((p,h)=>h.bufferLength<p.bufferLength),Hi(({rtt:p,bufferLength:h,segmentServerLatency:m})=>{let f=mr(this.manifestUrlString,2);return(p/2+h+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ht({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:h,isLowLatency:m})=>{if(!m||!h)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,D=p-f;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(D)>g&&(v=1+Math.sign(D)*S),Ya(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let d=0;this.representationSubscription.add(Ht({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Ed(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=mr(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),D=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,A=isFinite(p)?p:h,I=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),M=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(M);let P="none";if(I?P="active_low_latency":this.isLowLatency$.getValue()&&M?(this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),P="active_low_latency"):f!==0&&A<S?P="live_forward_buffering":A<S+v&&(P="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),P==="live_forward_buffering"||P==="live_with_target_offset"){let q=d-(S+D),w=this.normolizeLiveOffset(Math.trunc(f+q/m)),x=Math.abs(w-f),b=0;!p||x<=this.tuning.dashCmafLive.offsetCalculationError?b=f:w>0&&x>this.tuning.dashCmafLive.offsetCalculationError&&(b=w),this.manifestUrlString=J(this.manifestUrlString,b,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(d=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Fe.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=kt(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Hi(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=kt(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Hi(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue())));if(this.representationSubscription.add(kt(this.forceEnded$,Ht({allBuffersFull:l,someBufferEnded:c}).pipe(Br(({allBuffersFull:d,someBufferEnded:p})=>d&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream(),this.bufferManagers.forEach(d=>d.warmUpMediaSource())}catch(d){this.error$.next({id:"EndOfStream",category:Fe.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(kt(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(d=>this.source?.addEventListener("sourceopen",d))),!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),re(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&co(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Xa(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Fe.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Rr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=xt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Ut(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Ja()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=J(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Ut(this.element),this.state$.setState("running"),this.subscription.add(kt(...xd.map(e=>Ye(this.element,e)),Ye(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Fe.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ye(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ye(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&nt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Ja(),a=100,s=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(s);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<a&&r-s>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<a&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:Fe.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",Ui(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Xa(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Fe.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Ut(this.element),Ut(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),nt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(po(this.element)||po(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ui({requestedPosition:e,forcePrecise:t,position:i})))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Td(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-s<=r&&u.to+s>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ui(i)))}}};var _r=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ur=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,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??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){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={...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*(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 mo=`attribute vec2 a_vertex;
70
70
  attribute vec2 a_texel;
71
71
 
72
72
  varying vec2 v_texel;
@@ -77,7 +77,7 @@ void main(void) {
77
77
  // save texel vector to pass to fragment shader
78
78
  v_texel = a_texel;
79
79
  }
80
- `;var no=`#ifdef GL_ES
80
+ `;var fo=`#ifdef GL_ES
81
81
  precision highp float;
82
82
  precision highp int;
83
83
  #else
@@ -120,6 +120,6 @@ void main(void) {
120
120
  // sample using new coordinates
121
121
  gl_FragColor = texture2D(u_texture, tc);
122
122
  }
123
- `;var Nr=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 Br(this.params.fov,this.params.orientation),this.cameraRotationManager=new Or(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(so,this.gl.VERTEX_SHADER),i=this.createShader(no,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,p=t+r;return[a,s,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}};import{isNullable as Id,now as oo,Subscription as Ed,filter as xd,combine as uo,ValueSubject as za,isNonNullable as kd}from"@vkontakte/videoplayer-shared/evergreen";var Ya=class{constructor(){this.isSeeked$=new za(!1);this.isBuffering$=new za(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ed;this.severeStallOccurred$=new za(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(uo({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(xd(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(uo({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(Id(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a}=this.qualityLimitsOnStall,s=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=oo(),c=r&&this.currentStallsCount>=r,d=i&&l-this.lastUniqueVideoTrackSelectedTimestamp>=i+s&&l-u>=i+s&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,kd(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=oo(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},lo=Ya;import{combine as Pd,map as Ad,observeElementSize as Ld,Subscription as wd,ValueSubject as Ka,noop as $d}from"@vkontakte/videoplayer-shared/evergreen";var Fr=class{constructor(){this.subscription=new wd;this.pipSize$=new Ka(void 0);this.videoSize$=new Ka(void 0);this.elementSize$=new Ka(void 0);this.pictureInPictureWindowRemoveEventListener=$d}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(Ld(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Pd({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Ad(({videoSize:r,inPip:a,pipSize:s})=>a?s:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var At=class{constructor(e){this.subscription=new Od;this.videoState=new w("stopped");this.droppedFramesManager=new Tr;this.stallsManager=new lo;this.elementSizeManager=new Fr;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Zt;this.audioTrackSwitchHistory=new Zt;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(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let s=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-s,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),v(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"),v(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&v(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&v(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?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return Dd(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Nr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Te(e.source.url),this.params=e,this.video=ne(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),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(W(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Vr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=le(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:co.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(po(l=>!!l.length),mo()).subscribe(l=>{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:l})}));let s=this.params.desiredState.seekState.stateChangeEnded$.pipe(Xa(l=>l.to.state!=="none"),Qi());this.stallsManager.connect({isSeeked$:s,currentStallDuration$:this.player.currentStallDuration$.pipe(Qi()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),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(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(po(ho),mo()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Xa(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ce(this.video,t.isLooped,r)),this.subscription.add(ue(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ye(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ee(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),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(Cd(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Ba(h));let m=[];for(let f of h.representations){let g=Un(f);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Oa(p));let h=[];for(let m of p.representations){let f=_n({...m,streamId:p.id});f&&(h.push(f),this.videoTracksMap.set(f,{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=Hn(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&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(_r(this.player.currentStallDuration$,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.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Bd(this.video,"progress")).subscribe(async()=>{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.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);ho(m)&&(this.stallsManager.lastVideoTrackSelected=m);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Qi()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Oa(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qi()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Ba(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Xa(({to:l})=>l==="ready"),Qi());this.subscription.add(_r(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ja(["init"])).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(_r(o,this.player.state$.stateChangeEnded$,Ja(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=_r(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ja(["init"])).pipe(Vd(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:A})=>A===r),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Be(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:A})=>A===f?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(s&&!i){let A=gr(s,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,A?.bitrate??-1/0)}if(o){let A=gr(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,A?.bitrate??-1/0)}}let R=at(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),E=i?R??s:s??R,L=g&&an(E,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),S=this.videoTracksMap.get(E)?.representation,T=L&&this.audioTracksMap.get(L)?.representation;if(S&&T)return[S,T];if(S&&!T&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:co.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),oe(this.video),this.tracer.end()}};var ji=class extends At{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 fo,interval as Nd,map as bo}from"@vkontakte/videoplayer-shared/evergreen";var qi=class extends At{constructor(e){super(e),this.liveOffset=new Qe,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),r(this.player.liveLatency$,e.liveLatency$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe(bo(a=>a.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(fo({interval:Nd(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(a-1);s<=0&&e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(fo({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(bo(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=Qn(a);this.params.output.availableTextTracks$.next([s])}}))}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(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(s,r)})}};import{assertNever as Gi,assertNonNullable as go,debounce as Fd,ErrorCategory as Ur,filter as _d,isNonNullable as Ud,isNullable as Hd,map as Hr,merge as Qd,Observable as jd,observableFrom as qd,Subscription as Gd,videoSizeToQuality as Wd}from"@vkontakte/videoplayer-shared/evergreen";var we={};var Qt=(n,e)=>new jd(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Wi=class{constructor(e){this.subscription=new Gd;this.videoState=new w("initializing");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?.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:Gi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Gi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Gi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Gi(e)}break;default:Gi(t)}};this.textTracksManager=new Te(e.source.url),this.video=ne(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(W(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),oe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ur.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||(we.Hls=r.default,we.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){go(we.Hls,"hls.js not loaded"),this.hls=new we.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){go(we.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Ur.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=le(this.video),a=(l,c)=>this.subscription.add(l.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.loadedMetadata$,t.loadedMetadataEvent$),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(Ce(this.video,e.isLooped,i)),this.subscription.add(ue(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ye(this.video,e.playbackRate,r.playbackRateState$,i)),a(Ee(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Hr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Qt(this.hls,we.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ur.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Qt(this.hls,we.Events.MANIFEST_PARSED).pipe(Hr(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:m}=d,f=rt(d.attrs.QUALITY??"")??Wd({width:h,height:m});if(!f)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:f,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:y,level:d}),c.push(y),c},[]))),t.availableVideoTracks$),a(Qt(this.hls,we.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;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),a(Qt(this.hls,we.Events.LEVEL_LOADING).pipe(Hr(({url:l})=>W(l))),t.hostname$),a(Qt(this.hls,we.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(et(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let s=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=Qt(this.hls,we.Events.LEVEL_SWITCHED).pipe(Hr(({level:l})=>s(this.hls.levels[l])));o.pipe(_d(Ud)).subscribe(t.currentVideoTrack$,i),this.subscription.add(et(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),l=>{if(Hd(l))return;let c=this.trackLevels.get(l.id)?.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:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=Qd(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qd(["init"])).pipe(Fd(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)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ur.DOM,thrown:t}))||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("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"),v(this.params.desiredState.playbackState,"stopped",!0)}};var So="X-Playback-Duration",Za=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(So)?parseInt(e.headers.get(So),10):void 0};import{assertNever as ac,combine as sc,debounce as nc,ErrorCategory as qr,filter as oc,filterChanged as uc,isNonNullable as To,isNullable as Gr,map as Io,merge as lc,observableFrom as dc,Subscription as cc,ValueSubject as ts,VideoQuality as pc}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as zd,getExponentialDelay as Yd}from"@vkontakte/videoplayer-shared/evergreen";var Kd=n=>{let e=null;if(n.QUALITY&&(e=rt(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=zd({width:t,height:i})}return e??null},Xd=(n,e)=>{let t=n.split(`
124
- `),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),u=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=Object.fromEntries(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=Kd(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[g,y]=l.RESOLUTION.split("x").map(R=>parseInt(R,10));g&&y&&(m={width:g,height:y})}let f=new URL(t[++a],e).toString();d&&i.push({id:c,quality:d,url:f,bandwidth:p,size:m,fps:h})}if(u){let l=Object.fromEntries(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&r.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Jd=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),es=0,vo=async(n,e=n,t,i)=>{let a=await(await fetch(n,i)).text();es+=1;try{let{qualityManifests:s,textTracks:o}=Xd(a,e);return{qualityManifests:s,textTracks:o}}catch{if(es<=t.manifestRetryMaxCount)return await Jd(Yd(es-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),vo(n,e,t)}return{qualityManifests:[],textTracks:[]}},Qr=vo;import{isNonNullable as Zd,Subscription as ec,throttle as tc,ValueSubject as yo,Subject as ic,ErrorCategory as rc}from"@vkontakte/videoplayer-shared/evergreen";var jr=class{constructor(e,t,i,r,a){this.subscription=new ec;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new yo(null);this.getCurrentTime$=new yo(null);this.error$=new ic;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(tc(1e3)).subscribe(s=>{this.processLiveTime(s)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),s=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(s,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
125
- `),a=0;for(let s=0;s<r.length;++s){let o=r[s];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++s],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+c},url:l}),a=a+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Zd(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let s of t)if(s.time.from<=e&&s.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:s.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:rc.WTF,thrown:t,message:e})}};var zi=class{constructor(e){this.subscription=new cc;this.videoState=new w("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ts([]);this.liveOffset=new Qe;this.manifestStartTime$=new ts(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(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(a||s||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(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),v(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.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&v(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?.to==="paused"&&(v(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return ac(t)}};this.params=e,this.video=ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:pc.INVARIANT,url:this.params.source.url};let t=(i,r)=>Qr(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new jr(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Te(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:qr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:qr.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(W(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ts(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:qr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=le(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),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(ue(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ee(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(uc(),Io(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&To(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(W(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)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(sc({startTime:this.manifestStartTime$.pipe(oc(To)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Io(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$,i));let s=lc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,dc(["init"])).pipe(nc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),oe(this.video)}prepare(){let e=this.selectManifest();if(Gr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=X(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(s),this.video.setAttribute("src",s),this.video.load(),Za(s).then(o=>{if(!Gr(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Gr(u)||!isFinite(u))&&fetch(s).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,s).toString();Za(d).then(p=>{Gr(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qr.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()}generateLiveUrl(){let e=X(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as hc,debounce as mc,ErrorCategory as is,fromEvent as rs,isNonNullable as fc,isNullable as bc,map as Eo,merge as xo,observableFrom as ko,Subscription as gc,ValueSubject as Sc,VideoQuality as vc,clientChecker as yc}from"@vkontakte/videoplayer-shared/evergreen";var Yi=class{constructor(e){this.subscription=new gc;this.videoState=new w("stopped");this.manifests$=new Sc([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(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(a||s||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(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return hc(t)}};this.textTracksManager=new Te(e.source.url),this.params=e,this.video=ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:vc.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(W(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Qr(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:is.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:is.WTF,message:"HlsProvider internal logic error",thrown:o})},r=le(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),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(Eo(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ce(this.video,t.isLooped,i)),this.subscription.add(ue(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.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&&fc(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(W(m.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}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)},i))),this.subscription.add(this.manifests$.pipe(Eo(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$,i)),!yc.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(xo(rs(o,"addtrack"),rs(o,"removetrack"),rs(o,"change"),ko(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=xo(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ko(["init"])).pipe(mc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),oe(this.video)}prepare(){let e=this.selectManifest();if(bc(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:a,min:s}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[s,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:is.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Tc,assertNonNullable as Po,debounce as Ic,ErrorCategory as Ao,isHigherOrEqual as Ec,isLowerOrEqual as xc,isNonNullable as kc,merge as Pc,observableFrom as Ac,Subscription as Lc,map as wc}from"@vkontakte/videoplayer-shared/evergreen";var Ki=class{constructor(e){this.subscription=new Lc;this.videoState=new w("stopped");this.trackUrls={};this.textTracksManager=new Te;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.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"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?v(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return Tc(e)}};this.params=e,this.video=ne(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Ao.WTF,message:"MpegProvider internal logic error",thrown:o})},r=le(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),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(wc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ce(this.video,t.isLooped,i)),this.subscription.add(ue(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ee(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&kc(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Pc(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ac(["init"])).pipe(Ic(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),oe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Po(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Po(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Vi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(W(t))}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ao.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let c=at(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),s=Object.values(this.trackUrls).map(l=>l.track);if(!r||!a||Jt({limits:e,lowestAvailableQuality:s.at(-1)?.quality,highestAvailableQuality:s[0].quality})){i();return}let o=e.max?xc(r,e.max):!0,u=e.min?Ec(r,e.min):!0;o&&u||i(e)}};import{assertNever as wo,debounce as Dc,merge as $o,observableFrom as Cc,Subscription as Vc,map as Mo,ValueSubject as Bc,ErrorCategory as ss,VideoQuality as Oc}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as $c}from"@vkontakte/videoplayer-shared/evergreen";var Lo=["stun:videostun.mycdn.me:80"],Mc=1e3,Rc=3,as=()=>null,Wr=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=as;this.externalStopCallback=as;this.externalErrorCallback=as;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Lo}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:$c.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){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),Mc)}normalizeOptions(e={}){let t={stunServerList:Lo,maxRetryNumber:Rc,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xi=class{constructor(e){this.videoState=new w("stopped");this.maxSeekBackTime$=new Bc(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"),v(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"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return wo(e)}};this.subscription=new Vc,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ne(e.container,e.tuning),this.liveStreamClient=new Wr(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),oe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:ss.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};$o(this.videoState.stateChangeStarted$.pipe(Mo(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Mo(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=le(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Ee(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(()=>{this.videoState.getTransition()?.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(ue(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 wo(s.to)}},i)).add($o(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Cc(["init"])).pipe(Dc(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(W(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:Oc.INVARIANT}),this.video.srcObject=e,v(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:ss.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){de(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ss.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ji=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 Zi,assertNonNullable as lt,ErrorCategory as zr,filter as Oo,isNonNullable as No,isNullable as qc,map as Gc,merge as Wc,once as zc,Subject as Y,Subscription as Fo,ValueSubject as $,flattenObject as _o}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as Nc,map as Ro,Subscription as Fc,Subject as _c}from"@vkontakte/videoplayer-shared/evergreen";var Do=n=>new Nc(e=>{let t=new Fc,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(Ro(({from:l,to:c})=>`${l}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(Ro(({type:l})=>l!==void 0)),s=new _c,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>s.next(l),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as Uc,Subscription as Hc,combine as Qc,filter as Vo,once as Bo}from"@vkontakte/videoplayer-shared/evergreen";function Co(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as jc}from"@vkontakte/videoplayer-shared/evergreen";var jt=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Hc;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Vo(a=>!!a.type),Bo()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){jc.isSafari&&e!=="MPEG"||this.subscriptions.add(Qc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Vo(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),Bo()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Co();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:n.errorId,category:Uc.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var Yc={chunkDuration:5e3,maxParallelRequests:5},er=class{constructor(e){this.current$=new $({type:void 0});this.providerError$=new Y;this.noAvailableProvidersError$=new Y;this.volumeMultiplierError$=new Y;this.providerOutput={position$:new $(0),duration$:new $(1/0),volume$:new $({muted:!1,volume:1}),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableVideoTracks$:new $([]),currentVideoTrack$:new $(void 0),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0),isAudioAvailable$:new $(!0),autoVideoTrackLimitingAvailable$:new $(!1),autoVideoTrackLimits$:new $(void 0),currentBuffer$:new $(void 0),isBuffering$:new $(!0),error$:new Y,fetcherError$:new Y,fetcherRecoverableError$:new Y,warning$:new Y,willSeekEvent$:new Y,soundProhibitedEvent$:new Y,seekedEvent$:new Y,loopedEvent$:new Y,endedEvent$:new Y,firstBytesEvent$:new Y,loadedMetadataEvent$:new Y,firstFrameEvent$:new Y,canplay$:new Y,isLive$:new $(void 0),isLowLatency$:new $(!1),canChangePlaybackSpeed$:new $(!0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),liveLatency$:new $(void 0),severeStallOccurred$:new Y,availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),inPiP$:new $(!1),inFullscreen$:new $(!1),element$:new $(void 0),elementVisible$:new $(!0),availableSources$:new $(void 0),is3DVideo$:new $(!1),playbackState$:new $(""),getCurrentTime$:new $(null)};this.subscription=new Fo;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=In([...xn(this.params.tuning),...En(this.params.tuning)],this.params.tuning).filter(l=>No(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",_o(a)),this.screenFormatsIterator=new Ji(a);let s=[...La(!0),...La(!1)];this.chromecastFormatsIterator=new Ji(s.filter(l=>No(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&jt.isSupported()&&(this.volumeMultiplierManager=new jt(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(qc(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:zr.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.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination: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"}),this.tracer.log("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}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Zi(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return lt(o),new ji({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return lt(o),new qi({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return lt(o),Nt||!this.params.tuning.useHlsJs?new Yi({...s,source:o}):new Wi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return lt(o),new zi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return lt(o),new Ki({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return lt(o),new bn({...s,source:o,config:{...Yc,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return lt(o),new Xi({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Zi(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return lt(o),new zt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Zi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Zi(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 Zi(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{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new Fo,t=!1,i=0;return e.add(Wc(this.providerOutput.error$.pipe(Oo(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Do({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Gc(r=>({id:`ProviderHangup:${r}`,category:zr.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Oo(({to:a})=>a==="playing"),zc()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,s={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===zr.NETWORK,u=r.category===zr.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);s={...s,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}this.tracer.error("providerError",_o(s))})),e}};import{fromEvent as Yr,once as Kc,combine as Xc,Subscription as Uo,ValueSubject as ns,map as Jc,filter as Zc,isNonNullable as Kr,now as fe,safeStorage as os}from"@vkontakte/videoplayer-shared/evergreen";var ep=5e3,Ho="one_video_throughput",Qo="one_video_rtt",tr=window.navigator.connection,jo=()=>{let n=tr?.downlink;if(Kr(n)&&n!==10)return n*1e3},qo=()=>{let n=tr?.rtt;if(Kr(n)&&n!==3e3)return n},Go=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},us=class n{constructor(e){this.subscription=new Uo;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Ho)||(e.useBrowserEstimation?jo():void 0)||ep,i=n.load(Qo)??(e.useBrowserEstimation?qo():void 0)??0;if(this.throughput$=new ns(t),this.rtt$=new ns(i),this.rttAdjustedThroughput$=new ns(Go(t,i,e.rttPenaltyRequestSize)),this.throughput=It.getSmoothedValue(t,-1,e),this.rtt=It.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=jo();s&&this.throughput.next(s);let o=qo();Kr(o)&&this.rtt.next(o)};tr&&"onchange"in tr&&this.subscription.add(Yr(tr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{os.set(Ho,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{os.set(Qo,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Xc({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Jc(({throughput:r,rtt:a})=>Go(r,a,e.rttPenaltyRequestSize)),Zc(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=fe(),r=new Uo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Yr(e,"progress").pipe(Kc()).subscribe(a=>{t=a.loaded,i=fe()}));break;case 1:case 0:r.add(Yr(e,"loadstart").subscribe(()=>{t=0,i=fe()}));break}r.add(Yr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=fe(),u=s-t,l=o-i;this.addRawSpeed(u,l,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=fe(),s=0,o=fe(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,fe()-a,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=fe();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(s,m,1,t),s=d.byteLength,a=fe()}else s+=d.byteLength;o=fe()}else r+=d.byteLength,s+=d.byteLength,s>=this.tuningConfig.streamMinSampleSize&&fe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,fe()-o,this.concurrentDownloads.size),s=0,o=fe());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=os.get(e);if(Kr(t))return parseInt(t,10)??void 0}},Wo=us;import{fillWithDefault as tp,VideoQuality as Xr}from"@vkontakte/videoplayer-shared/evergreen";var zo={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:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Xr.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Xr.Q_720P,trafficSavingLimit:Xr.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Xr.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{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:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,useLazyInit:!1},Yo=n=>({...tp(n,zo),configName:[...n.configName??[],...zo.configName]});import{assertNonNullable as Jr,combine as Ye,ErrorCategory as Zr,filter as ae,filterChanged as O,fromEvent as ds,isNonNullable as up,isNullable as lp,Logger as dp,map as V,mapTo as Zo,merge as dt,now as ea,once as Ne,Subject as F,Subscription as eu,tap as tu,ValueSubject as I,isHigher as cp,isInvariantQuality as iu,flattenObject as ct,throttle as cs,getTraceSubscriptionMethod as ru,Tracer as pp,InternalsExposure as hp,uuid as mp}from"@vkontakte/videoplayer-shared/evergreen";import{merge as ip,map as rp,filter as Ko,isNonNullable as ap}from"@vkontakte/videoplayer-shared/evergreen";var ls=({seekState:n,position$:e})=>ip(n.stateChangeEnded$.pipe(rp(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Ko(ap)),e.pipe(Ko(()=>n.getState().state==="none")));import{assertNonNullable as sp}from"@vkontakte/videoplayer-shared/evergreen";var Xo=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return sp(e,`Wrong container or containerId {${n.container}}`),e};import{filter as np,once as op}from"@vkontakte/videoplayer-shared/evergreen";var Jo=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(np(r=>r.length>0),op()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var ta=class{constructor(e={configName:[]},t=pp.createRootTracer(!1)){this.id=mp();this.subscription=new eu;this.logger=new dp;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new I(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new w("stopped"),seekState:new w({state:"none"}),volume:new w({volume:1,muted:!1}),videoTrack:new w(void 0),videoStream:new w(void 0),audioStream:new w(void 0),autoVideoTrackSwitching:new w(!0),autoVideoTrackLimits:new w({}),isLooped:new w(!1),isLowLatency:new w(!1),playbackRate:new w(1),externalTextTracks:new w([]),internalTextTracks:new w([]),currentTextTrack:new w(void 0),textTrackCuesSettings:new w({}),cameraOrientation:new w({x:0,y:0})};this.info={playbackState$:new I("stopped"),position$:new I(0),duration$:new I(1/0),muted$:new I(!1),volume$:new I(1),availableVideoStreams$:new I([]),currentVideoStream$:new I(void 0),availableQualities$:new I([]),availableQualitiesFps$:new I({}),currentQuality$:new I(void 0),isAutoQualityEnabled$:new I(!0),autoQualityLimitingAvailable$:new I(!1),autoQualityLimits$:new I({}),predefinedQualityLimitType$:new I("unknown"),availableAudioStreams$:new I([]),currentAudioStream$:new I(void 0),availableAudioTracks$:new I([]),isAudioAvailable$:new I(!0),currentPlaybackRate$:new I(1),currentBuffer$:new I({start:0,end:0}),isBuffering$:new I(!0),isStalled$:new I(!1),isEnded$:new I(!1),isLooped$:new I(!1),isLive$:new I(void 0),canChangePlaybackSpeed$:new I(void 0),atLiveEdge$:new I(void 0),atLiveDurationEdge$:new I(void 0),liveTime$:new I(void 0),liveBufferTime$:new I(void 0),liveLatency$:new I(void 0),currentFormat$:new I(void 0),availableTextTracks$:new I([]),currentTextTrack$:new I(void 0),throughputEstimation$:new I(void 0),rttEstimation$:new I(void 0),videoBitrate$:new I(void 0),hostname$:new I(void 0),httpConnectionType$:new I(void 0),httpConnectionReused$:new I(void 0),surface$:new I("none"),chromecastState$:new I("NOT_AVAILABLE"),chromecastDeviceName$:new I(void 0),intrinsicVideoSize$:new I(void 0),availableSources$:new I(void 0),is3DVideo$:new I(!1),currentVideoSegmentLength$:new I(0),currentAudioSegmentLength$:new I(0)};this.events={inited$:new F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,fetcherRecoverableError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,autoplaySoundProhibited$:new F,firstBytes$:new F,loadedMetadata$:new F,firstFrame$:new F,canplay$:new F,log$:new F,fetcherError$:new F,severeStallOccured$:new F};this.experimental={element$:new I(void 0),tuningConfigName$:new I([]),enableDebugTelemetry$:new I(!1),dumpTelemetry:qs,getCurrentTime$:new I(null)};if(this.initLogs(),this.tuning=Yo(e),this.tracer=t,console.log(`Embed: SDK: PLayer: useLazyInit = ${this.tuning.useLazyInit}`),this.tuning.useLazyInit,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new cr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Wo(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new hp("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let s=Reflect.get(i,r,a);return typeof s!="function"?s:(...o)=>{try{return s.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Zr.WTF,message:d,thrown:u}),u}}}})}createProviderContainer(e){this.providerContainer=new er({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderDebugTelemetry(),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init()}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",ct(i)),this.domContainer=Xo(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.initTracerSubscription(),this.tuning.useLazyInit||this.createProviderContainer(e),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initBasicDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{this.providerContainer||this.createProviderContainer(this.config);let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ai()?(this.tracer.log("request play from hidden tab"),ds(document,"visibilitychange").pipe(Ne()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;return e>=i&&!r&&(a=i-.2),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t})),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e,t){let i=this.desiredState.volume,r=this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||r);return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e,i=this.info.volume$.getValue();return this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:i,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:i,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Jr(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ne()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",ct(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}return this.setAutoQualityLimits(r),this}setPlaybackRate(e){Jr(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",ct(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Jo(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),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(lp(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return up(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((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(dt(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(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ga({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ae(({from:e})=>e==="stopped"),Ne()).subscribe(()=>{this.initedAt=ea(),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();this.tracer.log("willSeekEvent",ct(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Zr.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ne()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ct(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(s=>s.destination),O()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ye({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(V(({availableVideoTracks:s,currentVideoStream:o})=>s.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>iu(u)?1:iu(l)?-1:cp(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(O()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(O((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(O((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(O()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(O()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(O()).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??{})})).add(e.providerOutput.currentBuffer$.pipe(V(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(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Ye({hasLiveOffsetByPaused:dt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(s=>s.to),O(),V(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ye({atLiveEdge:Ye({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ls({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:s,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return s&&Math.abs(o)<l/1e3}),O(),tu(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(Ye({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),O(),tu(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(s=>s.muted),O()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(s=>s.volume),O()).subscribe(this.info.volume$)).add(ls({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(dt(e.providerOutput.endedEvent$.pipe(Zo(!0)),e.providerOutput.seekedEvent$.pipe(Zo(!1))).pipe(O()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(V(s=>({id:s?`No${s}`:"NoProviders",category:Zr.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.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Ne(),V(s=>s??ea()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ne(),V(()=>ea()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ne(),V(()=>ea()-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 I(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new I(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:s})=>s==="playing"),Ne()).subscribe(()=>i.next(!1)));let r=0,a=dt(e.providerOutput.isBuffering$,t,i).pipe(V(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),O());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(dt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(dt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?s?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?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new eu;this.subscription.add(t),this.subscription.add(e.current$.pipe(O((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ne()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=at(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput: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(dt(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$))}initBasicDebugTelemetry(){js(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(e=>Qs(e)),this.events.fatalError$.subscribe(new te("fatalError")),this.events.managedError$.subscribe(new te("managedError")),this.info.currentBuffer$.subscribe(new te("buffer"))].forEach(e=>this.subscription.add(e)),Xt("codecs",Tn())}initProviderDebugTelemetry(){let e=this.providerContainer?.providerOutput;Jr(this.providerContainer),Jr(e),[this.providerContainer.current$.subscribe(({type:t})=>Xt("provider",t)),e.duration$.subscribe(t=>Xt("duration",t)),e.availableVideoTracks$.pipe(ae(t=>!!t.length),Ne()).subscribe(t=>Xt("tracks",t)),e.position$.subscribe(new te("position")),e.currentVideoTrack$.pipe(V(t=>t?.quality)).subscribe(new te("quality")),e.isBuffering$.subscribe(new te("isBuffering"))].forEach(t=>this.subscription.add(t))}initTracerSubscription(){let e=ru(this.tracer.log.bind(this.tracer)),t=ru(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(O()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Ye({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ae(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),O((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ae(i=>i>0),O()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ae(i=>i>0),O()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Ye({currentBuffer:this.info.currentBuffer$.pipe(ae(i=>i.end>0),O((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(O())}).pipe(cs(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(O()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(O()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(O()).subscribe(e("canChangePlaybackSpeed"))).add(Ye({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ae(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),cs(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(O(),ae(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(O(),ae(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(O()).subscribe(e("muted"))).add(this.info.volume$.pipe(O()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(O(),ae(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ye({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ae(({throughputEstimation:i,rtt:r})=>!!i&&!!r),cs(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(O(),ae(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Zr.DOM,message:String(r)})})};this.subscription.add(dt(ds(document,"visibilitychange"),ds(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",ct({quality:t,availableTracks:ct(e),track:ct(i),isAutoQuality:!i})),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 oA,Observable as uA,Subject as lA,ValueSubject as dA,VideoQuality as cA}from"@vkontakte/videoplayer-shared/evergreen";import{ValueSubject as fp}from"@vkontakte/videoplayer-shared/evergreen";var au="vk_vp_channel";var ia=class{constructor(e){this.ownerId=e;this.channel=new BroadcastChannel(au);this.listeners=new Map;this.other=[];this.start=performance.now();this.isBlocked=new fp(!0);this.handleMessage=e=>{let{data:t}=e,{type:i,from:r,to:a}=t;i==="register"?(!this.isBlocked.getValue()||this.tmt)&&(this.other.push(r),this.debug(`Send wait for ${r}: diff ${performance.now()-this.start}`),this.postMessage({type:"wait",from:this.ownerId,to:r})):i==="wait"&&this.tmt&&a===this.ownerId&&(this.debug(`CLEAR TIMEOUT, MUST WAIT: diff ${performance.now()-this.start}`),window.clearTimeout(this.tmt),this.tmt=0)};this.channel.onmessage=this.handleMessage,this.postMessage({type:"register",from:this.ownerId}),this.tmt=window.setTimeout(()=>{this.tmt=0},1e3)}destroy(){}postMessage(e){this.debug("postMessage",e),this.channel.postMessage(e),this.channel.onmessage}debug(e,...t){console.log(`PlayerGroupManager ${this.ownerId}: ${e}:`,...t)}};var pA=`@vkontakte/videoplayer-core@${hs}`;export{ur as ChromecastState,sa as HttpConnectionType,uA as Observable,se as PlaybackState,ta as Player,ia as PlayerGroupManager,lr as PredefinedQualityLimits,pA as SDK_VERSION,lA as Subject,oA as Subscription,na as Surface,hs as VERSION,dA as ValueSubject,Ze as VideoFormat,cA as VideoQuality};
123
+ `;var Hr=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 _r(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ur(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(mo,this.gl.VERTEX_SHADER),i=this.createShader(fo,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,p=t+r;return[a,s,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}};import{isNullable as $d,now as bo,Subscription as Ld,filter as wd,combine as go,ValueSubject as Za,isNonNullable as Md}from"@vkontakte/videoplayer-shared/evergreen";var es=class{constructor(){this.isSeeked$=new Za(!1);this.isBuffering$=new Za(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ld;this.severeStallOccurred$=new Za(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(go({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(wd(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(go({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if($d(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a}=this.qualityLimitsOnStall,s=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=bo(),c=r&&this.currentStallsCount>=r,d=i&&l-this.lastUniqueVideoTrackSelectedTimestamp>=i+s&&l-u>=i+s&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,Md(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=bo(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},So=es;import{combine as Rd,map as Dd,observeElementSize as Cd,Subscription as Vd,ValueSubject as ts,noop as Bd}from"@vkontakte/videoplayer-shared/evergreen";var Qr=class{constructor(){this.subscription=new Vd;this.pipSize$=new ts(void 0);this.videoSize$=new ts(void 0);this.elementSize$=new ts(void 0);this.pictureInPictureWindowRemoveEventListener=Bd}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(Cd(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Rd({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Dd(({videoSize:r,inPip:a,pipSize:s})=>a?s:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Pt=class{constructor(e){this.subscription=new Hd;this.videoState=new $("stopped");this.droppedFramesManager=new Er;this.stallsManager=new So;this.elementSizeManager=new Qr;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ei;this.audioTrackSwitchHistory=new ei;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(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),y(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"),y(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&y(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Nd(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Hr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new ke(e.source.url),this.params=e,this.video=ue(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),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(Y(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Fr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=ce(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:vo.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(yo(l=>!!l.length),Io()).subscribe(l=>{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:l})}));let s=this.params.desiredState.seekState.stateChangeEnded$.pipe(is(l=>l.to.state!=="none"),Qi());this.stallsManager.connect({isSeeked$:s,currentStallDuration$:this.player.currentStallDuration$.pipe(Qi()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),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(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(yo(To),Io()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(is(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Be(this.video,t.isLooped,r)),this.subscription.add(de(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(xe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ae(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),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(Fd(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(_a(h));let m=[];for(let f of h.representations){let g=zn(f);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Ua(p));let h=[];for(let m of p.representations){let f=Yn({...m,streamId:p.id});f&&(h.push(f),this.videoTracksMap.set(f,{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=Kn(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&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(jr(this.player.currentStallDuration$,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.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ud(this.video,"progress")).subscribe(async()=>{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.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);To(m)&&(this.stallsManager.lastVideoTrackSelected=m);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Qi()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Ua(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qi()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(_a(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(is(({to:l})=>l==="ready"),Qi());this.subscription.add(jr(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,rs(["init"])).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(jr(o,this.player.state$.stateChangeEnded$,rs(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=jr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,rs(["init"])).pipe(_d(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:P})=>P===r),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:P})=>P===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ne(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:P})=>P===f?.id)??this.audioStreamsMap.keys().next().value,S=0;if(g){if(s&&!i){let P=vr(s,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,P?.bitrate??-1/0)}if(o){let P=vr(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,P?.bitrate??-1/0)}}let D=st(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),v=i?D??s:s??D,A=g&&pn(v,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=this.videoTracksMap.get(v)?.representation,M=A&&this.audioTracksMap.get(A)?.representation;if(I&&M)return[I,M];if(I&&!M&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vo.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),le(this.video),this.tracer.end()}};var ji=class extends Pt{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 qr,merge as Eo,filter as Qd,filterChanged as jd,isNullable as as,map as xo,ValueSubject as ss}from"@vkontakte/videoplayer-shared/evergreen";var qi=class extends Pt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let s=new ss(1);a(i.playbackRateState$,s),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(xo(o=>o.to)).subscribe(this.player.isLowLatency$)).add(qr({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(xo(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(qr({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add(qr({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Eo(i.playbackRateState$,new ss(1))}).pipe(Qd(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||as(l)||(e=o-l)})).add(qr({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Eo(i.playbackRateState$,new ss(1))}).pipe(jd((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||as(o)||as(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Xn(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as Wi,assertNonNullable as ko,debounce as qd,ErrorCategory as Wr,filter as Wd,isNonNullable as Gd,isNullable as Yd,map as Gr,merge as zd,Observable as Kd,observableFrom as Xd,Subscription as Jd,videoSizeToQuality as Zd}from"@vkontakte/videoplayer-shared/evergreen";var Me={};var Qt=(n,e)=>new Kd(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Gi=class{constructor(e){this.subscription=new Jd;this.videoState=new $("initializing");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?.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:Wi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Wi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Wi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Wi(e)}break;default:Wi(t)}};this.textTracksManager=new ke(e.source.url),this.video=ue(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),le(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Wr.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(Me.Hls=r.default,Me.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){ko(Me.Hls,"hls.js not loaded"),this.hls=new Me.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){ko(Me.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Wr.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=ce(this.video),a=(l,c)=>this.subscription.add(l.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.loadedMetadata$,t.loadedMetadataEvent$),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(Be(this.video,e.isLooped,i)),this.subscription.add(de(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(xe(this.video,e.playbackRate,r.playbackRateState$,i)),a(Ae(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Gr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Qt(this.hls,Me.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Wr.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Qt(this.hls,Me.Events.MANIFEST_PARSED).pipe(Gr(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:m}=d,f=at(d.attrs.QUALITY??"")??Zd({width:h,height:m});if(!f)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:f,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),a(Qt(this.hls,Me.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;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),a(Qt(this.hls,Me.Events.LEVEL_LOADING).pipe(Gr(({url:l})=>Y(l))),t.hostname$),a(Qt(this.hls,Me.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(tt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let s=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=Qt(this.hls,Me.Events.LEVEL_SWITCHED).pipe(Gr(({level:l})=>s(this.hls.levels[l])));o.pipe(Wd(Gd)).subscribe(t.currentVideoTrack$,i),this.subscription.add(tt(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),l=>{if(Yd(l))return;let c=this.trackLevels.get(l.id)?.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:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=zd(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Xd(["init"])).pipe(qd(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)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wr.DOM,thrown:t}))||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("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"),y(this.params.desiredState.playbackState,"stopped",!0)}};var Po="X-Playback-Duration",ns=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Po)?parseInt(e.headers.get(Po),10):void 0};import{assertNever as dc,combine as cc,debounce as pc,ErrorCategory as Kr,filter as hc,filterChanged as mc,isNonNullable as Lo,isNullable as Xr,map as wo,merge as fc,observableFrom as bc,Subscription as gc,ValueSubject as us,VideoQuality as Sc}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as ec,getExponentialDelay as tc}from"@vkontakte/videoplayer-shared/evergreen";var ic=n=>{let e=null;if(n.QUALITY&&(e=at(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ec({width:t,height:i})}return e??null},rc=(n,e)=>{let t=n.split(`
124
+ `),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),u=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=Object.fromEntries(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=ic(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(D=>parseInt(D,10));g&&S&&(m={width:g,height:S})}let f=new URL(t[++a],e).toString();d&&i.push({id:c,quality:d,url:f,bandwidth:p,size:m,fps:h})}if(u){let l=Object.fromEntries(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&r.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},ac=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),os=0,Ao=async(n,e=n,t,i)=>{let a=await(await fetch(n,i)).text();os+=1;try{let{qualityManifests:s,textTracks:o}=rc(a,e);return{qualityManifests:s,textTracks:o}}catch{if(os<=t.manifestRetryMaxCount)return await ac(tc(os-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ao(n,e,t)}return{qualityManifests:[],textTracks:[]}},Yr=Ao;import{isNonNullable as sc,Subscription as nc,throttle as oc,ValueSubject as $o,Subject as uc,ErrorCategory as lc}from"@vkontakte/videoplayer-shared/evergreen";var zr=class{constructor(e,t,i,r,a){this.subscription=new nc;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new $o(null);this.getCurrentTime$=new $o(null);this.error$=new uc;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(oc(1e3)).subscribe(s=>{this.processLiveTime(s)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),s=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(s,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
125
+ `),a=0;for(let s=0;s<r.length;++s){let o=r[s];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++s],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+c},url:l}),a=a+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(sc(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let s of t)if(s.time.from<=e&&s.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:s.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:lc.WTF,thrown:t,message:e})}};var Yi=class{constructor(e){this.subscription=new gc;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new us([]);this.liveOffset=new St;this.manifestStartTime$=new us(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(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(a||s||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(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),y(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.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(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?.to==="paused"&&(y(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return dc(t)}};this.params=e,this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Sc.INVARIANT,url:this.params.source.url};let t=(i,r)=>Yr(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new zr(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ke(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Kr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Kr.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(Y(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new us(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Kr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ce(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),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(de(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xe(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ae(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(mc(),wo(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Lo(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(Y(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)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(cc({startTime:this.manifestStartTime$.pipe(hc(Lo)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(wo(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$,i));let s=fc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,bc(["init"])).pipe(pc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){let e=this.selectManifest();if(Xr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=J(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(s),this.video.setAttribute("src",s),this.video.load(),ns(s).then(o=>{if(!Xr(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Xr(u)||!isFinite(u))&&fetch(s).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,s).toString();ns(d).then(p=>{Xr(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kr.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()}generateLiveUrl(){let e=J(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as vc,debounce as yc,ErrorCategory as ls,fromEvent as ds,isNonNullable as Tc,isNullable as Ic,map as Mo,merge as Ro,observableFrom as Do,Subscription as Ec,ValueSubject as xc,VideoQuality as kc,clientChecker as Pc}from"@vkontakte/videoplayer-shared/evergreen";var zi=class{constructor(e){this.subscription=new Ec;this.videoState=new $("stopped");this.manifests$=new xc([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(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(a||s||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(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return vc(t)}};this.textTracksManager=new ke(e.source.url),this.params=e,this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:kc.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(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Yr(J(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:ls.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ls.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ce(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),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(Mo(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Be(this.video,t.isLooped,i)),this.subscription.add(de(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xe(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.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&&Tc(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Y(m.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}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)},i))),this.subscription.add(this.manifests$.pipe(Mo(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$,i)),!Pc.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Ro(ds(o,"addtrack"),ds(o,"removetrack"),ds(o,"change"),Do(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=Ro(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Do(["init"])).pipe(yc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){let e=this.selectManifest();if(Ic(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:a,min:s}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[s,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ls.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Ac,assertNonNullable as Co,debounce as $c,ErrorCategory as Vo,isHigherOrEqual as Lc,isLowerOrEqual as wc,isNonNullable as Mc,merge as Rc,observableFrom as Dc,Subscription as Cc,map as Vc}from"@vkontakte/videoplayer-shared/evergreen";var Ki=class{constructor(e){this.subscription=new Cc;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new ke;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.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"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?y(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Ac(e)}};this.params=e,this.video=ue(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Vo.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ce(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),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(Vc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Be(this.video,t.isLooped,i)),this.subscription.add(de(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xe(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ae(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Mc(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Rc(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Dc(["init"])).pipe($c(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),le(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Co(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Co(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Bi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Y(t))}playIfAllowed(){pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let c=st(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),s=Object.values(this.trackUrls).map(l=>l.track);if(!r||!a||Zt({limits:e,lowestAvailableQuality:s.at(-1)?.quality,highestAvailableQuality:s[0].quality})){i();return}let o=e.max?wc(r,e.max):!0,u=e.min?Lc(r,e.min):!0;o&&u||i(e)}};import{assertNever as Oo,debounce as Fc,merge as No,observableFrom as _c,Subscription as Uc,map as Fo,ValueSubject as Hc,ErrorCategory as ps,VideoQuality as Qc}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Bc}from"@vkontakte/videoplayer-shared/evergreen";var Bo=["stun:videostun.mycdn.me:80"],Oc=1e3,Nc=3,cs=()=>null,Jr=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=cs;this.externalStopCallback=cs;this.externalErrorCallback=cs;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Bo}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Bc.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){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),Oc)}normalizeOptions(e={}){let t={stunServerList:Bo,maxRetryNumber:Nc,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xi=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new Hc(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"),y(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"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Oo(e)}};this.subscription=new Uc,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ue(e.container,e.tuning),this.liveStreamClient=new Jr(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),le(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:ps.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};No(this.videoState.stateChangeStarted$.pipe(Fo(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Fo(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=ce(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Ae(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(()=>{this.videoState.getTransition()?.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(de(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 Oo(s.to)}},i)).add(No(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,_c(["init"])).pipe(Fc(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(Y(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:Qc.INVARIANT}),this.video.srcObject=e,y(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:ps.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ps.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ji=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 Zi,assertNonNullable as dt,ErrorCategory as Zr,filter as qo,isNonNullable as Wo,isNullable as Xc,map as Jc,merge as Zc,once as ep,Subject as K,Subscription as Go,ValueSubject as L,flattenObject as Yo}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as jc,map as _o,Subscription as qc,Subject as Wc}from"@vkontakte/videoplayer-shared/evergreen";var Uo=n=>new jc(e=>{let t=new qc,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(_o(({from:l,to:c})=>`${l}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(_o(({type:l})=>l!==void 0)),s=new Wc,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>s.next(l),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as Gc,Subscription as Yc,combine as zc,filter as Qo,once as jo}from"@vkontakte/videoplayer-shared/evergreen";function Ho(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as Kc}from"@vkontakte/videoplayer-shared/evergreen";var jt=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Yc;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Qo(a=>!!a.type),jo()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Kc.isSafari&&e!=="MPEG"||this.subscriptions.add(zc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Qo(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),jo()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Ho();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:n.errorId,category:Gc.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var tp={chunkDuration:5e3,maxParallelRequests:5},er=class{constructor(e){this.current$=new L({type:void 0});this.providerError$=new K;this.noAvailableProvidersError$=new K;this.volumeMultiplierError$=new K;this.providerOutput={position$:new L(0),duration$:new L(1/0),volume$:new L({muted:!1,volume:1}),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableVideoTracks$:new L([]),currentVideoTrack$:new L(void 0),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0),isAudioAvailable$:new L(!0),autoVideoTrackLimitingAvailable$:new L(!1),autoVideoTrackLimits$:new L(void 0),currentBuffer$:new L(void 0),isBuffering$:new L(!0),error$:new K,fetcherError$:new K,fetcherRecoverableError$:new K,warning$:new K,willSeekEvent$:new K,soundProhibitedEvent$:new K,seekedEvent$:new K,loopedEvent$:new K,endedEvent$:new K,firstBytesEvent$:new K,loadedMetadataEvent$:new K,firstFrameEvent$:new K,canplay$:new K,isLive$:new L(void 0),isLiveEnded$:new L(null),isLowLatency$:new L(!1),canChangePlaybackSpeed$:new L(!0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),liveLatency$:new L(void 0),severeStallOccurred$:new K,availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),inPiP$:new L(!1),inFullscreen$:new L(!1),element$:new L(void 0),elementVisible$:new L(!0),availableSources$:new L(void 0),is3DVideo$:new L(!1),playbackState$:new L(""),getCurrentTime$:new L(null)};this.subscription=new Go;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=wn([...Rn(this.params.tuning),...Mn(this.params.tuning)],this.params.tuning).filter(l=>Wo(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Yo(a)),this.screenFormatsIterator=new Ji(a);let s=[...Ra(!0),...Ra(!1)];this.chromecastFormatsIterator=new Ji(s.filter(l=>Wo(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&jt.isSupported()&&(this.volumeMultiplierManager=new jt(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Xc(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Zr.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.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination: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"}),this.tracer.log("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}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Zi(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return dt(o),new ji({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return dt(o),new qi({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return dt(o),Ot||!this.params.tuning.useHlsJs?new zi({...s,source:o}):new Gi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return dt(o),new Yi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return dt(o),new Ki({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return dt(o),new xn({...s,source:o,config:{...tp,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return dt(o),new Xi({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Zi(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return dt(o),new zt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Zi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Zi(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 Zi(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{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new Go,t=!1,i=0;return e.add(Zc(this.providerOutput.error$.pipe(qo(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Uo({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Jc(r=>({id:`ProviderHangup:${r}`,category:Zr.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(qo(({to:a})=>a==="playing"),ep()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,s={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Zr.NETWORK,u=r.category===Zr.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);s={...s,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}this.tracer.error("providerError",Yo(s))})),e}};import{fromEvent as ea,once as ip,combine as rp,Subscription as zo,ValueSubject as hs,map as ap,filter as sp,isNonNullable as ta,now as ve,safeStorage as ms}from"@vkontakte/videoplayer-shared/evergreen";var np=5e3,Ko="one_video_throughput",Xo="one_video_rtt",tr=window.navigator.connection,Jo=()=>{let n=tr?.downlink;if(ta(n)&&n!==10)return n*1e3},Zo=()=>{let n=tr?.rtt;if(ta(n)&&n!==3e3)return n},eu=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},fs=class n{constructor(e){this.subscription=new zo;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Ko)||(e.useBrowserEstimation?Jo():void 0)||np,i=n.load(Xo)??(e.useBrowserEstimation?Zo():void 0)??0;if(this.throughput$=new hs(t),this.rtt$=new hs(i),this.rttAdjustedThroughput$=new hs(eu(t,i,e.rttPenaltyRequestSize)),this.throughput=xt.getSmoothedValue(t,-1,e),this.rtt=xt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=Jo();s&&this.throughput.next(s);let o=Zo();ta(o)&&this.rtt.next(o)};tr&&"onchange"in tr&&this.subscription.add(ea(tr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{ms.set(Ko,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{ms.set(Xo,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(rp({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ap(({throughput:r,rtt:a})=>eu(r,a,e.rttPenaltyRequestSize)),sp(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ve(),r=new zo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(ea(e,"progress").pipe(ip()).subscribe(a=>{t=a.loaded,i=ve()}));break;case 1:case 0:r.add(ea(e,"loadstart").subscribe(()=>{t=0,i=ve()}));break}r.add(ea(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=ve(),u=s-t,l=o-i;this.addRawSpeed(u,l,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=ve(),s=0,o=ve(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,ve()-a,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=ve();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(s,m,1,t),s=d.byteLength,a=ve()}else s+=d.byteLength;o=ve()}else r+=d.byteLength,s+=d.byteLength,s>=this.tuningConfig.streamMinSampleSize&&ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,ve()-o,this.concurrentDownloads.size),s=0,o=ve());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=ms.get(e);if(ta(t))return parseInt(t,10)??void 0}},tu=fs;import{fillWithDefault as op,VideoQuality as ia}from"@vkontakte/videoplayer-shared/evergreen";var iu={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:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:ia.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:ia.Q_720P,trafficSavingLimit:ia.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ia.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{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:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!0,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1},ru=n=>({...op(n,iu),configName:[...n.configName??[],...iu.configName]});import{assertNonNullable as ra,combine as ze,ErrorCategory as aa,filter as se,filterChanged as O,fromEvent as gs,isNonNullable as mp,isNullable as fp,Logger as bp,map as V,mapTo as ou,merge as ct,now as sa,once as _e,Subject as F,Subscription as uu,tap as Ss,ValueSubject as T,isHigher as gp,isInvariantQuality as lu,flattenObject as pt,throttle as vs,getTraceSubscriptionMethod as du,Tracer as Sp,InternalsExposure as vp}from"@vkontakte/videoplayer-shared/evergreen";import{merge as up,map as lp,filter as au,isNonNullable as dp}from"@vkontakte/videoplayer-shared/evergreen";var bs=({seekState:n,position$:e})=>up(n.stateChangeEnded$.pipe(lp(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),au(dp)),e.pipe(au(()=>n.getState().state==="none")));import{assertNonNullable as cp}from"@vkontakte/videoplayer-shared/evergreen";var su=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return cp(e,`Wrong container or containerId {${n.container}}`),e};import{filter as pp,once as hp}from"@vkontakte/videoplayer-shared/evergreen";var nu=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(pp(r=>r.length>0),hp()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var na=class{constructor(e={configName:[]},t=Sp.createRootTracer(!1)){this.subscription=new uu;this.logger=new bp;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new T(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),isLowLatency:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new T("stopped"),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableVideoStreams$:new T([]),currentVideoStream$:new T(void 0),availableQualities$:new T([]),availableQualitiesFps$:new T({}),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),predefinedQualityLimitType$:new T("unknown"),availableAudioStreams$:new T([]),currentAudioStream$:new T(void 0),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),isLiveEnded$:new T(null),canChangePlaybackSpeed$:new T(void 0),atLiveEdge$:new T(void 0),atLiveDurationEdge$:new T(void 0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),liveLatency$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T("none"),chromecastState$:new T("NOT_AVAILABLE"),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1),currentVideoSegmentLength$:new T(0),currentAudioSegmentLength$:new T(0)};this.events={inited$:new F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,fetcherRecoverableError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,autoplaySoundProhibited$:new F,firstBytes$:new F,loadedMetadata$:new F,firstFrame$:new F,canplay$:new F,log$:new F,fetcherError$:new F,severeStallOccured$:new F};this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Zs,getCurrentTime$:new T(null)};if(this.initLogs(),this.tuning=ru(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new hr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new tu(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new vp("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let s=Reflect.get(i,r,a);return typeof s!="function"?s:(...o)=>{try{return s.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:aa.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",pt(i)),this.domContainer=su(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new er({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!si()?(this.tracer.log("request play from hidden tab"),gs(document,"visibilitychange").pipe(_e()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;return e>=i&&!r&&(a=i-.2),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t})),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e,t){let i=this.desiredState.volume,r=this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||r);return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e,i=this.info.volume$.getValue();return this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:i,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:i,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){ra(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(se(i=>i.length>0),_e()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",pt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}return this.setAutoQualityLimits(r),this}setPlaybackRate(e){ra(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",pt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return nu(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),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(fp(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return mp(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((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(ct(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(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ta({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(se(({from:e})=>e==="stopped"),_e()).subscribe(()=>{this.initedAt=sa(),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();this.tracer.log("willSeekEvent",pt(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:aa.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(_e()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",pt(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(s=>s.destination),O()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ze({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(V(({availableVideoTracks:s,currentVideoStream:o})=>s.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>lu(u)?1:lu(l)?-1:gp(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(O()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(O((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(O((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(O()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(O()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(O()).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??{})})).add(e.providerOutput.currentBuffer$.pipe(V(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.isLiveEnded$.pipe(Ss(s=>s&&this.stop())).subscribe(this.info.isLiveEnded$)).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(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ze({hasLiveOffsetByPaused:ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(s=>s.to),O(),V(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ze({atLiveEdge:ze({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:bs({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:s,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return s&&Math.abs(o)<l/1e3}),O(),Ss(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(ze({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),O(),Ss(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(s=>s.muted),O()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(s=>s.volume),O()).subscribe(this.info.volume$)).add(bs({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ct(e.providerOutput.endedEvent$.pipe(ou(!0)),e.providerOutput.seekedEvent$.pipe(ou(!1))).pipe(O()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(V(s=>({id:s?`No${s}`:"NoProviders",category:aa.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.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(_e(),V(s=>s??sa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(_e(),V(()=>sa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(_e(),V(()=>sa()-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 T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(se(({to:s})=>s==="playing"),_e()).subscribe(()=>i.next(!1)));let r=0,a=ct(e.providerOutput.isBuffering$,t,i).pipe(V(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),O());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(ct(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ct(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?s?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?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new uu;this.subscription.add(t),this.subscription.add(e.current$.pipe(O((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(se(i=>i.length>0),_e()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=st(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput: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(ct(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(){let e=this.providerContainer?.providerOutput;ra(this.providerContainer),ra(e),Js(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Xs(t)),this.providerContainer.current$.subscribe(({type:t})=>Jt("provider",t)),e.duration$.subscribe(t=>Jt("duration",t)),e.availableVideoTracks$.pipe(se(t=>!!t.length),_e()).subscribe(t=>Jt("tracks",t)),this.events.fatalError$.subscribe(new ie("fatalError")),this.events.managedError$.subscribe(new ie("managedError")),e.position$.subscribe(new ie("position")),e.currentVideoTrack$.pipe(V(t=>t?.quality)).subscribe(new ie("quality")),this.info.currentBuffer$.subscribe(new ie("buffer")),e.isBuffering$.subscribe(new ie("isBuffering"))].forEach(t=>this.subscription.add(t)),Jt("codecs",Ln())}initTracerSubscription(){let e=du(this.tracer.log.bind(this.tracer)),t=du(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(O()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ze({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(se(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),O((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(se(i=>i>0),O()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(se(i=>i>0),O()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ze({currentBuffer:this.info.currentBuffer$.pipe(se(i=>i.end>0),O((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(O())}).pipe(vs(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(O()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(O()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(O()).subscribe(e("canChangePlaybackSpeed"))).add(ze({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(se(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),vs(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(O(),se(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(O(),se(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(O()).subscribe(e("muted"))).add(this.info.volume$.pipe(O()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(O(),se(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ze({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(se(({throughputEstimation:i,rtt:r})=>!!i&&!!r),vs(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(O(),se(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:aa.DOM,message:String(r)})})};this.subscription.add(ct(gs(document,"visibilitychange"),gs(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",pt({quality:t,availableTracks:pt(e),track:pt(i),isAutoQuality:!i})),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 sA,Observable as nA,Subject as oA,ValueSubject as uA,VideoQuality as lA}from"@vkontakte/videoplayer-shared/evergreen";var dA=`@vkontakte/videoplayer-core@${Ts}`;export{dr as ChromecastState,la as HttpConnectionType,nA as Observable,ge as PlaybackState,na as Player,cr as PredefinedQualityLimits,dA as SDK_VERSION,oA as Subject,sA as Subscription,da as Surface,Ts as VERSION,uA as ValueSubject,et as VideoFormat,lA as VideoQuality};