@vkontakte/videoplayer-core 2.0.118-dev.f24234cb.0 → 2.0.118-dev.feac9bf3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +16 -15
- package/es2015.esm.js +14 -13
- package/es2018.cjs.js +16 -15
- package/es2018.esm.js +14 -13
- package/esnext.cjs.js +15 -14
- package/esnext.esm.js +13 -12
- package/evergreen.esm.js +15 -14
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -0
- package/types/player/types.d.ts +2 -0
- package/types/providers/HlsLiveProvider/LiveTextManager.d.ts +42 -0
- package/types/providers/HlsLiveProvider/index.d.ts +2 -0
- package/types/providers/HlsProvider/manifestDataExtractor.d.ts +1 -1
- package/types/providers/types.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +1 -0
package/evergreen.esm.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.118-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.118-dev.feac9bf3.0
|
|
3
|
+
* Wed, 04 Dec 2024 10:13:33 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-118/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Ka="2.0.118-dev.f24234cb.0";var re=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(re||{}),Ye=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(Ye||{});var tr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(tr||{}),jr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(jr||{});var qr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(qr||{});import{assertNever as is,assertNonNullable as Uo,isNonNullable as ir,ValueSubject as Wr,Subject as Ho,Subscription as Qo,merge as jo,observableFrom as qo,fromEvent as Xa,map as Za,tap as es,filterChanged as Wo,isNullable as Gr,ErrorCategory as ts}from"@vkontakte/videoplayer-shared/evergreen";var Ja=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var rr=class{constructor(e){this.connection$=new Wr(void 0);this.castState$=new Wr("NOT_AVAILABLE");this.errorEvent$=new Ho;this.realCastState$=new Wr("NOT_AVAILABLE");this.subscription=new Qo;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=ir(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||Ja("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ts.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(){ir(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Gr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Gr(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Xa(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 is(r.sessionState)}})).add(jo(Xa(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(es(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Za(r=>r.castState)),qo([i.getCastState()])).pipe(Wo(),Za(Go),es(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=ir(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();Uo(o);let u=o.getCastDevice(),d=o.getMediaSession()?.media?.contentId;(Gr(d)||d===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"?ir(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:ts.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Go=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 is(n)}};import{assertNever as rs}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:rs(t)}return n},ar=(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:rs(e)}};var T=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as Yo,Subject as sr,merge as as}from"@vkontakte/videoplayer-shared/evergreen";var $=class{constructor(e){this.transitionStarted$=new sr;this.transitionEnded$=new sr;this.transitionUpdated$=new sr;this.forceChanged$=new sr;this.stateChangeStarted$=as(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=as(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||Yo(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 zo}from"@vkontakte/videoplayer-shared/evergreen";var ss=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 zo(n)}};import{assertNever as Mt,assertNonNullable as pt,debounce as ns,ErrorCategory as os,fromEvent as ht,isNonNullable as us,map as ds,merge as ls,observableFrom as Ko,Subject as Jo,Subscription as Yr,timeout as Xo,getHighestQuality as Zo}from"@vkontakte/videoplayer-shared/evergreen";var eu=5,tu=5,iu=500,cs=7e3,jt=class{constructor(e){this.subscription=new Yr;this.loadMediaTimeoutSubscription=new Yr;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:Mt(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:Mt(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:Mt(e)}break}default:Mt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ss(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 Yr;this.subscription.add(e),this.subscription.add(ls(this.videoState.stateChangeStarted$.pipe(ds(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(ds(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 Jo;e.add(r.pipe(ns(iu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(ht(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)>eu)&&r.next(o),a=o})),e.add(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ht(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<tu&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Mt(s)}}),t(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=ls(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ko(["init"])).pipe(ns(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(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 d=t[e];pt(d);let l=Zo(Object.keys(d));pt(l);let c=d[l];pt(c),i=c,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];pt(d),i=d.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 d=t[e];pt(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];pt(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];pt(d),i=J(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",l=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:os.VIDEO_PIPELINE,message:d,thrown:l}),l}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Mt(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 us(o)&&(s.metadata.title=o),us(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(Xo(cs).subscribe(()=>a(`timeout(${cs})`)))});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:os.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as hs}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as ru}from"@vkontakte/videoplayer-shared/evergreen";var ps=n=>{try{n.pause(),n.playbackRate=0,ru(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as au,Subscription as su}from"@vkontakte/videoplayer-shared/evergreen";var zr=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)}},Kr=window.WeakMap?new WeakMap:new zr,Jr=window.WeakMap?new WeakMap:new Map,nu=(n,e=20)=>{let t=0;return au(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ae=(n,{audioVideoSyncRate:e})=>{let t=n.querySelector("video"),i=!!t;t?hs(t):(t=document.createElement("video"),n.appendChild(t)),Kr.set(t,i);let r=new su;return r.add(nu(t,e)),Jr.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},se=n=>{Jr.get(n)?.unsubscribe(),Jr.delete(n);let t=Kr.get(n);Kr.delete(n),t?hs(n):ps(n)};import{assertNonNullable as qt,isNonNullable as Re,isNullable as du,fromEvent as Rt,merge as ms,observableFrom as fs,filterChanged as bs,map as Wt,Subject as gs,Subscription as lu,ValueSubject as cu,ErrorCategory as pu}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Xr,isNullable as ou,Subscription as uu}from"@vkontakte/videoplayer-shared/evergreen";var nr=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=ou(r),d=new uu;return r&&d.add(r.subscribe(l=>{let c=n.getState();i(l,c)&&n.setState(l)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),u&&n.setState(l.to)},a)),d},Me=(n,e,t)=>nr(e,()=>n.loop,i=>{Xr(i)&&(n.loop=i)},{onError:t}),ne=(n,e,t,i)=>nr(e,()=>({muted:n.muted,volume:n.volume}),r=>{Xr(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}),ge=(n,e,t,i)=>nr(e,()=>n.playbackRate,r=>{Xr(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),ze=nr;var hu=n=>["__",n.language,n.label].join("|"),mu=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Zr=class n{constructor(){this.available$=new gs;this.current$=new cu(void 0);this.error$=new gs;this.subscription=new lu;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:pu.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(ze(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Re(a)&&this.setInternal(a)},{equal:(a,s)=>Re(a)&&Re(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Wt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(ze(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Re(a)&&this.setExternal(a)},{equal:(a,s)=>Re(a)&&Re(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Wt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(ze(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(ze(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){qt(this.video);let{textTracks:e}=this.video;this.subscription.add(Rt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ms(Rt(e,"addtrack"),Rt(e,"removetrack"),fs(["init"])).pipe(Wt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),bs((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(ms(Rt(e,"change"),fs(["init"])).pipe(Wt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Wt(i=>i&&this.htmlTextTrackToITextTrack(i).id),bs()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Rt(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(Rt(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;Re(t.align)&&(r.align=t.align),Re(t.position)&&(r.position=t.position),Re(t.size)&&(r.size=t.size),Re(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){qt(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:hu(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){qt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(du(e)||!mu(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){qt(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){qt(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)}},Se=Zr;var _e=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 Ss=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ea=n=>{let e=Ss(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},vs=n=>{let e=Ss(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as ve,map as Ke,merge as Ts,filterChanged as bu,isNonNullable as Is,Subject as gu,filter as Es,mapTo as xs,combine as Su,once as vu,ErrorCategory as yu,ValueSubject as ks,clientChecker as Tu}from"@vkontakte/videoplayer-shared/evergreen";var fu=3,ys=(n,e,t=fu)=>{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 oe=n=>{let e=I=>ve(n,I).pipe(xs(void 0)),i=Ts(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>ve(n,I))).pipe(Ke(I=>I.type==="ended"?n.readyState<2:n.readyState<3),bu()),r=Ts(ve(n,"progress"),ve(n,"timeupdate")).pipe(Ke(()=>ys(n.buffered,n.currentTime))),a=Tu.isSafari?Su({play:e("play").pipe(vu()),playing:e("playing")}).pipe(xs(void 0)):e("playing"),s=ve(n,"volumechange").pipe(Ke(()=>({muted:n.muted,volume:n.volume}))),o=ve(n,"ratechange").pipe(Ke(()=>n.playbackRate)),u=ve(n,"error").pipe(Es(()=>!!(n.error||n.played.length)),Ke(()=>{let I=n.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:yu.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:n.error??void 0}})),d=ve(n,"timeupdate").pipe(Ke(()=>n.currentTime)),l=new gu,c=.3,p;d.subscribe(I=>{n.loop&&Is(p)&&Is(I)&&p>=n.duration-c&&I<=c&&l.next(p),p=I});let h=e("pause").pipe(Es(()=>!n.error&&p!==n.duration)),m=ve(n,"enterpictureinpicture"),f=ve(n,"leavepictureinpicture"),b=new ks(vs(n));m.subscribe(()=>b.next(!0)),f.subscribe(()=>b.next(!1));let v=new ks(ea(n));return ve(n,"fullscreenchange").pipe(Ke(()=>ea(n))).subscribe(v),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:ve(n,"durationchange").pipe(Ke(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:b,inFullscreen$:v}};import{VideoQuality as Je}from"@vkontakte/videoplayer-shared/evergreen";var Xe=n=>{switch(n){case"mobile":return Je.Q_144P;case"lowest":return Je.Q_240P;case"low":return Je.Q_360P;case"sd":case"medium":return Je.Q_480P;case"hd":case"high":return Je.Q_720P;case"fullhd":case"full":return Je.Q_1080P;case"quadhd":case"quad":return Je.Q_1440P;case"ultrahd":case"ultra":return Je.Q_2160P}};import{isNonNullable as W,isNullable as ia,now as Rs,isHigher as ra,isHigherOrEqual as aa,isInvariantQuality as ws,isLower as Ls,isLowerOrEqual as sa,videoSizeToQuality as Iu,assertNotEmptyArray as Ds,assertNonNullable as Eu}from"@vkontakte/videoplayer-shared/evergreen";var ta=!1,Fe={},Ps=n=>{ta=n},As=()=>{Fe={}},$s=n=>{n(Fe)},Gt=(n,e)=>{ta&&(Fe.meta=Fe.meta??{},Fe.meta[n]=e)},ee=class{constructor(e){this.name=e}next(e){if(!ta)return;Fe.series=Fe.series??{};let t=Fe.series[this.name]??[];t.push([Date.now(),e]),Fe.series[this.name]=t}};var xu=new ee("best_bitrate"),Cs=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var na=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),Yt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Rs()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Vs='Assertion "ABR Tracks is empty array" failed',or=(n,e,t,i)=>{let r=[...e].sort(na(1)),a=[...t].sort(na(1)),s=a.filter(u=>W(u.bitrate)&&W(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)},Ms=n=>"quality"in n,Bs=(n,e,t,i)=>{let r=W(i?.last?.bitrate)&&W(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Rs()-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=Ms(s)?"video":"audio",u=Ms(s)?s.quality:s.bitrate;return e({message:`
|
|
6
|
+
var Xa="2.0.118-dev.feac9bf3.0";var re=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(re||{}),Ye=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(Ye||{});var tr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(tr||{}),qr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(qr||{});var Wr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Wr||{});import{assertNever as rs,assertNonNullable as Qo,isNonNullable as ir,ValueSubject as Gr,Subject as jo,Subscription as qo,merge as Wo,observableFrom as Go,fromEvent as Za,map as es,tap as ts,filterChanged as Yo,isNullable as Yr,ErrorCategory as is}from"@vkontakte/videoplayer-shared/evergreen";var Ja=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var rr=class{constructor(e){this.connection$=new Gr(void 0);this.castState$=new Gr("NOT_AVAILABLE");this.errorEvent$=new jo;this.realCastState$=new Gr("NOT_AVAILABLE");this.subscription=new qo;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=ir(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||Ja("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:is.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(){ir(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Yr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Yr(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Za(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 rs(r.sessionState)}})).add(Wo(Za(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ts(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),es(r=>r.castState)),Go([i.getCastState()])).pipe(Yo(),es(zo),ts(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=ir(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();Qo(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Yr(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"?ir(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:is.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},zo=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 rs(n)}};import{assertNever as as}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:as(t)}return n},ar=(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:as(e)}};var y=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as Ko,Subject as sr,merge as ss}from"@vkontakte/videoplayer-shared/evergreen";var $=class{constructor(e){this.transitionStarted$=new sr;this.transitionEnded$=new sr;this.transitionUpdated$=new sr;this.forceChanged$=new sr;this.stateChangeStarted$=ss(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ss(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||Ko(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 Xo}from"@vkontakte/videoplayer-shared/evergreen";var ns=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 Xo(n)}};import{assertNever as Mt,assertNonNullable as pt,debounce as os,ErrorCategory as us,fromEvent as ht,isNonNullable as ls,map as ds,merge as cs,observableFrom as Jo,Subject as Zo,Subscription as zr,timeout as eu,getHighestQuality as tu}from"@vkontakte/videoplayer-shared/evergreen";var iu=5,ru=5,au=500,ps=7e3,jt=class{constructor(e){this.subscription=new zr;this.loadMediaTimeoutSubscription=new zr;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:Mt(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:Mt(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:Mt(e)}break}default:Mt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ns(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 zr;this.subscription.add(e),this.subscription.add(cs(this.videoState.stateChangeStarted$.pipe(ds(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(ds(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 Zo;e.add(r.pipe(os(au)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(ht(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(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ht(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<ru&&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:Mt(s)}}),t(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ht(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=cs(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Jo(["init"])).pipe(os(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];pt(l);let d=tu(Object.keys(l));pt(d);let c=l[d];pt(c),i=c,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];pt(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];pt(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];pt(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];pt(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",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:us.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Mt(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 ls(o)&&(s.metadata.title=o),ls(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(eu(ps).subscribe(()=>a(`timeout(${ps})`)))});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:us.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as ms}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as su}from"@vkontakte/videoplayer-shared/evergreen";var hs=n=>{try{n.pause(),n.playbackRate=0,su(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as nu,Subscription as ou}from"@vkontakte/videoplayer-shared/evergreen";var Kr=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)}},Xr=window.WeakMap?new WeakMap:new Kr,Jr=window.WeakMap?new WeakMap:new Map,uu=(n,e=20)=>{let t=0;return nu(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ae=(n,{audioVideoSyncRate:e})=>{let t=n.querySelector("video"),i=!!t;t?ms(t):(t=document.createElement("video"),n.appendChild(t)),Xr.set(t,i);let r=new ou;return r.add(uu(t,e)),Jr.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},se=n=>{Jr.get(n)?.unsubscribe(),Jr.delete(n);let t=Xr.get(n);Xr.delete(n),t?ms(n):hs(n)};import{assertNonNullable as qt,isNonNullable as De,isNullable as cu,fromEvent as Dt,merge as fs,observableFrom as bs,filterChanged as gs,map as Wt,Subject as Ss,Subscription as pu,ValueSubject as hu,ErrorCategory as mu}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Zr,isNullable as lu,Subscription as du}from"@vkontakte/videoplayer-shared/evergreen";var nr=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=lu(r),l=new du;return r&&l.add(r.subscribe(d=>{let c=n.getState();i(d,c)&&n.setState(d)},a)),i(o,s)||(t(s),u&&n.setState(s)),l.add(n.stateChangeStarted$.subscribe(d=>{t(d.to),u&&n.setState(d.to)},a)),l},Me=(n,e,t)=>nr(e,()=>n.loop,i=>{Zr(i)&&(n.loop=i)},{onError:t}),ne=(n,e,t,i)=>nr(e,()=>({muted:n.muted,volume:n.volume}),r=>{Zr(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}),ge=(n,e,t,i)=>nr(e,()=>n.playbackRate,r=>{Zr(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),ze=nr;var fu=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},ea=class n{constructor(){this.available$=new Ss;this.current$=new hu(void 0);this.error$=new Ss;this.subscription=new pu;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:mu.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(ze(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{De(a)&&this.setInternal(a)},{equal:(a,s)=>De(a)&&De(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Wt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(ze(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{De(a)&&this.setExternal(a)},{equal:(a,s)=>De(a)&&De(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Wt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(ze(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(ze(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){qt(this.video);let{textTracks:e}=this.video;this.subscription.add(Dt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(fs(Dt(e,"addtrack"),Dt(e,"removetrack"),bs(["init"])).pipe(Wt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),gs((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(fs(Dt(e,"change"),bs(["init"])).pipe(Wt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Wt(i=>i&&this.htmlTextTrackToITextTrack(i).id),gs()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Dt(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(Dt(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;De(t.align)&&(r.align=t.align),De(t.position)&&(r.position=t.position),De(t.size)&&(r.size=t.size),De(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){qt(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:fu(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){qt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(cu(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){qt(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){qt(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)}},Se=ea;var _e=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},ta=n=>{let e=vs(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Ts=n=>{let e=vs(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as ve,map as Ke,merge as Is,filterChanged as Su,isNonNullable as Es,Subject as vu,filter as xs,mapTo as ks,combine as Tu,once as yu,ErrorCategory as Iu,ValueSubject as Ps,clientChecker as Eu}from"@vkontakte/videoplayer-shared/evergreen";var gu=3,ys=(n,e,t=gu)=>{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 oe=n=>{let e=I=>ve(n,I).pipe(ks(void 0)),i=Is(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>ve(n,I))).pipe(Ke(I=>I.type==="ended"?n.readyState<2:n.readyState<3),Su()),r=Is(ve(n,"progress"),ve(n,"timeupdate")).pipe(Ke(()=>ys(n.buffered,n.currentTime))),a=Eu.isSafari?Tu({play:e("play").pipe(yu()),playing:e("playing")}).pipe(ks(void 0)):e("playing"),s=ve(n,"volumechange").pipe(Ke(()=>({muted:n.muted,volume:n.volume}))),o=ve(n,"ratechange").pipe(Ke(()=>n.playbackRate)),u=ve(n,"error").pipe(xs(()=>!!(n.error||n.played.length)),Ke(()=>{let I=n.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:Iu.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=ve(n,"timeupdate").pipe(Ke(()=>n.currentTime)),d=new vu,c=.3,p;l.subscribe(I=>{n.loop&&Es(p)&&Es(I)&&p>=n.duration-c&&I<=c&&d.next(p),p=I});let h=e("pause").pipe(xs(()=>!n.error&&p!==n.duration)),m=ve(n,"enterpictureinpicture"),f=ve(n,"leavepictureinpicture"),b=new Ps(Ts(n));m.subscribe(()=>b.next(!0)),f.subscribe(()=>b.next(!1));let v=new Ps(ta(n));return ve(n,"fullscreenchange").pipe(Ke(()=>ta(n))).subscribe(v),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:ve(n,"durationchange").pipe(Ke(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:b,inFullscreen$:v}};import{VideoQuality as Xe}from"@vkontakte/videoplayer-shared/evergreen";var Je=n=>{switch(n){case"mobile":return Xe.Q_144P;case"lowest":return Xe.Q_240P;case"low":return Xe.Q_360P;case"sd":case"medium":return Xe.Q_480P;case"hd":case"high":return Xe.Q_720P;case"fullhd":case"full":return Xe.Q_1080P;case"quadhd":case"quad":return Xe.Q_1440P;case"ultrahd":case"ultra":return Xe.Q_2160P}};import{isNonNullable as W,isNullable as ra,now as Rs,isHigher as aa,isHigherOrEqual as sa,isInvariantQuality as Ls,isLower as Ms,isLowerOrEqual as na,videoSizeToQuality as xu,assertNotEmptyArray as Cs,assertNonNullable as ku}from"@vkontakte/videoplayer-shared/evergreen";var ia=!1,Fe={},As=n=>{ia=n},$s=()=>{Fe={}},ws=n=>{n(Fe)},Gt=(n,e)=>{ia&&(Fe.meta=Fe.meta??{},Fe.meta[n]=e)},ee=class{constructor(e){this.name=e}next(e){if(!ia)return;Fe.series=Fe.series??{};let t=Fe.series[this.name]??[];t.push([Date.now(),e]),Fe.series[this.name]=t}};var Pu=new ee("best_bitrate"),Vs=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var oa=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),Yt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Rs()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Bs='Assertion "ABR Tracks is empty array" failed',or=(n,e,t,i)=>{let r=[...e].sort(oa(1)),a=[...t].sort(oa(1)),s=a.filter(u=>W(u.bitrate)&&W(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)},Ds=n=>"quality"in n,Os=(n,e,t,i)=>{let r=W(i?.last?.bitrate)&&W(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Rs()-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=Ds(s)?"video":"audio",u=Ds(s)?s.quality:s.bitrate;return e({message:`
|
|
7
7
|
[last ${o} selected] ${u}
|
|
8
|
-
`}),s}return i?.recordSwitch(t),t},
|
|
8
|
+
`}),s}return i?.recordSwitch(t),t},Au=(n,e)=>Math.log(e)/Math.log(n),Ze=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{Cs(n,Bs);let f=i.containerSizeFactor;if(i.usePixelRatio&&window.devicePixelRatio){let g=window.devicePixelRatio;if(i.pixelRatioMultiplier)f*=i.pixelRatioMultiplier*(g-1)+1;else{let T=i.pixelRatioLogBase,[_=0,pe=0,Ie=0]=i.pixelRatioLogCoefficients,x=Au(T,_*g+pe)+Ie;Number.isFinite(x)&&(f*=x)}}let b=i.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*f,height:e.height*f}:void 0,v=i.considerPlaybackRate&&W(o)?o:1,L=n.filter(g=>!Ls(g.quality)).sort((g,T)=>aa(g.quality,T.quality)?-1:1),I=L.at(-1)?.quality,k=L.at(0)?.quality,S=ra(r)||W(r.min)&&W(r.max)&&Ms(r.max,r.min)||W(r.min)&&k&&aa(r.min,k)||W(r.max)&&I&&Ms(r.max,I),A=v*Vs(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),C={},B=L.filter(g=>{let T=!0;if(b)if(g.size)T=g.size.width<=b.width&&g.size.height<=b.height;else{let z=b&&xu(b);T=z?na(g.quality,z):!0}if(!T)return C[g.quality]="FitsContainer",!1;let _=h||t;if(!(W(_)&&isFinite(_)&&W(g.bitrate)?_-a>=g.bitrate*A:!0))return C[g.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&W(i.minBufferToSwitchUp)&&u&&!Ls(u.quality)&&(s??0)<i.minBufferToSwitchUp&&aa(g.quality,u.quality))return C[g.quality]="Buffer",!1;if(!!c&&sa(g.quality,c))return C[g.quality]="DroppedFramesLimit",!1;if(!!p&&sa(g.quality,p))return C[g.quality]="StallsLimit",!1;let P=S||(ra(r.max)||na(g.quality,r.max))&&(ra(r.min)||sa(g.quality,r.min)),q=W(d)&&!d?na(g.quality,i.backgroundVideoQualityLimit):!0;return!P||!q?(C[g.quality]="FitsQualityLimits",!1):!0})[0];B&&B.bitrate&&Pu.next(B.bitrate);let F=B??L.at(-1)??n[0];return F.quality!==l?.last?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
11
|
${n.map(g=>`{ id: ${g.id}, quality: ${g.quality}, bitrate: ${g.bitrate} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(i??{}).map(([g,
|
|
15
|
+
${Object.entries(i??{}).map(([g,T])=>`${g}: ${T}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
@@ -32,12 +32,12 @@ var Ka="2.0.118-dev.f24234cb.0";var re=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
32
32
|
minQualityLimit: ${r?.min},
|
|
33
33
|
|
|
34
34
|
[limited video tracks]
|
|
35
|
-
${Object.entries(C).map(([g,
|
|
35
|
+
${Object.entries(C).map(([g,T])=>`${g}: ${T}`).join(`
|
|
36
36
|
`)||"All tracks are available"}
|
|
37
37
|
|
|
38
38
|
[best video track] ${B?.quality}
|
|
39
39
|
[selected video track] ${F?.quality}
|
|
40
|
-
`}),
|
|
40
|
+
`}),Os(i,m,F,l)},Ns=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:s,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Cs(t,Bs);let d=r.considerPlaybackRate&&W(a)?a:1,c=[...t].sort(oa(-1)),p=n.bitrate;ku(p);let h=d*Vs(s??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=or(n,e,t,r.minVideoAudioRatio),b=l||i;return W(b)&&isFinite(b)&&(m=c.find(v=>W(v.bitrate)&&W(f?.bitrate)?b-p>=v.bitrate*h&&v.bitrate>=f.bitrate:!1)),m||(m=f),m?.bitrate!==o?.last?.bitrate&&u({message:`
|
|
41
41
|
[AUDIO TRACKS ABR]
|
|
42
42
|
[available audio tracks]
|
|
43
43
|
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
@@ -49,23 +49,23 @@ var Ka="2.0.118-dev.f24234cb.0";var re=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
49
49
|
|
|
50
50
|
[limit params]
|
|
51
51
|
estimatedThroughput: ${i},
|
|
52
|
-
stallsPredictedThroughput: ${
|
|
52
|
+
stallsPredictedThroughput: ${l},
|
|
53
53
|
reserve: ${p},
|
|
54
54
|
playbackRate: ${a},
|
|
55
|
-
playbackRateFactor: ${
|
|
55
|
+
playbackRateFactor: ${d},
|
|
56
56
|
forwardBufferHealth: ${s},
|
|
57
57
|
bitrateFactor: ${h},
|
|
58
58
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
59
59
|
|
|
60
60
|
[selected audio track] ${m?.id}
|
|
61
|
-
`}),m&&Bs(r,u,m,o)};var G=n=>new URL(n).hostname;import{assertNever as Qs,assertNonNullable as js,combine as Wu,debounce as Gu,ErrorCategory as qs,filter as Ws,filterChanged as Yu,isNonNullable as ca,map as pr,merge as Gs,observableFrom as zu,once as Ku,Subscription as Ju,ValueSubject as pa,videoQualityToHeight as Xu,videoSizeToQuality as Zu}from"@vkontakte/videoplayer-shared/evergreen";var Ns=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"))},ue=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!Ns(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return Ns(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as dr,isNullable as $u,assertNonNullable as Jt}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as _s,assertNonNullable as ur,now as Pu}from"@vkontakte/videoplayer-shared/evergreen";function Y(){return Pu()}function oa(n){return Y()-n}function ua(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Fs(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Dt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,l,c,p=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;ur(l);let y=oa(l),_;if(y<f){_=f-y,setTimeout(b,_);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,A()},v=y=>(a=y,g),L=y=>(c=y,g),I=()=>(h="json",g),k=()=>{if(!u){if(--d>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},S=y=>(p=y,g),A=()=>{l=Y(),s=new r,s.open("get",n);let y=0,_,pe=0,Ie=()=>(ur(l),Math.max(l,Math.max(_||0,pe||0)));if(a&&s.addEventListener("progress",x=>{let M=Y();a.updateChunk&&x.loaded>y&&(a.updateChunk(Ie(),x.loaded-y),y=x.loaded,_=M)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>k())),s.addEventListener("load",()=>{if(u)return;ur(s);let x=s.status;if(x>=200&&x<300){if(s.response.byteLength&&a){let M=s.response.byteLength-y;M&&a.updateChunk&&a.updateChunk(Ie(),M)}s.responseType==="json"&&!Object.values(s.response).length?k():(c&&c(),e(s.response))}else k()}),s.addEventListener("error",()=>{k()}),p){let x=()=>{ur(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(pe=Y(),s.removeEventListener("readystatechange",x))};s.addEventListener("readystatechange",x)}return s.responseType=h,s.send(),g},g={withBitrateReporting:v,withParallel:S,withJSONResponse:I,withRetryCount:y=>(d=y,g),withRetryInterval:(y,_)=>(_s(y)&&(f=y),_s(_)&&(m=_),g),withTimeout:y=>(o=y,g),withFinally:L,send:A,abort:()=>{s&&(s.abort(),s=void 0),u=!0,c&&c()}};return g}var zt=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 Kt=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=Y(),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=Y()-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=Dt(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=Y()}_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=Y();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 wu}from"@vkontakte/videoplayer-shared/evergreen";var lr=1e4,da=3;var Lu=6e4,Mu=10,Ru=1,Du=500,Xt=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new wu,this.chunkRateEstimator=new zt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ua(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ua(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],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||dr(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=()=>{Fs(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 Kt(da,lr,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,d=null,l=!1,c=()=>{let k=a&&(!l||l===this.rep);return k||t("Not running!"),k},p=(k,S,A)=>{u&&u.abort(),u=Dt(this.urlResolver.resolve(k,!1),S,A,()=>this._retryCallback()).withTimeout(lr).withBitrateReporting(this.bitrateSwitcher).withRetryCount(da).withFinally(()=>{u=null}).send()},h=(k,S,A)=>{Jt(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),S,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=k=>{let S=i.playbackRate;i.playbackRate!==k&&(t(`Playback rate switch: ${S}=>${k}`),i.playbackRate=k)},f=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let A=Y()-1e4,C=0;for(let B=0;B<this.bufferStates.length;B++){let F=this.bufferStates[B];k=Math.min(k,F.buf),F.ts<A&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${k} drop=${C} jitter=${this.sourceJitter}`);let N=k-Ru;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?m(1.15):N>1?m(1.1):N>.3?m(1.05):m(1)}},v=k=>{let S,A=()=>S&&S.start?S.start.length:0,C=x=>S.start[x]/1e3,N=x=>S.dur[x]/1e3,B=x=>S.fragIndex+x,F=(x,M)=>({chunkIdx:B(x),startTS:C(x),dur:N(x),discontinuity:M}),g=()=>{let x=0;if(S&&S.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,P=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,q=M;this.sourceJitter>1&&(q+=this.sourceJitter-1);let z=S.dur.length-1;for(;z>=0&&(q-=S.dur[z],!(q<=0));--z);x=Math.min(z,S.dur.length-1-P),x=Math.max(x,0)}return F(x,!0)},y=x=>{let M=A();if(!(M<=0)){if(dr(x)){for(let P=0;P<M;P++)if(C(P)>x)return F(P)}return g()}},_=x=>{let M=A(),P=x?x.chunkIdx+1:0,q=P-S.fragIndex;if(!(M<=0)){if(!x||q<0||q-M>Mu)return t(`Resync: offset=${q} bChunks=${M} chunk=`+JSON.stringify(x)),g();if(!(q>=M))return F(P-S.fragIndex,!1)}},pe=(x,M,P)=>{d&&d.abort(),d=Dt(this.urlResolver.resolve(x,!0,this.lowLatency),M,P,()=>this._retryCallback()).withTimeout(lr).withRetryCount(da).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,M)=>{pe(k,P=>{if(!c())return;S=P;let q=!!S.lowLatency;q!==this.lowLatency&&f(q);let z=0;for(let qe=0;qe<S.dur.length;++qe)z+=S.dur[qe];z>0&&(Jt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/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,x(y(M))},()=>this._handleNetworkError())},nextChunk:_}},L=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),Jt(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:k=>{let{videoElement:S,logger:A}=this.params,C=v(e.jidxUrl),N,B,F,g,y=0,_,pe,Ie,x=()=>{_&&(clearTimeout(_),_=void 0);let D=Math.max(Du,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),K=y+D,j=Y(),ie=Math.min(1e4,K-j);y=j;let he=()=>{d||c()&&C.seek(()=>{c()&&(y=Y(),M(),x())})};ie>0?_=window.setTimeout(()=>{this.paused?x():he()},ie):he()},M=()=>{let D;for(;D=C.nextChunk(g);)g=D,xt(D);let K=C.nextChunk(F);if(K){if(F&&K.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?x():(L(),this._initPlayerWith(e));return}qe(K)}else x()},P=(D,K)=>{if(!c()||!this.sourceBuffer)return;let j,ie,he,Ve=Ae=>{window.setTimeout(()=>{c()&&P(D,K)},Ae)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),Ve(100);else{let Ae=Y(),Be=S.currentTime;!this.paused&&S.buffered.length>1&&pe===Be&&Ae-Ie>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),pe!==Be&&(pe=Be,Ie=Ae);let $e=this._getBufferSizeSec();if($e>30)A(`Buffered ${$e} seconds; delaying appendBuffer`),Ve(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:Ae,buf:$e}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),K&&K()}catch(kt){if(kt.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),he=this.sourceBuffer.buffered.length,he!==0&&(j=this.sourceBuffer.buffered.start(0),ie=Be,ie-j>4&&this.sourceBuffer.remove(j,ie-3)),Ve(1e3);else throw kt}}},q=()=>{B&&N&&(A([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(F)]),P(B,function(){B=null,M()}))},z=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),qe=D=>{c()&&h(z(D),(K,j)=>{if(c()){if(j/=1e3,B=K,F=D,s=D.startTS,j){let ie=Math.min(10,D.dur/j);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ie:ie}q()}},()=>this._handleNetworkError())},xt=D=>{c()&&(Jt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(D),!1)))},ut=D=>{c()&&(e.cachedHeader=D,P(D,()=>{N=!0,q()}))};a=!0,C.seek(D=>{if(c()){if(y=Y(),!D){x();return}g=D,!$u(k)||D.startTS>k?qe(D):(F=D,M())}},k),e.cachedHeader?ut(e.cachedHeader):p(e.headerUrl,ut,()=>this._handleNetworkError())},stop:L,getTimestampSec:()=>s},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),dr(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,Jt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return dr(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/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(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(p,h)=>{let m=Y();if(this.chunkRateEstimator.addInterval(p,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:b}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},s=-1/0,o,u=!0,d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&oa(s)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=a.updateChunk(c,p);return h&&d(),h},notifySwitch:c=>{let p=Y();c<o&&(s=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Dt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(lr).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;ue(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,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Lu))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Cu,filter as Us,fromEvent as Vu,interval as Bu,isHigher as Ou,isInvariantQuality as Nu,isLower as _u,merge as Fu,Subject as Hs,Subscription as Uu}from"@vkontakte/videoplayer-shared/evergreen";var la=class{constructor(){this.onDroopedVideoFramesLimit$=new Hs;this.subscription=new Uu;this.playing=!1;this.tracks=[];this.forceChecker$=new Hs;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&&!Nu(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&&Ou(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(Vu(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Bu(this.droppedFramesChecker.checkTime).pipe(Us(()=>this.playing),Us(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Cu(this.droppedFramesChecker.checkTime)),i=Fu(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])=>_u(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}},cr=la;import{map as Hu,Observable as Qu}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as ju}from"@vkontakte/videoplayer-shared/evergreen";var Zt=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var qu=(n,e)=>new Qu(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Zt()))},{...i,...e});r.observe(n);let a=ju(document,"visibilitychange").pipe(Hu(s=>!document.hidden||Zt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),ye=qu;var ed=["paused","playing","ready"],td=["paused","playing","ready"],ei=class{constructor(e){this.subscription=new Ju;this.videoState=new $("stopped");this.representations$=new pa([]);this.textTracksManager=new Se;this.droppedFramesManager=new cr;this.maxSeekBackTime$=new pa(1/0);this.zeroTime$=new pa(void 0);this.liveOffset=new _e;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:qs.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=Xe(r.name)??Zu(r.video),o=r.bitrate/1e3,u={...r.video};if(!s)continue;let d={id:a,quality:s,bitrate:o,size:u};i.push({track:d,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),ca(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(td.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&ed.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 Qs(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:qs.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Gs(this.videoState.stateChangeStarted$.pipe(pr(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(pr(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ae(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(G(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=oe(this.video);this.subscription.add(this.representations$.pipe(pr(r=>r.map(({track:a})=>a)),Ws(r=>!!r.length),Ku()).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(Yu(),pr(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Wu({zeroTime:this.zeroTime$.pipe(Ws(ca)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Me(this.video,this.params.desiredState.isLooped,t)).add(ne(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ge(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(ye(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Xu(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).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 Qs(r.to)}},t)).add(Gs(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zu(["init"])).pipe(Gu(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),se(this.video)}createLiveDashPlayer(){let e=new Xt({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&&ca(t)?t:Ze(e.map(({track:d})=>d),{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 d=e.find(({track:l})=>l.id===a)?.representation;js(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;js(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 Ys=ei;var De=(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 il,assertNonNullable as rl,debounce as al,ErrorCategory as Ca,filter as Qn,filterChanged as Bi,fromEvent as sl,isNonNullable as jn,map as Va,merge as wr,observableFrom as nl,observeElementSize as ol,once as qn,Subscription as ul,ValueSubject as dl}from"@vkontakte/videoplayer-shared/evergreen";var Ue=()=>window.ManagedMediaSource||window.MediaSource,hr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),zs=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ks=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as gr,clientChecker as fr}from"@vkontakte/videoplayer-shared/evergreen";var br=document.createElement("video"),ad='video/mp4; codecs="avc1.42000a,mp4a.40.2"',sd='video/mp4; codecs="hev1.1.6.L93.B0"',Js='video/webm; codecs="vp09.00.10.08"',Xs='video/webm; codecs="av01.0.00M.08"',nd='audio/mp4; codecs="mp4a.40.2"',od='audio/webm; codecs="opus"',ti={mms:hr(),mse:zs(),hls:!!(br.canPlayType?.("application/x-mpegurl")||br.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},de={mp4:!!br.canPlayType?.("video/mp4"),webm:!!br.canPlayType?.("video/webm"),cmaf:!0},le={h264:!!Ue()?.isTypeSupported?.(ad),h265:!!Ue()?.isTypeSupported?.(sd),vp9:!!Ue()?.isTypeSupported?.(Js),av1:!!Ue()?.isTypeSupported?.(Xs),aac:!!Ue()?.isTypeSupported?.(nd),opus:!!Ue()?.isTypeSupported?.(od)},Ct=(le.h264||le.h265)&&le.aac,mt,ud=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:Xs}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Js}})]);mt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{ud()}catch(n){console.error(n)}var Vt=ti.hls&&de.mp4,Zs=()=>Object.keys(le).filter(n=>le[n]),en=(n,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let r=ti.mse&&(!i||!!window.MediaStreamTrack)||ti.mms&&t;return n.filter(a=>{switch(a){case"DASH_SEP":return r&&de.mp4&&Ct;case"DASH_WEBM":return r&&de.webm&&le.vp9&&le.opus;case"DASH_WEBM_AV1":return r&&de.webm&&le.av1&&le.opus;case"DASH_STREAMS":return r&&(de.mp4&&Ct||de.webm&&(le.vp9||le.av1)&&(le.opus||le.aac));case"DASH_LIVE":return r&&de.mp4&&Ct;case"DASH_LIVE_CMAF":return r&&de.mp4&&Ct&&de.cmaf;case"DASH_ONDEMAND":return r&&de.mp4&&Ct;case"HLS":case"HLS_ONDEMAND":return Vt||e&&r&&de.mp4&&Ct;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Vt;case"MPEG":return de.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ti.webrtc&&ti.ws&&le.h264&&(de.mp4||de.webm);default:return gr(a)}})},mr=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 mt?mt[t].smooth?[t,e]:mt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return mt?mt[t].powerEfficient?[t,e]:mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:gr(n)}return[e,t]},tn=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...mr(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(fr.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",...mr(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mr(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mr(n),...r,"HLS","HLS_ONDEMAND"];default:gr(e)}return Vt?[...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=fr.isMac&&fr.isSafari;if(fr.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:gr(n)}else Vt&&!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"]},ha=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],an=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 ii}from"@vkontakte/videoplayer-shared/evergreen";var sn=n=>{if(!n)return{id:"EmptyResponse",category:ii.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:ii.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:ii.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:ii.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ii.PARSER,message:"Response is valid XML, but parser failed"}};var et=(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 La,assertNonNullable as yt,clientChecker as Ud,combine as Ri,ErrorCategory as at,filter as xr,filterChanged as Ma,flattenObject as Di,fromEvent as Tt,getTraceSubscriptionMethod as Hd,interval as Ra,isNonNullable as Cn,map as Ci,merge as It,now as Qd,Subject as Vn,Subscription as Bn,tap as jd,throttle as qd,ValueSubject as Q}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as dd,ErrorCategory as nn,clientChecker as ma,Subject as on}from"@vkontakte/videoplayer-shared/evergreen";var ld=18,un=!1;try{un=ma.isSafari&&!!ma.macVersion&&ma.macVersion<=ld}catch(n){console.error(n)}var fa=class{constructor(e){this.bufferFull$=new on;this.error$=new on;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:nn.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;un&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:nn.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:dd(t)}}},dn=fa;var ba=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 gt,assertNonNullable as te,ErrorCategory as it,fromEvent as ka,getExponentialDelay as Pa,isNonNullable as Sr,isNullable as Te,now as vr,once as Md,Subject as Rd,Subscription as Dd,ValueSubject as Ot}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Bt=class extends O{};var ri=class extends O{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 ai=class extends O{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 si=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var H=class extends O{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ni=class extends H{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 oi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var ft=class extends H{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,d=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:s,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}};var di=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var li=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends H{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 pi=class extends H{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var hi=class extends H{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var mi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends H{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 bi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends H{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var vi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends H{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 Ti=class extends H{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 Ii=class extends H{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 pd={ftyp:ai,moov:si,mvhd:ni,moof:oi,mdat:ui,sidx:ft,trak:di,mdia:mi,mfhd:Si,tkhd:fi,traf:vi,tfhd:yi,tfdt:Ti,trun:Ii,minf:bi,sv3d:li,st3d:ci,prhd:pi,proj:gi,equi:hi,uuid:ri,unknown:Bt},He=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=pd[e];return i?new i(t,new n):new Bt(t,new n)}};var tt=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 md=new TextDecoder("ascii"),fd=n=>md.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",bd=n=>{let e=new ft(n,new He),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})},gd=(n,e)=>{let i=new He().parse(n),r=new tt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,c)},Sd=n=>{let t=new He().parse(n),i=new tt(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},vd=n=>{let t=new He().parse(n);return new tt(t).find("sidx")?.timescale},yd=(n,e)=>{let i=new He().parse(n),a=new tt(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,p)=>c+p,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},Td=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 He().parse(n),r=new tt(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},ln={validateData:fd,parseInit:Td,getIndexRange:()=>{},parseSegments:bd,parseFeedableSegmentChunk:gd,getChunkEndTime:yd,getServerLatencyTimestamps:Sd,getTimescaleFromIndex:vd};import{assertNonNullable as Sa,isNonNullable as mn,isNullable as Ed}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Id}from"@vkontakte/videoplayer-shared/evergreen";var cn={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"}},pn=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=Ei(n,t),r=i in cn,a=r?cn[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,l=Ei(u),c=d*2**((o-1)*8)+l,p=t+o,h;return p+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Ei=(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},ke=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return Ei(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:Id(e)}},bt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=pn(i);if(!e(r))return;r.type==="master"&&bt(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=pn(n);return bt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=ke(o,s):a===17026?t=ke(o,s):a===17029&&(i=ke(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var fn=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],xd=[231,22612,22743,167,171,163,160,175],kd=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,l=!1,c=0;return bt(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let b=ke(m,h);d=Ei(b)}else p!==21420&&(d=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=ke(m,h):p===17545?r=ke(m,h):p===21420&&d===475249515?u=ke(m,h):p===374648427?bt(m,({tag:b,type:v,value:L})=>b===30321?(l=ke(L,v)===1,!1):!0):a&&s&&fn.includes(p)&&(o=!0),!o}),Sa(e,"Failed to parse webm Segment start"),Sa(t,"Failed to parse webm Segment end"),Sa(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:l,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Pd=n=>{if(Ed(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ad=(n,e)=>{let t=!1,i=!1,r=o=>mn(o.time)&&mn(o.position),a=[],s;return bt(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=ke(d,u));break;case 183:break;case 241:s&&(s.position=ke(d,u));break;default:t&&fn.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:l}=o,c=a[u+1];return{status:"none",time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},$d=n=>{let e=0,t=!1;try{bt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):xd.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},bn={validateData:hn,parseInit:kd,getIndexRange:Pd,parseSegments:Ad,parseFeedableSegmentChunk:$d};var xi=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return bn;case"mp4":return ln}}throw new ReferenceError(`Unsupported mime type ${n}`)};var va=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 vn,isNullable as yn}from"@vkontakte/videoplayer-shared/evergreen";var gn=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Sn=n=>{try{let e=wd(),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 wd(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",l=`^(?:(?<langtag>${`
|
|
61
|
+
`}),m&&Os(r,u,m,o)};var G=n=>new URL(n).hostname;import{assertNever as js,assertNonNullable as qs,combine as Yu,debounce as zu,ErrorCategory as Ws,filter as Gs,filterChanged as Ku,isNonNullable as pa,map as pr,merge as Ys,observableFrom as Xu,once as Ju,Subscription as Zu,ValueSubject as ha,videoQualityToHeight as el,videoSizeToQuality as tl}from"@vkontakte/videoplayer-shared/evergreen";var _s=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"))},ue=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!_s(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return _s(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as lr,isNullable as Lu,assertNonNullable as Xt}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Fs,assertNonNullable as ur,now as $u}from"@vkontakte/videoplayer-shared/evergreen";function Y(){return $u()}function ua(n){return Y()-n}function la(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 Us(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Rt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;ur(d);let T=ua(d),_;if(T<f){_=f-T,setTimeout(b,_);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,A()},v=T=>(a=T,g),L=T=>(c=T,g),I=()=>(h="json",g),k=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},S=T=>(p=T,g),A=()=>{d=Y(),s=new r,s.open("get",n);let T=0,_,pe=0,Ie=()=>(ur(d),Math.max(d,Math.max(_||0,pe||0)));if(a&&s.addEventListener("progress",x=>{let M=Y();a.updateChunk&&x.loaded>T&&(a.updateChunk(Ie(),x.loaded-T),T=x.loaded,_=M)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>k())),s.addEventListener("load",()=>{if(u)return;ur(s);let x=s.status;if(x>=200&&x<300){if(s.response.byteLength&&a){let M=s.response.byteLength-T;M&&a.updateChunk&&a.updateChunk(Ie(),M)}s.responseType==="json"&&!Object.values(s.response).length?k():(c&&c(),e(s.response))}else k()}),s.addEventListener("error",()=>{k()}),p){let x=()=>{ur(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(pe=Y(),s.removeEventListener("readystatechange",x))};s.addEventListener("readystatechange",x)}return s.responseType=h,s.send(),g},g={withBitrateReporting:v,withParallel:S,withJSONResponse:I,withRetryCount:T=>(l=T,g),withRetryInterval:(T,_)=>(Fs(T)&&(f=T),Fs(_)&&(m=_),g),withTimeout:T=>(o=T,g),withFinally:L,send:A,abort:()=>{s&&(s.abort(),s=void 0),u=!0,c&&c()}};return g}var zt=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 Kt=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=Y(),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=Y()-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=Rt(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=Y()}_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=Y();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 Mu}from"@vkontakte/videoplayer-shared/evergreen";var dr=1e4,da=3;var Du=6e4,Ru=10,Cu=1,Vu=500,Jt=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Mu,this.chunkRateEstimator=new zt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=la(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=la(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],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||lr(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=()=>{Us(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 Kt(da,dr,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,d=!1,c=()=>{let k=a&&(!d||d===this.rep);return k||t("Not running!"),k},p=(k,S,A)=>{u&&u.abort(),u=Rt(this.urlResolver.resolve(k,!1),S,A,()=>this._retryCallback()).withTimeout(dr).withBitrateReporting(this.bitrateSwitcher).withRetryCount(da).withFinally(()=>{u=null}).send()},h=(k,S,A)=>{Xt(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),S,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=k=>{let S=i.playbackRate;i.playbackRate!==k&&(t(`Playback rate switch: ${S}=>${k}`),i.playbackRate=k)},f=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let A=Y()-1e4,C=0;for(let B=0;B<this.bufferStates.length;B++){let F=this.bufferStates[B];k=Math.min(k,F.buf),F.ts<A&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${k} drop=${C} jitter=${this.sourceJitter}`);let N=k-Cu;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?m(1.15):N>1?m(1.1):N>.3?m(1.05):m(1)}},v=k=>{let S,A=()=>S&&S.start?S.start.length:0,C=x=>S.start[x]/1e3,N=x=>S.dur[x]/1e3,B=x=>S.fragIndex+x,F=(x,M)=>({chunkIdx:B(x),startTS:C(x),dur:N(x),discontinuity:M}),g=()=>{let x=0;if(S&&S.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,P=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,q=M;this.sourceJitter>1&&(q+=this.sourceJitter-1);let z=S.dur.length-1;for(;z>=0&&(q-=S.dur[z],!(q<=0));--z);x=Math.min(z,S.dur.length-1-P),x=Math.max(x,0)}return F(x,!0)},T=x=>{let M=A();if(!(M<=0)){if(lr(x)){for(let P=0;P<M;P++)if(C(P)>x)return F(P)}return g()}},_=x=>{let M=A(),P=x?x.chunkIdx+1:0,q=P-S.fragIndex;if(!(M<=0)){if(!x||q<0||q-M>Ru)return t(`Resync: offset=${q} bChunks=${M} chunk=`+JSON.stringify(x)),g();if(!(q>=M))return F(P-S.fragIndex,!1)}},pe=(x,M,P)=>{l&&l.abort(),l=Rt(this.urlResolver.resolve(x,!0,this.lowLatency),M,P,()=>this._retryCallback()).withTimeout(dr).withRetryCount(da).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,M)=>{pe(k,P=>{if(!c())return;S=P;let q=!!S.lowLatency;q!==this.lowLatency&&f(q);let z=0;for(let qe=0;qe<S.dur.length;++qe)z+=S.dur[qe];z>0&&(Xt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/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,x(T(M))},()=>this._handleNetworkError())},nextChunk:_}},L=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Xt(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:k=>{let{videoElement:S,logger:A}=this.params,C=v(e.jidxUrl),N,B,F,g,T=0,_,pe,Ie,x=()=>{_&&(clearTimeout(_),_=void 0);let R=Math.max(Vu,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),K=T+R,j=Y(),ie=Math.min(1e4,K-j);T=j;let he=()=>{l||c()&&C.seek(()=>{c()&&(T=Y(),M(),x())})};ie>0?_=window.setTimeout(()=>{this.paused?x():he()},ie):he()},M=()=>{let R;for(;R=C.nextChunk(g);)g=R,xt(R);let K=C.nextChunk(F);if(K){if(F&&K.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?x():(L(),this._initPlayerWith(e));return}qe(K)}else x()},P=(R,K)=>{if(!c()||!this.sourceBuffer)return;let j,ie,he,Ve=Ae=>{window.setTimeout(()=>{c()&&P(R,K)},Ae)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),Ve(100);else{let Ae=Y(),Be=S.currentTime;!this.paused&&S.buffered.length>1&&pe===Be&&Ae-Ie>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),pe!==Be&&(pe=Be,Ie=Ae);let $e=this._getBufferSizeSec();if($e>30)A(`Buffered ${$e} seconds; delaying appendBuffer`),Ve(2e3);else try{this.sourceBuffer.appendBuffer(R),this.videoPlayStarted?(this.bufferStates.push({ts:Ae,buf:$e}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),K&&K()}catch(kt){if(kt.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),he=this.sourceBuffer.buffered.length,he!==0&&(j=this.sourceBuffer.buffered.start(0),ie=Be,ie-j>4&&this.sourceBuffer.remove(j,ie-3)),Ve(1e3);else throw kt}}},q=()=>{B&&N&&(A([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(F)]),P(B,function(){B=null,M()}))},z=R=>e.fragUrlTemplate.replace("%%id%%",R.chunkIdx),qe=R=>{c()&&h(z(R),(K,j)=>{if(c()){if(j/=1e3,B=K,F=R,s=R.startTS,j){let ie=Math.min(10,R.dur/j);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ie:ie}q()}},()=>this._handleNetworkError())},xt=R=>{c()&&(Xt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(R),!1)))},ut=R=>{c()&&(e.cachedHeader=R,P(R,()=>{N=!0,q()}))};a=!0,C.seek(R=>{if(c()){if(T=Y(),!R){x();return}g=R,!Lu(k)||R.startTS>k?qe(R):(F=R,M())}},k),e.cachedHeader?ut(e.cachedHeader):p(e.headerUrl,ut,()=>this._handleNetworkError())},stop:L,getTimestampSec:()=>s},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),lr(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,Xt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return lr(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/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(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(p,h)=>{let m=Y();if(this.chunkRateEstimator.addInterval(p,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:b}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},s=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&ua(s)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=a.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=Y();c<o&&(s=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Rt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(dr).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;ue(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))},Du))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Bu,filter as Hs,fromEvent as Ou,interval as Nu,isHigher as _u,isInvariantQuality as Fu,isLower as Uu,merge as Hu,Subject as Qs,Subscription as Qu}from"@vkontakte/videoplayer-shared/evergreen";var ca=class{constructor(){this.onDroopedVideoFramesLimit$=new Qs;this.subscription=new Qu;this.playing=!1;this.tracks=[];this.forceChecker$=new Qs;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&&!Fu(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&&_u(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(Ou(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Nu(this.droppedFramesChecker.checkTime).pipe(Hs(()=>this.playing),Hs(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Bu(this.droppedFramesChecker.checkTime)),i=Hu(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])=>Uu(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}},cr=ca;import{map as ju,Observable as qu}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as Wu}from"@vkontakte/videoplayer-shared/evergreen";var Zt=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Gu=(n,e)=>new qu(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Zt()))},{...i,...e});r.observe(n);let a=Wu(document,"visibilitychange").pipe(ju(s=>!document.hidden||Zt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),Te=Gu;var il=["paused","playing","ready"],rl=["paused","playing","ready"],ei=class{constructor(e){this.subscription=new Zu;this.videoState=new $("stopped");this.representations$=new ha([]);this.textTracksManager=new Se;this.droppedFramesManager=new cr;this.maxSeekBackTime$=new ha(1/0);this.zeroTime$=new ha(void 0);this.liveOffset=new _e;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:Ws.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=Je(r.name)??tl(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(rl.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&il.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 js(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ws.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Ys(this.videoState.stateChangeStarted$.pipe(pr(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(pr(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ae(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(G(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=oe(this.video);this.subscription.add(this.representations$.pipe(pr(r=>r.map(({track:a})=>a)),Gs(r=>!!r.length),Ju()).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(Ku(),pr(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Yu({zeroTime:this.zeroTime$.pipe(Gs(pa)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Me(this.video,this.params.desiredState.isLooped,t)).add(ne(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ge(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(Te(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&el(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).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 js(r.to)}},t)).add(Ys(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Xu(["init"])).pipe(zu(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),se(this.video)}createLiveDashPlayer(){let e=new Jt({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:Ze(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:d})=>d.id===a)?.representation;qs(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;qs(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 zs=ei;var Re=(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 ad,assertNonNullable as sd,debounce as nd,ErrorCategory as Va,filter as jn,filterChanged as Bi,fromEvent as od,isNonNullable as qn,map as Ba,merge as wr,observableFrom as ud,observeElementSize as ld,once as Wn,Subscription as dd,ValueSubject as cd}from"@vkontakte/videoplayer-shared/evergreen";var Ue=()=>window.ManagedMediaSource||window.MediaSource,hr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Ks=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Xs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as gr,clientChecker as fr}from"@vkontakte/videoplayer-shared/evergreen";var br=document.createElement("video"),nl='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ol='video/mp4; codecs="hev1.1.6.L93.B0"',Js='video/webm; codecs="vp09.00.10.08"',Zs='video/webm; codecs="av01.0.00M.08"',ul='audio/mp4; codecs="mp4a.40.2"',ll='audio/webm; codecs="opus"',ti={mms:hr(),mse:Ks(),hls:!!(br.canPlayType?.("application/x-mpegurl")||br.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},le={mp4:!!br.canPlayType?.("video/mp4"),webm:!!br.canPlayType?.("video/webm"),cmaf:!0},de={h264:!!Ue()?.isTypeSupported?.(nl),h265:!!Ue()?.isTypeSupported?.(ol),vp9:!!Ue()?.isTypeSupported?.(Js),av1:!!Ue()?.isTypeSupported?.(Zs),aac:!!Ue()?.isTypeSupported?.(ul),opus:!!Ue()?.isTypeSupported?.(ll)},Ct=(de.h264||de.h265)&&de.aac,mt,dl=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:Zs}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Js}})]);mt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{dl()}catch(n){console.error(n)}var Vt=ti.hls&&le.mp4,en=()=>Object.keys(de).filter(n=>de[n]),tn=(n,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let r=ti.mse&&(!i||!!window.MediaStreamTrack)||ti.mms&&t;return n.filter(a=>{switch(a){case"DASH_SEP":return r&&le.mp4&&Ct;case"DASH_WEBM":return r&&le.webm&&de.vp9&&de.opus;case"DASH_WEBM_AV1":return r&&le.webm&&de.av1&&de.opus;case"DASH_STREAMS":return r&&(le.mp4&&Ct||le.webm&&(de.vp9||de.av1)&&(de.opus||de.aac));case"DASH_LIVE":return r&&le.mp4&&Ct;case"DASH_LIVE_CMAF":return r&&le.mp4&&Ct&&le.cmaf;case"DASH_ONDEMAND":return r&&le.mp4&&Ct;case"HLS":case"HLS_ONDEMAND":return Vt||e&&r&&le.mp4&&Ct;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Vt;case"MPEG":return le.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ti.webrtc&&ti.ws&&de.h264&&(le.mp4||le.webm);default:return gr(a)}})},mr=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 mt?mt[t].smooth?[t,e]:mt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return mt?mt[t].powerEfficient?[t,e]:mt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:gr(n)}return[e,t]},rn=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...mr(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(fr.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",...mr(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mr(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mr(n),...r,"HLS","HLS_ONDEMAND"];default:gr(e)}return Vt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},an=({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=fr.isMac&&fr.isSafari;if(fr.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:gr(n)}else Vt&&!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"]},ma=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],sn=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 ii}from"@vkontakte/videoplayer-shared/evergreen";var nn=n=>{if(!n)return{id:"EmptyResponse",category:ii.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:ii.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:ii.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:ii.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ii.PARSER,message:"Response is valid XML, but parser failed"}};var et=(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 Ma,assertNonNullable as Tt,clientChecker as Ql,combine as Di,ErrorCategory as at,filter as xr,filterChanged as Da,flattenObject as Ri,fromEvent as yt,getTraceSubscriptionMethod as jl,interval as Ra,isNonNullable as Vn,map as Ci,merge as It,now as ql,Subject as Bn,Subscription as On,tap as Wl,throttle as Gl,ValueSubject as Q}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as cl,ErrorCategory as on,clientChecker as fa,Subject as un}from"@vkontakte/videoplayer-shared/evergreen";var pl=18,ln=!1;try{ln=fa.isSafari&&!!fa.macVersion&&fa.macVersion<=pl}catch(n){console.error(n)}var ba=class{constructor(e){this.bufferFull$=new un;this.error$=new un;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:on.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;ln&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:on.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:cl(t)}}},dn=ba;var ga=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 gt,assertNonNullable as te,ErrorCategory as it,fromEvent as Pa,getExponentialDelay as Aa,isNonNullable as Sr,isNullable as ye,now as vr,once as Rl,Subject as Cl,Subscription as Vl,ValueSubject as Ot}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Bt=class extends O{};var ri=class extends O{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 ai=class extends O{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 si=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var H=class extends O{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ni=class extends H{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 oi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var ft=class extends H{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 li=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends H{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 pi=class extends H{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var hi=class extends H{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var mi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends H{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 bi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends H{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var vi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends H{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 yi=class extends H{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 Ii=class extends H{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 ml={ftyp:ai,moov:si,mvhd:ni,moof:oi,mdat:ui,sidx:ft,trak:li,mdia:mi,mfhd:Si,tkhd:fi,traf:vi,tfhd:Ti,tfdt:yi,trun:Ii,minf:bi,sv3d:di,st3d:ci,prhd:pi,proj:gi,equi:hi,uuid:ri,unknown:Bt},He=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=ml[e];return i?new i(t,new n):new Bt(t,new n)}};var tt=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 bl=new TextDecoder("ascii"),gl=n=>bl.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Sl=n=>{let e=new ft(n,new He),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})},vl=(n,e)=>{let i=new He().parse(n),r=new tt(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,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,c)},Tl=n=>{let t=new He().parse(n),i=new tt(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},yl=n=>{let t=new He().parse(n);return new tt(t).find("sidx")?.timescale},Il=(n,e)=>{let i=new He().parse(n),a=new tt(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},El=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 He().parse(n),r=new tt(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},cn={validateData:gl,parseInit:El,getIndexRange:()=>{},parseSegments:Sl,parseFeedableSegmentChunk:vl,getChunkEndTime:Il,getServerLatencyTimestamps:Tl,getTimescaleFromIndex:yl};import{assertNonNullable as va,isNonNullable as fn,isNullable as kl}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as xl}from"@vkontakte/videoplayer-shared/evergreen";var pn={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},hn=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=Ei(n,t),r=i in pn,a=r?pn[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,d=Ei(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Ei=(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},ke=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return Ei(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:xl(e)}},bt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=hn(i);if(!e(r))return;r.type==="master"&&bt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},mn=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=hn(n);return bt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=ke(o,s):a===17026?t=ke(o,s):a===17029&&(i=ke(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],Pl=[231,22612,22743,167,171,163,160,175],Al=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,l,d=!1,c=0;return bt(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let b=ke(m,h);l=Ei(b)}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=ke(m,h):p===17545?r=ke(m,h):p===21420&&l===475249515?u=ke(m,h):p===374648427?bt(m,({tag:b,type:v,value:L})=>b===30321?(d=ke(L,v)===1,!1):!0):a&&s&&bn.includes(p)&&(o=!0),!o}),va(e,"Failed to parse webm Segment start"),va(t,"Failed to parse webm Segment end"),va(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},$l=n=>{if(kl(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},wl=(n,e)=>{let t=!1,i=!1,r=o=>fn(o.time)&&fn(o.position),a=[],s;return bt(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=ke(l,u));break;case 183:break;case 241:s&&(s.position=ke(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:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Ll=n=>{let e=0,t=!1;try{bt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Pl.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},gn={validateData:mn,parseInit:Al,getIndexRange:$l,parseSegments:wl,parseFeedableSegmentChunk:Ll};var xi=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return gn;case"mp4":return cn}}throw new ReferenceError(`Unsupported mime type ${n}`)};var Ta=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 Tn,isNullable as yn}from"@vkontakte/videoplayer-shared/evergreen";var Sn=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var vn=n=>{try{let e=Ml(),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 Ml(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
62
62
|
(?<language>${`(?:[a-z]{2,3}(?:-${n})?|[a-z]{4}|[a-z]{5,8})`})
|
|
63
63
|
(-(?<script>[a-z]{4}))?
|
|
64
64
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
65
65
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
66
66
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
67
67
|
(?:-(?<privateuse>(?:${e})))?
|
|
68
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(l,"i")}var Tn=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},Qe=(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)=>yn(a)?o:yn(u)?a:a.padStart(parseInt(u,10),"0"))}return t},In=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(S=>S.textContent?.trim()??""),u=o.at(0)??"",d=s.children,l=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,h,m=a.getAttribute("mediaPresentationDuration"),f=s.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=Tn(m);else if(f){let S=Tn(f);vn(S)&&(h=S)}else v&&(h=parseInt(v,10));let L=0,I=a.getAttribute("profiles")?.split(",")??[];for(let S of d){let A=S.getAttribute("id")??"id"+(L++).toString(10),C=S.getAttribute("mimeType")??"",N=S.getAttribute("codecs")??"",B=S.getAttribute("contentType")??C?.split("/")[0],F=S.getAttribute("profiles")?.split(",")??[],g=Sn(S.getAttribute("lang")??"")??{},y=S.querySelector("Label")?.textContent?.trim()??void 0,_=S.querySelectorAll("Representation"),pe=S.querySelector("SegmentTemplate"),Ie=S.querySelector("Role")?.getAttribute("value")??void 0,x=B,M={id:A,language:g.language,isDefault:Ie==="main",label:y,codecs:N,hdr:x==="video"&&va(N),mime:C,representations:[]};for(let P of _){let q=P.getAttribute("lang")??void 0,z=P.getAttribute("label")??void 0,qe=P.querySelector("BaseURL")?.textContent?.trim()??"",xt=new URL(qe||u,e).toString(),ut=P.getAttribute("mimeType")??C,D=P.getAttribute("codecs")??N??"",K;if(B==="text"){let j=P.getAttribute("id")||"",ie=g.privateuse?.includes("x-auto")||j.includes("_auto"),he=P.querySelector("SegmentTemplate");if(he){let Ve={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},Ae=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,Be=parseInt(he.getAttribute("startNumber")??"",10)??1,$e=parseInt(he.getAttribute("timescale")??"",10),kt=he.querySelectorAll("SegmentTimeline S")??[],Pt=he.getAttribute("media");if(!Pt)continue;let zi=[],Ki=0,Ji="",At=0,Ut=Be,Z=0;for(let Ee of kt){let dt=parseInt(Ee.getAttribute("d")??"",10),be=parseInt(Ee.getAttribute("r")??"",10)||0,We=parseInt(Ee.getAttribute("t")??"",10);Z=Number.isFinite(We)?We:Z;let lt=dt/$e*1e3,$t=Z/$e*1e3;for(let we=0;we<be+1;we++){let Ge=Qe(Pt,{...Ve,segmentNumber:Ut.toString(10),segmentTime:(Z+we*dt).toString(10)}),wt=($t??0)+we*lt,Qt=wt+lt;Ut++,zi.push({time:{from:wt,to:Qt},url:Ge})}Z+=(be+1)*dt,Ki+=(be+1)*lt}At=Z/$e*1e3,Ji=Qe(Pt,{...Ve,segmentNumber:Ut.toString(10),segmentTime:Z.toString(10)});let Ht={time:{from:At,to:1/0},url:Ji},Oe={type:"template",baseUrl:xt,segmentTemplateUrl:Pt,initUrl:"",totalSegmentsDurationMs:Ki,segments:zi,nextSegmentBeyondManifest:Ht,timescale:$e};K={id:j,kind:"text",segmentReference:Oe,profiles:[],duration:h,bitrate:Ae,mime:"",codecs:"",width:0,height:0,isAuto:ie}}else K={id:j,isAuto:ie,kind:"text",url:xt}}else{let j=P.getAttribute("contentType")??ut?.split("/")[0]??B,ie=S.getAttribute("profiles")?.split(",")??[],he=parseInt(P.getAttribute("width")??"",10),Ve=parseInt(P.getAttribute("height")??"",10),Ae=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,Be=P.getAttribute("frameRate")??"",$e=P.getAttribute("quality")??void 0,kt=Be?gn(Be):void 0,Pt=P.getAttribute("id")??"id"+(L++).toString(10),zi=j==="video"?`${Ve}p`:j==="audio"?`${Ae}Kbps`:D,Ki=`${Pt}@${zi}`,Ji=[...I,...F,...ie],At,Ut=P.querySelector("SegmentBase"),Z=P.querySelector("SegmentTemplate")??pe;if(Ut){let Oe=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ee,dt]=Oe.split("-").map(Ge=>parseInt(Ge,10)),be={from:Ee,to:dt},We=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[lt,$t]=We?We.split("-").map(Ge=>parseInt(Ge,10)):[],we=We?{from:lt,to:$t}:void 0;At={type:"byteRange",url:xt,initRange:be,indexRange:we}}else if(Z){let Oe={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},Ee=parseInt(Z.getAttribute("timescale")??"",10),dt=Z.getAttribute("initialization")??"",be=Z.getAttribute("media"),We=parseInt(Z.getAttribute("startNumber")??"",10)??1,lt=Qe(dt,Oe);if(!be)throw new ReferenceError("No media attribute in SegmentTemplate");let $t=Z.querySelectorAll("SegmentTimeline S")??[],we=[],Ge=0,wt="",Qt=0;if($t.length){let Xi=We,xe=0;for(let Lt of $t){let Le=parseInt(Lt.getAttribute("d")??"",10),ct=parseInt(Lt.getAttribute("r")??"",10)||0,Zi=parseInt(Lt.getAttribute("t")??"",10);xe=Number.isFinite(Zi)?Zi:xe;let Qr=Le/Ee*1e3,No=xe/Ee*1e3;for(let er=0;er<ct+1;er++){let _o=Qe(be,{...Oe,segmentNumber:Xi.toString(10),segmentTime:(xe+er*Le).toString(10)}),za=(No??0)+er*Qr,Fo=za+Qr;Xi++,we.push({time:{from:za,to:Fo},url:_o})}xe+=(ct+1)*Le,Ge+=(ct+1)*Qr}Qt=xe/Ee*1e3,wt=Qe(be,{...Oe,segmentNumber:Xi.toString(10),segmentTime:xe.toString(10)})}else if(vn(h)){let xe=parseInt(Z.getAttribute("duration")??"",10)/Ee*1e3,Lt=Math.ceil(h/xe),Le=0;for(let ct=1;ct<Lt;ct++){let Zi=Qe(be,{...Oe,segmentNumber:ct.toString(10),segmentTime:Le.toString(10)});we.push({time:{from:Le,to:Le+xe},url:Zi}),Le+=xe}Qt=Le,wt=Qe(be,{...Oe,segmentNumber:Lt.toString(10),segmentTime:Le.toString(10)})}let Oo={time:{from:Qt,to:1/0},url:wt};At={type:"template",baseUrl:xt,segmentTemplateUrl:be,initUrl:lt,totalSegmentsDurationMs:Ge,segments:we,nextSegmentBeyondManifest:Oo,timescale:Ee}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!ut)continue;let Ht={video:"video",audio:"audio",text:"text"}[j];if(!Ht)continue;x||=Ht,K={id:Ki,kind:Ht,segmentReference:At,profiles:Ji,duration:h,bitrate:Ae,mime:ut,codecs:D,width:he,height:Ve,fps:kt,quality:$e}}M.language||=q,M.label||=z,M.mime||=ut,M.codecs||=D,M.hdr||=x==="video"&&va(D),M.representations.push(K)}x&&r[x].push(M)}return{dynamic:l,liveAvailabilityStartTime:p,duration:h,streams:r,baseUrls:o}};import{videoSizeToQuality as Ld}from"@vkontakte/videoplayer-shared/evergreen";var En=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:s})=>{let o=(a?Xe(a):void 0)??Ld({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:s}},xn=({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}),Pn=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Ia=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Ea=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),xa=n=>"url"in n,me=n=>n.type==="template",ki=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Pi=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:d}){this.currentLiveSegmentServerLatency$=new Ot(0);this.currentSegmentLength$=new Ot(0);this.onLastSegment$=new Ot(!1);this.fullyBuffered$=new Ot(!1);this.playingRepresentation$=new Ot(void 0);this.playingRepresentationInit$=new Ot(void 0);this.error$=new Rd;this.gaps=[];this.subscription=new Dd;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=gt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);te(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new dn(this.sourceBuffer),this.subscription.add(ka(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:it.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:it.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(ka(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:it.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,ba(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let d=De(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,s*2,d<l)})),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);te(i,"No init buffer for starting representation"),te(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.switchToOld=gt(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);te(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Te(a)||Te(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),te(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();Sr(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=gt(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 d=t.find(p=>p.id===u);d&&this.representations.set(u,d);let l=this.representations.get(u);if(!l||!me(l.segmentReference))return;let c=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);te(r);let a=this.segments.get(i);te(a,"No segments for starting representation");let s=this.initData.get(i);if(te(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!d?.dynamic,this.baseUrls=d?.baseUrls??[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);te(a,`No such representation ${i}`);let s=this.segments.get(i),o=this.initData.get(i);if(Te(o)||Te(s)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),s=this.segments.get(i),te(s,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(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();Sr(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))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Te(e)||Te(this.downloadingRepresentationId)||Te(this.playingRepresentationId)||Te(this.sourceBuffer)||Sr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(te(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=De(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&ba(this.sourceBuffer.buffered)>=this.bufferLimit){let d=De(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let l=o.at(0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&De(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;Sr(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.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)??[];for(let i of t){if(!i||!me(i.segmentReference))return;let r=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),a=this.segments.get(i.id)??[],s=a.at(-1)?.time.to??0,o=r?.findIndex(u=>Math.floor(s)>=Math.floor(u.time.from)&&Math.floor(s)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=r.slice(o+1);this.segments.set(i.id,[...a,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;te(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!me(i))return;let r=this.segments.get(t.id)??[],a=r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to),!!!r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),u=Qe(i.segmentTemplateUrl,{segmentTime:o});r.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}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){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.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:c,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,b=p>i||f||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),L=this.preloadOnly&&p<=i+v||h<=i+v;return(c==="none"||c==="partially_ejected"&&b&&L&&this.sourceBuffer&&!(et(this.sourceBuffer.buffered,p)&&et(this.sourceBuffer.buffered,h)))&&b&&L});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=d||o<=l);c++){let p=a[c];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){me(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:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await gt(o,async function*(){let l=Pa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vr(),!l)return;let c=new DataView(l),p=xi(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,f)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),ki(l)||(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())me(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 gt(s,async function*(){let u=Pa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),ka(window,"online").pipe(Md()).subscribe(()=>{d(),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=vr(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ki(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(me(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=vr(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:it.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!me(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=vr();let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:it.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}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 d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=xi(s.mime).parseFeedableSegmentChunk(d,this.isLive);l?.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.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:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let l=d.byte.from-i,c=d.byte.to-i,p=c-l+1,h=l<r,m=c<=r;if(!h)continue;let f=xi(o.mime);if(d.status==="downloading"&&m){d.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?b:f.parseFeedableSegmentChunk(b);v?.byteLength&&(d.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):s())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(te(this.sourceBuffer),et(this.sourceBuffer.buffered,e.segment.time.from,100)&&et(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:it.VIDEO_PIPELINE,message:"Safari 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",xa(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");te(this.sourceBuffer),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?gt(this.destroyAbortController.signal,async function*(){let o=Pa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,xi(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let p=l;this.isLive&&me(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:it.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||!this.playingRepresentationId||Te(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((l,c)=>l.from-c.from);let d=[u[0]];for(let l=1;l<u.length;l++){let{from:c,to:p}=u[l],h=d[d.length-1];h.to>=c?h.to=Math.max(h.to,p):d.push(u[l])}return d},o=u=>{if(a>=t)return r;r.push({...u.time}),r=s(r);let d=xa(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&d.status==="fed"&&o(d)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:d,to:l},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+u&&l.status==="fed"&&o(l)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||l,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||Te(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){te(this.sourceBuffer);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:it.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Te(this.sourceBuffer)||Te(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(l=>l.from-t<=s&&l.to+t>=o),d=e.filter(l=>s>=l.from&&s<l.to-t||o>l.from+t&&o<=l.to);u||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var Ai=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var An=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 $i,assertNever as wn,fromEvent as Ln,merge as Cd,now as wi,Subscription as Vd,ValueSubject as Aa,flattenObject as Nt}from"@vkontakte/videoplayer-shared/evergreen";var $n=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var yr=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Aa(void 0);this.lastConnectionReused$=new Aa(void 0);this.lastRequestFirstBytes$=new Aa(void 0);this.abortAllController=new AbortController;this.subscription=new Vd;this.fetchManifest=$i(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ai(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=$n(i));let r=yield fetch(i,{signal:this.abortAllController.signal}).catch(Li);return r?(t.log("success",Nt({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Nt({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=$i(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 d=e,l=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let g=new URL(d,location.href);g.searchParams.append("bytes",`${i.from}-${i.to}`),d=g.toString();break}default:wn(t)}this.requestQuic&&(d=Ai(d));let p=this.abortAllController.signal,h;if(s){let g=new AbortController;if(h=Cd(Ln(this.abortAllController.signal,"abort"),Ln(s,"abort")).subscribe(()=>{try{g.abort()}catch(y){Li(y)}}),this.abortAllController.signal.aborted||s.aborted)try{g.abort()}catch(y){Li(y)}p=g.signal}let m=wi();c.log("startRequest",Nt({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield fetch(d,{priority:a,headers:l,signal:p}).catch(Li),b=wi();if(!f)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){h?.unsubscribe();let g=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:g}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let g=wi(),y={requestStartedAt:m,requestEndedAt:g,duration:g-m};return c.log("endRequest",Nt(y)),c.end(),f.arrayBuffer()}let[v,L]=f.body.tee(),I=v.getReader();o&&this.throughputEstimator?.trackStream(L,u);let k=0,S=new Uint8Array(0),A=!1,C=g=>{h?.unsubscribe(),A=!0,Li(g)},N=$i(p,async function*({done:g,value:y}){if(k===0&&this.lastRequestFirstBytes$.next(wi()-m),p.aborted){h?.unsubscribe();return}if(!g&&y){let _=new Uint8Array(S.length+y.length);_.set(S),_.set(y,S.length),S=_,k+=y.byteLength,r?.(new DataView(S.buffer),k),yield I?.read().then(N,C)}}.bind(this));yield I?.read().then(N,C),h?.unsubscribe();let B=wi(),F={failed:A,requestStartedAt:m,requestEndedAt:B,duration:B-m};return A?(c.error("endRequest",Nt(F)),c.end(),null):(c.log("endRequest",Nt(F)),c.end(),S.buffer)}.bind(this));this.fetchByteRangeRepresentation=$i(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,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(l,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-s,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!v)return null;f=new DataView(v)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=$i(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}=An(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:wn(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Li=n=>{if(!ki(n))throw n};var St=(n,e,t)=>t*e+(1-t)*n,$a=(n,e)=>n.reduce((t,i)=>t+i,0)/e,Mn=(n,e,t,i)=>{let r=0,a=t,s=$a(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 Bd,ValueSubject as Rn}from"@vkontakte/videoplayer-shared/evergreen";var rt=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 Rn(e.initial),this.debounced$=new Rn(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ee(`raw_${t}`),this.smoothedSeries$=new ee(`smoothed_${t}`),this.reportedSeries$=new ee(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let 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)&&(Bd(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 Tr=class extends rt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=St(this.slow,e,this.params.emaAlphaSlow),this.fast=St(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ir=class extends rt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=$a(this.pastMeasures,this.takenMeasures);this.emaSmoothed=St(this.emaSmoothed,e,this.params.emaAlpha);let i=Mn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Er=class extends rt{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?St(this.smoothed,t,this.params.emaAlpha):t}};var vt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Tr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ir({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 Er({initial:e,label:"liveEdgeDelay",...t})}};var wa=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as Od,ValueSubject as Nd}from"@vkontakte/videoplayer-shared/evergreen";var Mi=class n{constructor(e,t){this.currentRepresentation$=new Nd(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(!Od(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(d=>d.time.from<=e&&d.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&&me(t.segmentReference))}};var Wd=["timeupdate","progress","play","seeked","stalled","waiting"],Gd=["timeupdate","progress","loadeddata","playing","seeked"];var kr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Bn;this.representationSubscription=new Bn;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 Vn;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.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.isLowLatency$=new Q(!1);this.isActiveLowLatency$=new Q(!1);this.currentStallDuration$=new Q(0);this.videoLastDataObtainedTimestamp$=new Q(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Vn;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=La(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:at.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=La(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:at.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t=null;try{t=In(e??"",this.manifestUrlString)}catch(s){let o=sn(e)??{id:"ManifestParsing",category:at.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)&&Ue()?.isTypeSupported?.(`${o}; codecs="${u}"`)||s==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let u=t.streams[s].filter(({mime:c,codecs:p})=>i(s,c,p)),d=new Set(u.map(({codecs:c})=>c)),l=an(d);if(l&&(r[s]=u.filter(({codecs:c})=>c.startsWith(l))),s==="video"){let c=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);Ud.isHDR&&c&&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",Di(a)),a}.bind(this));this.initRepresentations=La(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Di({initialVideo:e,initialAudio:t,sourceHls:i})),yt(this.manifest),yt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Tt(p,"error").pipe(xr(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:at.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Ks():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&hr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Pi("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],Cn(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Pi("audio",this.source,p,s),this.bufferManagers.push(this.audioBufferManager)}Mi.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Mi(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(Ra(1e3).subscribe(p=>{if(this.element?.paused){let h=ar(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,h+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(It(...Gd.map(p=>Tt(this.element,p))).pipe(Ci(p=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),Ma(),jd(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(It(Tt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ma()).subscribe(h=>wa(this.element,1))),this.representationSubscription.add(Ri({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(xr(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(Ri({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(xr(({isLive:h})=>h),Ci(h=>({...h})),Ma((h,m)=>m.bufferLength<h.bufferLength),Ci(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=ar(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ri({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,L=h-f,I=1;Math.abs(L)>b&&(I=1+Math.sign(L)*v),wa(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Ri({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(qd(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(yt(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=ar(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,L=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,S=isFinite(h)?h:m,A=this.isActiveLowLatency$.getValue(),C=v<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(A&&C);let N="none";if(A?N="active_low_latency":this.isLowLatency$.getValue()&&C?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),N="active_low_latency"):b!==0&&S<L?N="live_forward_buffering":S<L+k&&(N="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),N==="live_forward_buffering"||N==="live_with_target_offset"){let B=p-(L+I),F=this.normolizeLiveOffset(Math.trunc(b+B/f)),g=Math.abs(F-b),y;!h||g<=this.tuning.dashCmafLive.offsetCalculationError?y=b:F>0&&g>this.tuning.dashCmafLive.offsetCalculationError?y=F:y=0,this.manifestUrlString=J(this.manifestUrlString,y,2)}N!=="none"&&N!=="active_low_latency"&&(p=0,this.updateLive())}))}let d=It(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ci(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=It(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ci(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(It(this.forceEnded$,Ri({allBuffersFull:d,someBufferEnded:l}).pipe(xr(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:at.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(It(...this.bufferManagers.map(p=>p.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(p=>this.source?.addEventListener("sourceopen",p)));let c=[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),me(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Cn(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=Ra(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:at.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 yr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=vt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){yt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=J(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(){yt(this.element),this.state$.setState("running"),this.subscription.add(It(...Wd.map(e=>Tt(this.element,e)),Tt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:at.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Tt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Tt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&et(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=Qd(),a=100,s=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(s);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,l=u<a&&r-s>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&d<a&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((l||c)&&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),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",Di(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Ra(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:at.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){yt(this.element),yt(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),et(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Di({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}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=Hd(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}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={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let o of s.gaps)s.playingRepresentation$.getValue()===o.representation&&o.from-a<=i&&o.to+a>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():(this.element.currentTime=s/1e3,t={...t,gapEnds:r,jumpTo:s,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Di(t)))}}};var Pr=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ar=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 On=`attribute vec2 a_vertex;
|
|
68
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var In=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},Qe=(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)=>yn(a)?o:yn(u)?a:a.padStart(parseInt(u,10),"0"))}return t},En=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(S=>S.textContent?.trim()??""),u=o.at(0)??"",l=s.children,d=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,h,m=a.getAttribute("mediaPresentationDuration"),f=s.getAttribute("duration"),v=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=In(m);else if(f){let S=In(f);Tn(S)&&(h=S)}else v&&(h=parseInt(v,10));let L=0,I=a.getAttribute("profiles")?.split(",")??[];for(let S of l){let A=S.getAttribute("id")??"id"+(L++).toString(10),C=S.getAttribute("mimeType")??"",N=S.getAttribute("codecs")??"",B=S.getAttribute("contentType")??C?.split("/")[0],F=S.getAttribute("profiles")?.split(",")??[],g=vn(S.getAttribute("lang")??"")??{},T=S.querySelector("Label")?.textContent?.trim()??void 0,_=S.querySelectorAll("Representation"),pe=S.querySelector("SegmentTemplate"),Ie=S.querySelector("Role")?.getAttribute("value")??void 0,x=B,M={id:A,language:g.language,isDefault:Ie==="main",label:T,codecs:N,hdr:x==="video"&&Ta(N),mime:C,representations:[]};for(let P of _){let q=P.getAttribute("lang")??void 0,z=P.getAttribute("label")??void 0,qe=P.querySelector("BaseURL")?.textContent?.trim()??"",xt=new URL(qe||u,e).toString(),ut=P.getAttribute("mimeType")??C,R=P.getAttribute("codecs")??N??"",K;if(B==="text"){let j=P.getAttribute("id")||"",ie=g.privateuse?.includes("x-auto")||j.includes("_auto"),he=P.querySelector("SegmentTemplate");if(he){let Ve={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},Ae=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,Be=parseInt(he.getAttribute("startNumber")??"",10)??1,$e=parseInt(he.getAttribute("timescale")??"",10),kt=he.querySelectorAll("SegmentTimeline S")??[],Pt=he.getAttribute("media");if(!Pt)continue;let zi=[],Ki=0,Xi="",At=0,Ut=Be,Z=0;for(let Ee of kt){let lt=parseInt(Ee.getAttribute("d")??"",10),be=parseInt(Ee.getAttribute("r")??"",10)||0,We=parseInt(Ee.getAttribute("t")??"",10);Z=Number.isFinite(We)?We:Z;let dt=lt/$e*1e3,$t=Z/$e*1e3;for(let we=0;we<be+1;we++){let Ge=Qe(Pt,{...Ve,segmentNumber:Ut.toString(10),segmentTime:(Z+we*lt).toString(10)}),wt=($t??0)+we*dt,Qt=wt+dt;Ut++,zi.push({time:{from:wt,to:Qt},url:Ge})}Z+=(be+1)*lt,Ki+=(be+1)*dt}At=Z/$e*1e3,Xi=Qe(Pt,{...Ve,segmentNumber:Ut.toString(10),segmentTime:Z.toString(10)});let Ht={time:{from:At,to:1/0},url:Xi},Oe={type:"template",baseUrl:xt,segmentTemplateUrl:Pt,initUrl:"",totalSegmentsDurationMs:Ki,segments:zi,nextSegmentBeyondManifest:Ht,timescale:$e};K={id:j,kind:"text",segmentReference:Oe,profiles:[],duration:h,bitrate:Ae,mime:"",codecs:"",width:0,height:0,isAuto:ie}}else K={id:j,isAuto:ie,kind:"text",url:xt}}else{let j=P.getAttribute("contentType")??ut?.split("/")[0]??B,ie=S.getAttribute("profiles")?.split(",")??[],he=parseInt(P.getAttribute("width")??"",10),Ve=parseInt(P.getAttribute("height")??"",10),Ae=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,Be=P.getAttribute("frameRate")??"",$e=P.getAttribute("quality")??void 0,kt=Be?Sn(Be):void 0,Pt=P.getAttribute("id")??"id"+(L++).toString(10),zi=j==="video"?`${Ve}p`:j==="audio"?`${Ae}Kbps`:R,Ki=`${Pt}@${zi}`,Xi=[...I,...F,...ie],At,Ut=P.querySelector("SegmentBase"),Z=P.querySelector("SegmentTemplate")??pe;if(Ut){let Oe=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ee,lt]=Oe.split("-").map(Ge=>parseInt(Ge,10)),be={from:Ee,to:lt},We=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[dt,$t]=We?We.split("-").map(Ge=>parseInt(Ge,10)):[],we=We?{from:dt,to:$t}:void 0;At={type:"byteRange",url:xt,initRange:be,indexRange:we}}else if(Z){let Oe={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},Ee=parseInt(Z.getAttribute("timescale")??"",10),lt=Z.getAttribute("initialization")??"",be=Z.getAttribute("media"),We=parseInt(Z.getAttribute("startNumber")??"",10)??1,dt=Qe(lt,Oe);if(!be)throw new ReferenceError("No media attribute in SegmentTemplate");let $t=Z.querySelectorAll("SegmentTimeline S")??[],we=[],Ge=0,wt="",Qt=0;if($t.length){let Ji=We,xe=0;for(let Lt of $t){let Le=parseInt(Lt.getAttribute("d")??"",10),ct=parseInt(Lt.getAttribute("r")??"",10)||0,Zi=parseInt(Lt.getAttribute("t")??"",10);xe=Number.isFinite(Zi)?Zi:xe;let jr=Le/Ee*1e3,Fo=xe/Ee*1e3;for(let er=0;er<ct+1;er++){let Uo=Qe(be,{...Oe,segmentNumber:Ji.toString(10),segmentTime:(xe+er*Le).toString(10)}),Ka=(Fo??0)+er*jr,Ho=Ka+jr;Ji++,we.push({time:{from:Ka,to:Ho},url:Uo})}xe+=(ct+1)*Le,Ge+=(ct+1)*jr}Qt=xe/Ee*1e3,wt=Qe(be,{...Oe,segmentNumber:Ji.toString(10),segmentTime:xe.toString(10)})}else if(Tn(h)){let xe=parseInt(Z.getAttribute("duration")??"",10)/Ee*1e3,Lt=Math.ceil(h/xe),Le=0;for(let ct=1;ct<Lt;ct++){let Zi=Qe(be,{...Oe,segmentNumber:ct.toString(10),segmentTime:Le.toString(10)});we.push({time:{from:Le,to:Le+xe},url:Zi}),Le+=xe}Qt=Le,wt=Qe(be,{...Oe,segmentNumber:Lt.toString(10),segmentTime:Le.toString(10)})}let _o={time:{from:Qt,to:1/0},url:wt};At={type:"template",baseUrl:xt,segmentTemplateUrl:be,initUrl:dt,totalSegmentsDurationMs:Ge,segments:we,nextSegmentBeyondManifest:_o,timescale:Ee}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!j||!ut)continue;let Ht={video:"video",audio:"audio",text:"text"}[j];if(!Ht)continue;x||=Ht,K={id:Ki,kind:Ht,segmentReference:At,profiles:Xi,duration:h,bitrate:Ae,mime:ut,codecs:R,width:he,height:Ve,fps:kt,quality:$e}}M.language||=q,M.label||=z,M.mime||=ut,M.codecs||=R,M.hdr||=x==="video"&&Ta(R),M.representations.push(K)}x&&r[x].push(M)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:r,baseUrls:o}};import{videoSizeToQuality as Dl}from"@vkontakte/videoplayer-shared/evergreen";var xn=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:s})=>{let o=(a?Je(a):void 0)??Dl({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:s}},kn=({id:n,bitrate:e})=>({id:n,bitrate:e}),Pn=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),An=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Ea=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),xa=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),ka=n=>"url"in n,me=n=>n.type==="template",ki=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Pi=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ot(0);this.currentSegmentLength$=new Ot(0);this.onLastSegment$=new Ot(!1);this.fullyBuffered$=new Ot(!1);this.playingRepresentation$=new Ot(void 0);this.playingRepresentationInit$=new Ot(void 0);this.error$=new Cl;this.gaps=[];this.subscription=new Vl;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=gt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);te(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new dn(this.sourceBuffer),this.subscription.add(Pa(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:it.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:it.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(Pa(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:it.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,ga(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Re(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,s*2,l<d)})),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);te(i,"No init buffer for starting representation"),te(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.switchToOld=gt(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);te(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ye(a)||ye(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),te(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();Sr(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=gt(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 d=this.representations.get(u);if(!d||!me(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);te(r);let a=this.segments.get(i);te(a,"No segments for starting representation");let s=this.initData.get(i);if(te(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);te(a,`No such representation ${i}`);let s=this.segments.get(i),o=this.initData.get(i);if(ye(o)||ye(s)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),s=this.segments.get(i),te(s,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(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();Sr(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))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ye(e)||ye(this.downloadingRepresentationId)||ye(this.playingRepresentationId)||ye(this.sourceBuffer)||Sr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(te(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Re(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&ga(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Re(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);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 d=o.at(0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Re(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;Sr(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.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)??[];for(let i of t){if(!i||!me(i.segmentReference))return;let r=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),a=this.segments.get(i.id)??[],s=a.at(-1)?.time.to??0,o=r?.findIndex(u=>Math.floor(s)>=Math.floor(u.time.from)&&Math.floor(s)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=r.slice(o+1);this.segments.set(i.id,[...a,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;te(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!me(i))return;let r=this.segments.get(t.id)??[],a=r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to),!!!r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),u=Qe(i.segmentTemplateUrl,{segmentTime:o});r.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}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){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.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:c,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,b=p>i||f||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),L=this.preloadOnly&&p<=i+v||h<=i+v;return(c==="none"||c==="partially_ejected"&&b&&L&&this.sourceBuffer&&!(et(this.sourceBuffer.buffered,p)&&et(this.sourceBuffer.buffered,h)))&&b&&L});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,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=l||o<=d);c++){let p=a[c];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){me(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 gt(o,async function*(){let d=Aa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vr(),!d)return;let c=new DataView(d),p=xi(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ki(d)||(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())me(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 gt(s,async function*(){let u=Aa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Pa(window,"online").pipe(Rl()).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=vr(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ki(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(me(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=vr(),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:it.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!me(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,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=vr();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:it.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}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),d=xi(s.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.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){s();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,m=c<=r;if(!h)continue;let f=xi(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?b:f.parseFeedableSegmentChunk(b);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,a)&&!a.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):s())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(te(this.sourceBuffer),et(this.sourceBuffer.buffered,e.segment.time.from,100)&&et(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:it.VIDEO_PIPELINE,message:"Safari 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",ka(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");te(this.sourceBuffer),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?gt(this.destroyAbortController.signal,async function*(){let o=Aa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,xi(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&me(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:it.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||!this.playingRepresentationId||ye(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=s(r);let l=ka(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 d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=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(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},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 d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||ye(e)?0:Re(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){te(this.sourceBuffer);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:it.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ye(this.sourceBuffer)||ye(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(d=>d.from-t<=s&&d.to+t>=o),l=e.filter(d=>s>=d.from&&s<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var Ai=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var $n=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 $i,assertNever as Ln,fromEvent as Mn,merge as Bl,now as wi,Subscription as Ol,ValueSubject as $a,flattenObject as Nt}from"@vkontakte/videoplayer-shared/evergreen";var wn=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Tr=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new $a(void 0);this.lastConnectionReused$=new $a(void 0);this.lastRequestFirstBytes$=new $a(void 0);this.abortAllController=new AbortController;this.subscription=new Ol;this.fetchManifest=$i(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ai(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=wn(i));let r=yield fetch(i,{signal:this.abortAllController.signal}).catch(Li);return r?(t.log("success",Nt({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Nt({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=$i(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,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let g=new URL(l,location.href);g.searchParams.append("bytes",`${i.from}-${i.to}`),l=g.toString();break}default:Ln(t)}this.requestQuic&&(l=Ai(l));let p=this.abortAllController.signal,h;if(s){let g=new AbortController;if(h=Bl(Mn(this.abortAllController.signal,"abort"),Mn(s,"abort")).subscribe(()=>{try{g.abort()}catch(T){Li(T)}}),this.abortAllController.signal.aborted||s.aborted)try{g.abort()}catch(T){Li(T)}p=g.signal}let m=wi();c.log("startRequest",Nt({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield fetch(l,{priority:a,headers:d,signal:p}).catch(Li),b=wi();if(!f)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){h?.unsubscribe();let g=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:g}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let g=wi(),T={requestStartedAt:m,requestEndedAt:g,duration:g-m};return c.log("endRequest",Nt(T)),c.end(),f.arrayBuffer()}let[v,L]=f.body.tee(),I=v.getReader();o&&this.throughputEstimator?.trackStream(L,u);let k=0,S=new Uint8Array(0),A=!1,C=g=>{h?.unsubscribe(),A=!0,Li(g)},N=$i(p,async function*({done:g,value:T}){if(k===0&&this.lastRequestFirstBytes$.next(wi()-m),p.aborted){h?.unsubscribe();return}if(!g&&T){let _=new Uint8Array(S.length+T.length);_.set(S),_.set(T,S.length),S=_,k+=T.byteLength,r?.(new DataView(S.buffer),k),yield I?.read().then(N,C)}}.bind(this));yield I?.read().then(N,C),h?.unsubscribe();let B=wi(),F={failed:A,requestStartedAt:m,requestEndedAt:B,duration:B-m};return A?(c.error("endRequest",Nt(F)),c.end(),null):(c.log("endRequest",Nt(F)),c.end(),S.buffer)}.bind(this));this.fetchByteRangeRepresentation=$i(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,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(s=Math.min(l,r),o=Math.max(d,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-s,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!v)return null;f=new DataView(v)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=$i(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}=$n(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:Ln(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Li=n=>{if(!ki(n))throw n};var St=(n,e,t)=>t*e+(1-t)*n,wa=(n,e)=>n.reduce((t,i)=>t+i,0)/e,Dn=(n,e,t,i)=>{let r=0,a=t,s=wa(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 Nl,ValueSubject as Rn}from"@vkontakte/videoplayer-shared/evergreen";var rt=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 Rn(e.initial),this.debounced$=new Rn(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ee(`raw_${t}`),this.smoothedSeries$=new ee(`smoothed_${t}`),this.reportedSeries$=new ee(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let 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)&&(Nl(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 yr=class extends rt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=St(this.slow,e,this.params.emaAlphaSlow),this.fast=St(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ir=class extends rt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=wa(this.pastMeasures,this.takenMeasures);this.emaSmoothed=St(this.emaSmoothed,e,this.params.emaAlpha);let i=Dn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Er=class extends rt{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?St(this.smoothed,t,this.params.emaAlpha):t}};var vt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new yr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ir({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 Er({initial:e,label:"liveEdgeDelay",...t})}};var La=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as _l,ValueSubject as Fl}from"@vkontakte/videoplayer-shared/evergreen";var Mi=class n{constructor(e,t){this.currentRepresentation$=new Fl(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(!_l(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&&me(t.segmentReference))}};var Yl=["timeupdate","progress","play","seeked","stalled","waiting"],zl=["timeupdate","progress","loadeddata","playing","seeked"];var kr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new On;this.representationSubscription=new On;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 Bn;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.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.isLowLatency$=new Q(!1);this.isActiveLowLatency$=new Q(!1);this.currentStallDuration$=new Q(0);this.videoLastDataObtainedTimestamp$=new Q(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Bn;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Ma(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:at.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ma(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:at.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t=null;try{t=En(e??"",this.manifestUrlString)}catch(s){let o=nn(e)??{id:"ManifestParsing",category:at.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)&&Ue()?.isTypeSupported?.(`${o}; codecs="${u}"`)||s==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let u=t.streams[s].filter(({mime:c,codecs:p})=>i(s,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=sn(l);if(d&&(r[s]=u.filter(({codecs:c})=>c.startsWith(d))),s==="video"){let c=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);Ql.isHDR&&c&&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",Ri(a)),a}.bind(this));this.initRepresentations=Ma(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ri({initialVideo:e,initialAudio:t,sourceHls:i})),Tt(this.manifest),Tt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(yt(p,"error").pipe(xr(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:at.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Xs():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&hr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Pi("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],Vn(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Pi("audio",this.source,p,s),this.bufferManagers.push(this.audioBufferManager)}Mi.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Mi(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(Ra(1e3).subscribe(p=>{if(this.element?.paused){let h=ar(this.manifestUrlString,2);this.manifestUrlString=X(this.manifestUrlString,h+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(It(...zl.map(p=>yt(this.element,p))).pipe(Ci(p=>this.element?Re(this.element.buffered,this.element.currentTime*1e3):0),Da(),Wl(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(It(yt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Da()).subscribe(h=>La(this.element,1))),this.representationSubscription.add(Di({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(xr(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(Di({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(xr(({isLive:h})=>h),Ci(h=>({...h})),Da((h,m)=>m.bufferLength<h.bufferLength),Ci(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=ar(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Di({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,L=h-f,I=1;Math.abs(L)>b&&(I=1+Math.sign(L)*v),La(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Di({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Gl(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(Tt(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=ar(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,L=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,S=isFinite(h)?h:m,A=this.isActiveLowLatency$.getValue(),C=v<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(A&&C);let N="none";if(A?N="active_low_latency":this.isLowLatency$.getValue()&&C?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),N="active_low_latency"):b!==0&&S<L?N="live_forward_buffering":S<L+k&&(N="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),N==="live_forward_buffering"||N==="live_with_target_offset"){let B=p-(L+I),F=this.normolizeLiveOffset(Math.trunc(b+B/f)),g=Math.abs(F-b),T;!h||g<=this.tuning.dashCmafLive.offsetCalculationError?T=b:F>0&&g>this.tuning.dashCmafLive.offsetCalculationError?T=F:T=0,this.manifestUrlString=X(this.manifestUrlString,T,2)}N!=="none"&&N!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=It(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ci(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=It(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ci(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(It(this.forceEnded$,Di({allBuffersFull:l,someBufferEnded:d}).pipe(xr(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:at.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(It(...this.bufferManagers.map(p=>p.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(p=>this.source?.addEventListener("sourceopen",p)));let c=[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),me(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Vn(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=Ra(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:at.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 Tr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=vt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Tt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&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(){Tt(this.element),this.state$.setState("running"),this.subscription.add(It(...Yl.map(e=>yt(this.element,e)),yt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:at.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(yt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(yt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&et(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=ql(),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,d=u<a&&r-s>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<a&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&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),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",Ri(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Ra(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:at.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){Tt(this.element),Tt(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),et(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ri({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}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=jl(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}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={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let o of s.gaps)s.playingRepresentation$.getValue()===o.representation&&o.from-a<=i&&o.to+a>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():(this.element.currentTime=s/1e3,t={...t,gapEnds:r,jumpTo:s,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ri(t)))}}};var Pr=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ar=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 Nn=`attribute vec2 a_vertex;
|
|
69
69
|
attribute vec2 a_texel;
|
|
70
70
|
|
|
71
71
|
varying vec2 v_texel;
|
|
@@ -76,7 +76,7 @@ void main(void) {
|
|
|
76
76
|
// save texel vector to pass to fragment shader
|
|
77
77
|
v_texel = a_texel;
|
|
78
78
|
}
|
|
79
|
-
`;var
|
|
79
|
+
`;var _n=`#ifdef GL_ES
|
|
80
80
|
precision highp float;
|
|
81
81
|
precision highp int;
|
|
82
82
|
#else
|
|
@@ -119,5 +119,6 @@ void main(void) {
|
|
|
119
119
|
// sample using new coordinates
|
|
120
120
|
gl_FragColor = texture2D(u_texture, tc);
|
|
121
121
|
}
|
|
122
|
-
`;var $r=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 Pr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ar(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();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(On,this.gl.VERTEX_SHADER),i=this.createShader(Nn,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,p=t+r;return[a,s,o,u,d,l,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as Kd,now as _n,Subscription as Jd,filter as Xd,combine as Fn,ValueSubject as Un,isNonNullable as Zd}from"@vkontakte/videoplayer-shared/evergreen";var Da=class{constructor(){this.isSeeked$=new Un(!1);this.isBuffering$=new Un(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Jd}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(Fn({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(Xd(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Fn({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:i})=>{if(Kd(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:r,stallDurationNoDataBeforeQualityDecrease:a,stallCountBeforeQualityDecrease:s,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),d=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=_n(),p=s&&this.currentStallsCount>=s,h=r&&!i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+u&&t>=r,m=a&&c-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&c-l>=a+u&&t>=a;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,Zd(this.lastUniqueVideoTrackSelected.bitrate)&&d>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=_n(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Hn=Da;var Et=class{constructor(e){this.subscription=new ul;this.videoState=new $("stopped");this.elementSize$=new dl(void 0);this.textTracksManager=new Se;this.droppedFramesManager=new cr;this.stallsManager=new Hn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yt;this.audioTrackSwitchHistory=new Yt;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.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return il(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new $r(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ae(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(G(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 kr({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=oe(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Ca.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(Qn(l=>!!l.length),qn()).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(Va(l=>l.to.state!=="none"),Bi());this.stallsManager.connect({isSeeked$:s,currentStallDuration$:this.player.currentStallDuration$.pipe(Bi()),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.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Qn(jn),qn()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(Va(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Me(this.video,t.isLooped,r)),this.subscription.add(ne(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ge(this.video,t.playbackRate,i.playbackRateState$,r)),a(ol(this.video),this.elementSize$),a(ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(rl(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of c.audio){h.push(Ia(m));let f=[];for(let b of m.representations){let v=xn(b);f.push(v),this.audioTracksMap.set(v,{stream:m,representation:b})}this.audioStreamsMap.set(m,f)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of c.video){p.push(Ea(h));let m=[];for(let f of h.representations){let b=En({...f,streamId:h.id});b&&(m.push(b),this.videoTracksMap.set(b,{stream:h,representation:f}))}this.videoStreamsMap.set(h,m)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of c.text)for(let m of h.representations){let f=kn(h,m);this.textTracksMap.set(f,{stream:h,representation:m})}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));let o=l=>e.error$.next({id:"RepresentationSwitch",category:Ca.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(wr(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,sl(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,f=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===h.id);jn(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,v).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Bi()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=c,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ea(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Bi()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=c,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Ia(h))},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 u=t.playbackState.stateChangeStarted$.pipe(Va(({to:l})=>l==="ready"),Bi());this.subscription.add(wr(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(wr(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=wr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nl(["init"])).pipe(al(0));this.subscription.add(d.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 d=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let c=De(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),f=[...this.audioStreamsMap.keys()].find(({id:A})=>A===m?.id)??this.audioStreamsMap.keys().next().value,b=0;if(f){if(s&&!i){let A=or(s,l,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);b=Math.max(b,A?.bitrate??-1/0)}if(o){let A=or(o,l,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);b=Math.max(b,A?.bitrate??-1/0)}}let v=Ze(l,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:h,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}),L=i?v??s:s??v,I=f&&Os(L,l,this.audioStreamsMap.get(f)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=this.videoTracksMap.get(L)?.representation,S=I&&this.audioTracksMap.get(I)?.representation;if(k&&S)return[k,S];if(k&&!S&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ca.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),this.textTracksManager?.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),se(this.video),this.tracer.end()}};var Oi=class extends Et{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 Wn,interval as ll,map as Gn}from"@vkontakte/videoplayer-shared/evergreen";var Ni=class extends Et{constructor(e){super(e),this.liveOffset=new _e,this.textTracksManager=null}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(Gn(a=>a.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Wn({interval:ll(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(Wn({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Gn(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=Pn(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 _i,assertNonNullable as Yn,debounce as cl,ErrorCategory as Lr,filter as pl,isNonNullable as hl,isNullable as ml,map as Mr,merge as fl,Observable as bl,observableFrom as gl,Subscription as Sl,videoSizeToQuality as vl}from"@vkontakte/videoplayer-shared/evergreen";var Pe={};var _t=(n,e)=>new bl(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Fi=class{constructor(e){this.subscription=new Sl;this.videoState=new $("initializing");this.textTracksManager=new Se;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:_i(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:_i(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:_i(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:_i(e)}break;default:_i(t)}};this.video=ae(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(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),se(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Lr.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||(Pe.Hls=r.default,Pe.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){Yn(Pe.Hls,"hls.js not loaded"),this.hls=new Pe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Yn(Pe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:Lr.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=oe(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.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(Me(this.video,e.isLooped,i)),this.subscription.add(ne(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ge(this.video,e.playbackRate,r.playbackRateState$,i)),a(ye(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Mr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(_t(this.hls,Pe.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:Lr.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(_t(this.hls,Pe.Events.MANIFEST_PARSED).pipe(Mr(({levels:d})=>d.reduce((l,c)=>{let p=c.name||c.height.toString(10),{width:h,height:m}=c,f=Xe(c.attrs.QUALITY??"")??vl({width:h,height:m});if(!f)return l;let b=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:f,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:b};return this.trackLevels.set(p,{track:v,level:c}),l.push(v),l},[]))),t.availableVideoTracks$),a(_t(this.hls,Pe.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let l=[];for(let c of d.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;l.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(l)}}),a(_t(this.hls,Pe.Events.LEVEL_LOADING).pipe(Mr(({url:d})=>G(d))),t.hostname$),a(_t(this.hls,Pe.Events.FRAG_CHANGED),d=>{let{video:l,audio:c}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(ze(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>Array.from(this.trackLevels.values()).find(({level:l})=>l===d)?.track,o=_t(this.hls,Pe.Events.LEVEL_SWITCHED).pipe(Mr(({level:d})=>s(this.hls.levels[d])));o.pipe(pl(hl)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ze(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{if(ml(d))return;let l=this.trackLevels.get(d.id)?.level;if(!l)return;let c=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=fl(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gl(["init"])).pipe(cl(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 ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Lr.DOM,thrown:t}))||(this.videoState.setState("paused"),T(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"),T(this.params.desiredState.playbackState,"stopped",!0)}};var zn="X-Playback-Duration",Ba=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(zn)?parseInt(e.headers.get(zn),10):void 0};import{assertNever as kl,combine as Pl,debounce as Al,ErrorCategory as Dr,filter as $l,filterChanged as wl,isNonNullable as Jn,isNullable as Cr,map as Xn,merge as Ll,observableFrom as Ml,Subscription as Rl,ValueSubject as Na,VideoQuality as Dl}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as yl,getExponentialDelay as Tl}from"@vkontakte/videoplayer-shared/evergreen";var Il=n=>{let e=null;if(n.QUALITY&&(e=Xe(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=yl({width:t,height:i})}return e??null},El=(n,e)=>{let t=n.split(`
|
|
123
|
-
`),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 d=Object.fromEntries(o[1].split(",").map(b=>b.split("="))),l=d.QUALITY??`stream-${d.BANDWIDTH}`,c=Il(d),p;d.BANDWIDTH&&(p=parseInt(d.BANDWIDTH,10)/1e3||void 0),!p&&d["AVERAGE-BANDWIDTH"]&&(p=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,m;if(d.RESOLUTION){let[b,v]=d.RESOLUTION.split("x").map(L=>parseInt(L,10));b&&v&&(m={width:b,height:v})}let f=new URL(t[++a],e).toString();c&&i.push({id:l,quality:c,url:f,bandwidth:p,size:m,fps:h})}if(u){let d=Object.fromEntries(u[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),l=d.URI?.replace(/playlist$/,"subtitles.vtt"),c=d.LANGUAGE,p=d.NAME;l&&c&&r.push({type:"internal",id:c,label:p,language:c,url:l,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},xl=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Oa=0,Kn=async(n,e=n,t)=>{let r=await(await fetch(n)).text();Oa+=1;try{let{qualityManifests:a,textTracks:s}=El(r,e);return{qualityManifests:a,textTracks:s}}catch{if(Oa<=t.manifestRetryMaxCount)return await xl(Tl(Oa-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Kn(n,e,t)}return{qualityManifests:[],textTracks:[]}},Rr=Kn;var Ui=class{constructor(e){this.subscription=new Rl;this.videoState=new $("stopped");this.textTracksManager=new Se;this.manifests$=new Na([]);this.liveOffset=new _e;this.manifestStartTime$=new Na(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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else r?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return kl(t)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Dl.INVARIANT,url:this.params.source.url},Rr(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Dr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Dr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Na(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:Dr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=oe(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(ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ge(this.video,t.playbackRate,r.playbackRateState$,i)),a(ye(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(wl(),Xn(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Jn(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Pl({startTime:this.manifestStartTime$.pipe($l(Jn)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Xn(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=Ll(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ml(["init"])).pipe(Al(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){let e=this.selectManifest();if(Cr(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[d,l]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(d||""));l&&d&&r.searchParams.set(l,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=J(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),Ba(s).then(o=>{if(!Cr(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Cr(u)||!isFinite(u))try{fetch(s).then(d=>d.text()).then(d=>{let l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(l){let c=new URL(l,s).toString();Ba(c).then(p=>{Cr(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Dr.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as Cl,debounce as Vl,ErrorCategory as _a,fromEvent as Fa,isNonNullable as Bl,isNullable as Ol,map as Zn,merge as eo,observableFrom as to,Subscription as Nl,ValueSubject as _l,VideoQuality as Fl,clientChecker as Ul}from"@vkontakte/videoplayer-shared/evergreen";var Hi=class{constructor(e){this.subscription=new Nl;this.videoState=new $("stopped");this.textTracksManager=new Se;this.manifests$=new _l([]);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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Cl(t)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Fl.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(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rr(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:_a.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&&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:_a.WTF,message:"HlsProvider internal logic error",thrown:o})},r=oe(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(Zn(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Me(this.video,t.isLooped,i)),this.subscription.add(ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ge(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{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(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Bl(d.to)){let h=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(G(m.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(Zn(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Ul.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(eo(Fa(o,"addtrack"),Fa(o,"removetrack"),Fa(o,"change"),to(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=eo(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,to(["init"])).pipe(Vl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){let e=this.selectManifest();if(Ol(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 d=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_a.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Hl,assertNonNullable as io,debounce as Ql,ErrorCategory as ro,isHigher as jl,isHigherOrEqual as ql,isInvariantQuality as ao,isLowerOrEqual as Wl,isNonNullable as Gl,merge as Yl,observableFrom as zl,Subscription as Kl,map as Jl}from"@vkontakte/videoplayer-shared/evergreen";var Qi=class{constructor(e){this.subscription=new Kl;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Se;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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),s.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[s.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return Hl(e)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,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:ro.WTF,message:"MpegProvider internal logic error",thrown:o})},r=oe(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(Jl(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Me(this.video,t.isLooped,i)),this.subscription.add(ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ge(this.video,t.playbackRate,r.playbackRateState$,i)),a(ye(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Gl(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(),d=this.params.output.element$.getValue()?.playbackRate;if(u!==d){let l=this.params.output.element$.getValue();l&&(this.params.desiredState.playbackRate.setState(u),l.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Yl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,zl(["init"])).pipe(Ql(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),se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;io(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];io(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ai(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ro.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!ao(o.track.quality)&&Wl(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&ql(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(d=>!ao(d.track.quality)&&jl(d.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=Ze(r,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as no,debounce as tc,merge as oo,observableFrom as ic,Subscription as rc,map as uo,ValueSubject as ac,ErrorCategory as Ha,VideoQuality as sc}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Xl}from"@vkontakte/videoplayer-shared/evergreen";var so=["stun:videostun.mycdn.me:80"],Zl=1e3,ec=3,Ua=()=>null,Vr=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=Ua;this.externalStopCallback=Ua;this.externalErrorCallback=Ua;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:so}]};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:Xl.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),Zl)}normalizeOptions(e={}){let t={stunServerList:so,maxRetryNumber:ec,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ji=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new ac(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return no(e)}};this.subscription=new rc,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ae(e.container,e.tuning),this.liveStreamClient=new Vr(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),se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:Ha.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};oo(this.videoState.stateChangeStarted$.pipe(uo(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(uo(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=oe(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(ye(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(ne(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 no(s.to)}},i)).add(oo(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ic(["init"])).pipe(tc(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(G(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:sc.INVARIANT}),this.video.srcObject=e,T(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ha.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ha.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var qi=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 Wi,assertNonNullable as st,ErrorCategory as Br,filter as fo,isNonNullable as bo,isNullable as hc,map as mc,merge as fc,once as bc,Subject as ce,Subscription as go,ValueSubject as w,flattenObject as So}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as nc,map as lo,Subscription as oc,Subject as uc}from"@vkontakte/videoplayer-shared/evergreen";var co=n=>new nc(e=>{let t=new oc,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(lo(({from:d,to:l})=>`${d}-${l}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(lo(({type:d})=>d!==void 0)),s=new uc,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as dc,Subscription as lc,combine as cc,filter as ho,once as mo}from"@vkontakte/videoplayer-shared/evergreen";function po(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as pc}from"@vkontakte/videoplayer-shared/evergreen";var Ft=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 lc;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(ho(a=>!!a.type),mo()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){pc.isSafari&&e!=="MPEG"||this.subscriptions.add(cc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(ho(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),mo()).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=po();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:dc.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var gc={chunkDuration:5e3,maxParallelRequests:5},Gi=class{constructor(e){this.current$=new w({type:void 0});this.providerError$=new ce;this.noAvailableProvidersError$=new ce;this.volumeMultiplierError$=new ce;this.providerOutput={position$:new w(0),duration$:new w(1/0),volume$:new w({muted:!1,volume:1}),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableVideoTracks$:new w([]),currentVideoTrack$:new w(void 0),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0),isAudioAvailable$:new w(!0),autoVideoTrackLimitingAvailable$:new w(!1),autoVideoTrackLimits$:new w(void 0),currentBuffer$:new w(void 0),isBuffering$:new w(!0),error$:new ce,warning$:new ce,willSeekEvent$:new ce,soundProhibitedEvent$:new ce,seekedEvent$:new ce,loopedEvent$:new ce,endedEvent$:new ce,firstBytesEvent$:new ce,loadedMetadataEvent$:new ce,firstFrameEvent$:new ce,canplay$:new ce,isLive$:new w(void 0),isLowLatency$:new w(!1),canChangePlaybackSpeed$:new w(!0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),inPiP$:new w(!1),inFullscreen$:new w(!1),element$:new w(void 0),elementVisible$:new w(!0),availableSources$:new w(void 0),is3DVideo$:new w(!1),playbackState$:new w("")};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=en([...rn(this.params.tuning),...tn(this.params.tuning)],this.params.tuning).filter(d=>bo(e.sources[d])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(d=>!r.includes(d)),...t.filter(d=>r.includes(d))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",So(a)),this.screenFormatsIterator=new qi(a);let s=[...ha(!0),...ha(!1)];this.chromecastFormatsIterator=new qi(s.filter(d=>bo(e.sources[d]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ft.isSupported()&&(this.volumeMultiplierManager=new Ft(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(hc(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Br.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 Wi(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 st(o),new Oi({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return st(o),new Ni({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return st(o),Vt||!this.params.tuning.useHlsJs?new Hi({...s,source:o}):new Fi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return st(o),new Ui({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return st(o),new Qi({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return st(o),new Ys({...s,source:o,config:{...gc,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return st(o),new ji({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 Wi(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 st(o),new jt({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 Wi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Wi(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 Wi(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(fc(this.providerOutput.error$.pipe(fo(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),co({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(mc(r=>({id:`ProviderHangup:${r}`,category:Br.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(fo(({to:a})=>a==="playing"),bc()).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===Br.NETWORK,u=r.category===Br.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!u,c=d&&!u&&(o&&t||!l);s={...s,isNetworkError:o,isFatalError:u,haveFailoverHost:d,tryFailover:c,canReinitProvider:l},l?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}this.tracer.error("providerError",So(s))})),e}};import{fromEvent as Or,once as Sc,combine as vc,Subscription as vo,ValueSubject as Qa,map as yc,filter as Tc,isNonNullable as Nr,now as fe,safeStorage as ja}from"@vkontakte/videoplayer-shared/evergreen";var Ic=5e3,yo="one_video_throughput",To="one_video_rtt",Yi=window.navigator.connection,Io=()=>{let n=Yi?.downlink;if(Nr(n)&&n!==10)return n*1e3},Eo=()=>{let n=Yi?.rtt;if(Nr(n)&&n!==3e3)return n},xo=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},qa=class n{constructor(e){this.subscription=new vo;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(yo)||(e.useBrowserEstimation?Io():void 0)||Ic,i=n.load(To)??(e.useBrowserEstimation?Eo():void 0)??0;if(this.throughput$=new Qa(t),this.rtt$=new Qa(i),this.rttAdjustedThroughput$=new Qa(xo(t,i,e.rttPenaltyRequestSize)),this.throughput=vt.getSmoothedValue(t,-1,e),this.rtt=vt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=Io();s&&this.throughput.next(s);let o=Eo();Nr(o)&&this.rtt.next(o)};Yi&&"onchange"in Yi&&this.subscription.add(Or(Yi,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{ja.set(yo,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{ja.set(To,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(vc({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(yc(({throughput:r,rtt:a})=>xo(r,a,e.rttPenaltyRequestSize)),Tc(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 vo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Or(e,"progress").pipe(Sc()).subscribe(a=>{t=a.loaded,i=fe()}));break;case 1:case 0:r.add(Or(e,"loadstart").subscribe(()=>{t=0,i=fe()}));break}r.add(Or(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=fe(),u=s-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=fe(),s=0,o=fe(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,fe()-a,1),this.concurrentDownloads.delete(e);else if(c){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=c.byteLength,a=fe()}else s+=c.byteLength;o=fe()}else r+=c.byteLength,s+=c.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(d,u)}};this.concurrentDownloads.add(e),i?.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=ja.get(e);if(Nr(t))return parseInt(t,10)??void 0}},ko=qa;import{fillWithDefault as Ec,VideoQuality as Po}from"@vkontakte/videoplayer-shared/evergreen";var Ao={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:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Po.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Po.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:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!0,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:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,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},$o=n=>({...Ec(n,Ao),configName:[...n.configName??[],...Ao.configName]});import{assertNonNullable as _r,combine as je,ErrorCategory as Fr,filter as X,filterChanged as V,fromEvent as Ga,isNonNullable as Lc,isNullable as Mc,Logger as Rc,map as R,mapTo as Ro,merge as nt,now as Ur,once as Ce,Subject as U,Subscription as Do,tap as Co,ValueSubject as E,isHigher as Dc,isInvariantQuality as Vo,flattenObject as ot,throttle as Ya,getTraceSubscriptionMethod as Bo,Tracer as Cc}from"@vkontakte/videoplayer-shared/evergreen";import{merge as xc,map as kc,filter as wo,isNonNullable as Pc}from"@vkontakte/videoplayer-shared/evergreen";var Wa=({seekState:n,position$:e})=>xc(n.stateChangeEnded$.pipe(kc(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),wo(Pc)),e.pipe(wo(()=>n.getState().state==="none")));import{assertNonNullable as Ac}from"@vkontakte/videoplayer-shared/evergreen";var Lo=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return Ac(e,`Wrong container or containerId {${n.container}}`),e};import{filter as $c,once as wc}from"@vkontakte/videoplayer-shared/evergreen";var Mo=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe($c(r=>r.length>0),wc()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Hr=class{constructor(e={configName:[]},t=Cc.createRootTracer(!1)){this.subscription=new Do;this.logger=new Rc;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!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 E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),liveLatency$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new U,ready$:new U,started$:new U,playing$:new U,paused$:new U,stopped$:new U,willStart$:new U,willResume$:new U,willPause$:new U,willStop$:new U,willDestruct$:new U,watchCoverageRecord$:new U,watchCoverageLive$:new U,managedError$:new U,fatalError$:new U,ended$:new U,looped$:new U,seeked$:new U,willSeek$:new U,autoplaySoundProhibited$:new U,firstBytes$:new U,loadedMetadata$:new U,firstFrame$:new U,canplay$:new U,log$:new U};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:$s};if(this.initLogs(),this.tuning=$o(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new rr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ko(this.tuning.throughputEstimator),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 d=o.map(p=>JSON.stringify(p,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${d.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Fr.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",ot(i)),this.domContainer=Lo(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Gi({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}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()}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&&!Zt()?(this.tracer.log("request play from hidden tab"),Ga(document,"visibilitychange").pipe(Ce()).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-.1),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),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){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){_r(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(X(i=>i.length>0),Ce()).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",ot(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){_r(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",ot(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Mo(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(Mc(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Lc(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(nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(R(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(R(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(R(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(R(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(R(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(X(({from:e})=>e==="stopped"),Ce()).subscribe(()=>{this.initedAt=Ur(),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",ot(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Fr.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ce()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ot(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(R(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(R(s=>s.destination),V()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(je({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(X(({currentVideoStream:s})=>!!s),R(({availableVideoTracks:s,currentVideoStream:o})=>s.filter(u=>o?.id===u.streamId).map(({quality:u})=>u).sort((u,d)=>Vo(u)?1:Vo(d)?-1:Dc(d,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(V()).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(V((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(V((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(V()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(V()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(V()).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(R(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(je({hasLiveOffsetByPaused:nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(R(s=>s.to),V(),R(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(je({atLiveEdge:je({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Wa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(R(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),V(),Co(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(R(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(je({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(R(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),V(),Co(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(R(s=>s.muted),V()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(R(s=>s.volume),V()).subscribe(this.info.volume$)).add(Wa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(nt(e.providerOutput.endedEvent$.pipe(Ro(!0)),e.providerOutput.seekedEvent$.pipe(Ro(!1))).pipe(V()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(R(s=>({id:s?`No${s}`:"NoProviders",category:Fr.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Ce(),R(s=>s??Ur()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ce(),R(()=>Ur()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ce(),R(()=>Ur()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(X(({to:s})=>s==="playing"),Ce()).subscribe(()=>i.next(!1)));let r=0,a=nt(e.providerOutput.isBuffering$,t,i).pipe(R(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),V());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(nt(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(nt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),c;l==="CONNECTED"?c="second_screen":u?d?s?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(R(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Do;this.subscription.add(t),this.subscription.add(e.current$.pipe(V((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(X(i=>i.length>0),Ce()).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=Ze(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(nt(this.desiredState.videoTrack.stateChangeStarted$.pipe(R(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(R(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(R(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(R(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(R(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(R(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(R(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(R(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(R(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;_r(this.providerContainer),_r(e),As(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ps(t)),this.providerContainer.current$.subscribe(({type:t})=>Gt("provider",t)),e.duration$.subscribe(t=>Gt("duration",t)),e.availableVideoTracks$.pipe(X(t=>!!t.length),Ce()).subscribe(t=>Gt("tracks",t)),this.events.fatalError$.subscribe(new ee("fatalError")),this.events.managedError$.subscribe(new ee("managedError")),e.position$.subscribe(new ee("position")),e.currentVideoTrack$.pipe(R(t=>t?.quality)).subscribe(new ee("quality")),this.info.currentBuffer$.subscribe(new ee("buffer")),e.isBuffering$.subscribe(new ee("isBuffering"))].forEach(t=>this.subscription.add(t)),Gt("codecs",Zs())}initTracerSubscription(){let e=Bo(this.tracer.log.bind(this.tracer)),t=Bo(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(V()).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(je({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(X(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),V((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(X(i=>i>0),V()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(X(i=>i>0),V()).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(je({currentBuffer:this.info.currentBuffer$.pipe(X(i=>i.end>0),V((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(V())}).pipe(Ya(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(V()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(V()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(V()).subscribe(e("canChangePlaybackSpeed"))).add(je({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(X(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Ya(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(V(),X(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(V(),X(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(V()).subscribe(e("muted"))).add(this.info.volume$.pipe(V()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(V(),X(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(je({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(X(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Ya(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(V(),X(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:Fr.DOM,message:String(r)})})};this.subscription.add(nt(Ga(document,"visibilitychange"),Ga(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",ot({quality:t,availableTracks:ot(e),track:ot(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 $k,Observable as wk,Subject as Lk,ValueSubject as Mk,VideoQuality as Rk}from"@vkontakte/videoplayer-shared/evergreen";var Dk=`@vkontakte/videoplayer-core@${Ka}`;export{tr as ChromecastState,jr as HttpConnectionType,wk as Observable,re as PlaybackState,Hr as Player,Dk as SDK_VERSION,Lk as Subject,$k as Subscription,qr as Surface,Ka as VERSION,Mk as ValueSubject,Ye as VideoFormat,Rk as VideoQuality};
|
|
122
|
+
`;var $r=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 Pr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ar(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();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(Nn,this.gl.VERTEX_SHADER),i=this.createShader(_n,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,d=t+r,c=e-i,p=t+r;return[a,s,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as Jl,now as Fn,Subscription as Zl,filter as ed,combine as Un,ValueSubject as Hn,isNonNullable as td}from"@vkontakte/videoplayer-shared/evergreen";var Ca=class{constructor(){this.isSeeked$=new Hn(!1);this.isBuffering$=new Hn(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Zl}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(Un({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(ed(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Un({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:i})=>{if(Jl(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:r,stallDurationNoDataBeforeQualityDecrease:a,stallCountBeforeQualityDecrease:s,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),c=Fn(),p=s&&this.currentStallsCount>=s,h=r&&!i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+u&&t>=r,m=a&&c-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&c-d>=a+u&&t>=a;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,td(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Fn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Qn=Ca;var Et=class{constructor(e){this.subscription=new dd;this.videoState=new $("stopped");this.elementSize$=new cd(void 0);this.textTracksManager=new Se;this.droppedFramesManager=new cr;this.stallsManager=new Qn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yt;this.audioTrackSwitchHistory=new Yt;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.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}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.liveOffset?.pause(),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.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"&&y(this.params.desiredState.playbackState,"paused");return;default:return ad(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new $r(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ae(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(G(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 kr({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=oe(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Va.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(jn(d=>!!d.length),Wn()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let s=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ba(d=>d.to.state!=="none"),Bi());this.stallsManager.connect({isSeeked$:s,currentStallDuration$:this.player.currentStallDuration$.pipe(Bi()),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.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(jn(qn),Wn()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(Ba(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Me(this.video,t.isLooped,r)),this.subscription.add(ne(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ge(this.video,t.playbackRate,i.playbackRateState$,r)),a(ld(this.video),this.elementSize$),a(Te(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:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(sd(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of c.audio){h.push(Ea(m));let f=[];for(let b of m.representations){let v=kn(b);f.push(v),this.audioTracksMap.set(v,{stream:m,representation:b})}this.audioStreamsMap.set(m,f)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of c.video){p.push(xa(h));let m=[];for(let f of h.representations){let b=xn({...f,streamId:h.id});b&&(m.push(b),this.videoTracksMap.set(b,{stream:h,representation:f}))}this.videoStreamsMap.set(h,m)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of c.text)for(let m of h.representations){let f=Pn(h,m);this.textTracksMap.set(f,{stream:h,representation:m})}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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=d=>e.error$.next({id:"RepresentationSwitch",category:Va.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(wr(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,od(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(d)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,f=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===h.id);qn(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,v).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Bi()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=c,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(xa(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Bi()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=c,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Ea(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),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 u=t.playbackState.stateChangeStarted$.pipe(Ba(({to:d})=>d==="ready"),Bi());this.subscription.add(wr(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(wr(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=wr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ud(["init"])).pipe(nd(0));this.subscription.add(l.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),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=Re(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),f=[...this.audioStreamsMap.keys()].find(({id:A})=>A===m?.id)??this.audioStreamsMap.keys().next().value,b=0;if(f){if(s&&!i){let A=or(s,d,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);b=Math.max(b,A?.bitrate??-1/0)}if(o){let A=or(o,d,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);b=Math.max(b,A?.bitrate??-1/0)}}let v=Ze(d,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:h,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}),L=i?v??s:s??v,I=f&&Ns(L,d,this.audioStreamsMap.get(f)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=this.videoTracksMap.get(L)?.representation,S=I&&this.audioTracksMap.get(I)?.representation;if(k&&S)return[k,S];if(k&&!S&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),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:Va.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),this.textTracksManager?.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),se(this.video),this.tracer.end()}};var Oi=class extends Et{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 Gn,interval as pd,map as Yn}from"@vkontakte/videoplayer-shared/evergreen";var Ni=class extends Et{constructor(e){super(e),this.liveOffset=new _e,this.textTracksManager=null}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(Yn(a=>a.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Gn({interval:pd(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(Gn({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Yn(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=An(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 _i,assertNonNullable as zn,debounce as hd,ErrorCategory as Lr,filter as md,isNonNullable as fd,isNullable as bd,map as Mr,merge as gd,Observable as Sd,observableFrom as vd,Subscription as Td,videoSizeToQuality as yd}from"@vkontakte/videoplayer-shared/evergreen";var Pe={};var _t=(n,e)=>new Sd(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Fi=class{constructor(e){this.subscription=new Td;this.videoState=new $("initializing");this.textTracksManager=new Se;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:_i(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:_i(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:_i(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:_i(e)}break;default:_i(t)}};this.video=ae(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(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),se(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Lr.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||(Pe.Hls=r.default,Pe.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){zn(Pe.Hls,"hls.js not loaded"),this.hls=new Pe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){zn(Pe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Lr.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=oe(this.video),a=(l,d)=>this.subscription.add(l.subscribe(d,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(Me(this.video,e.isLooped,i)),this.subscription.add(ne(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ge(this.video,e.playbackRate,r.playbackRateState$,i)),a(Te(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Mr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(_t(this.hls,Pe.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Lr.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(_t(this.hls,Pe.Events.MANIFEST_PARSED).pipe(Mr(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:h,height:m}=c,f=Je(c.attrs.QUALITY??"")??yd({width:h,height:m});if(!f)return d;let b=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:f,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:b};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),a(_t(this.hls,Pe.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),a(_t(this.hls,Pe.Events.LEVEL_LOADING).pipe(Mr(({url:l})=>G(l))),t.hostname$),a(_t(this.hls,Pe.Events.FRAG_CHANGED),l=>{let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(ze(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:d})=>d===l)?.track,o=_t(this.hls,Pe.Events.LEVEL_SWITCHED).pipe(Mr(({level:l})=>s(this.hls.levels[l])));o.pipe(md(fd)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ze(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),l=>{if(bd(l))return;let d=this.trackLevels.get(l.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=gd(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,vd(["init"])).pipe(hd(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 ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Lr.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 Kn="X-Playback-Duration",Oa=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(Kn)?parseInt(e.headers.get(Kn),10):void 0};import{assertNever as Rd,combine as Cd,debounce as Vd,ErrorCategory as Cr,filter as Bd,filterChanged as Od,isNonNullable as Zn,isNullable as Vr,map as eo,merge as Nd,observableFrom as _d,Subscription as Fd,ValueSubject as _a,VideoQuality as Ud}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Id,getExponentialDelay as Ed}from"@vkontakte/videoplayer-shared/evergreen";var xd=n=>{let e=null;if(n.QUALITY&&(e=Je(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Id({width:t,height:i})}return e??null},kd=(n,e)=>{let t=n.split(`
|
|
123
|
+
`),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(b=>b.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=xd(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[b,v]=l.RESOLUTION.split("x").map(L=>parseInt(L,10));b&&v&&(m={width:b,height:v})}let f=new URL(t[++a],e).toString();c&&i.push({id:d,quality:c,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,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,p=l.NAME;d&&c&&r.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Pd=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Na=0,Xn=async(n,e=n,t,i)=>{let a=await(await fetch(n,i)).text();Na+=1;try{let{qualityManifests:s,textTracks:o}=kd(a,e);return{qualityManifests:s,textTracks:o}}catch{if(Na<=t.manifestRetryMaxCount)return await Pd(Ed(Na-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Xn(n,e,t)}return{qualityManifests:[],textTracks:[]}},Dr=Xn;import{isNonNullable as Ad,Subscription as $d,throttle as wd,ValueSubject as Jn,Logger as Ld,Subject as Md,ErrorCategory as Dd}from"@vkontakte/videoplayer-shared/evergreen";var Rr=class{constructor(e,t,i,r){this.subscription=new $d;this.abortControllers={destroy:new AbortController,nextManifest:null};this.numberFormat=new Intl.NumberFormat("ru-RU",{maximumFractionDigits:2,minimumFractionDigits:2,useGrouping:!0});this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Jn(null);this.getCurrentTime$=new Jn(null);this.error$=new Md;this.logger=new Ld,this.log=this.logger.createComponentLog("LiveTextManager"),this.params={fetchManifestData:i,sourceUrl:r},this.subscription.add(e.pipe(wd(1e3)).subscribe(a=>{this.processLiveTime(a)})).add(this.logger.log$.subscribe(a=>{console.debug(`%c${a.component}`,"background:#258b6d;",a.message)})),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();this.log({message:"[parseTextTracks]"}),this.log({message:r});let s=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text();this.log({message:s});let o=this.parsePlaylist(s,r);return this.log({message:JSON.stringify(o,void 0,2)}),{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
124
|
+
`),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(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-c}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(Ad(e)&&this.currentTextTrackData){this.log({message:`[processLiveTime] ${e.toFixed(2)}, ${new Date(e).toISOString()}`});let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i){this.log({message:`[processLiveTime] out of bounds (before) ! ${i-e}`});return}if(e>r){this.log({message:`[processLiveTime] out of bounds (after) !' ${e-r}`});return}let a=r-e;this.log({message:`Current segments time left: ${this.numberFormat.format(a)} ms`}),a<4e3&&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:Dd.WTF,thrown:t,message:e})}};var Ui=class{constructor(e){this.subscription=new Fd;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new _a([]);this.liveOffset=new _e;this.manifestStartTime$=new _a(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else r?.to==="paused"&&(y(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Rd(t)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ud.INVARIANT,url:this.params.source.url};let t=(i,r)=>Dr(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 Rr(this.params.output.liveTime$,this.video,t,this.params.source.url):this.textTracksManager=new Se,t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Cr.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:Cr.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(G(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new _a(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:Cr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=oe(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(ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ge(this.video,t.playbackRate,r.playbackRateState$,i)),a(Te(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(Od(),eo(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Zn(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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(Cd({startTime:this.manifestStartTime$.pipe(Bd(Zn)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(eo(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=Nd(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,_d(["init"])).pipe(Vd(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),se(this.video)}prepare(){let e=this.selectManifest();if(Vr(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,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}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(),Oa(s).then(o=>{if(!Vr(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Vr(u)||!isFinite(u))&&fetch(s).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,s).toString();Oa(c).then(p=>{Vr(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ue(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:Cr.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 Hd,debounce as Qd,ErrorCategory as Fa,fromEvent as Ua,isNonNullable as jd,isNullable as qd,map as to,merge as io,observableFrom as ro,Subscription as Wd,ValueSubject as Gd,VideoQuality as Yd,clientChecker as zd}from"@vkontakte/videoplayer-shared/evergreen";var Hi=class{constructor(e){this.subscription=new Wd;this.videoState=new $("stopped");this.textTracksManager=new Se;this.manifests$=new Gd([]);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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*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 Hd(t)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Yd.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(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Dr(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:Fa.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&&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:Fa.WTF,message:"HlsProvider internal logic error",thrown:o})},r=oe(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(to(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Me(this.video,t.isLooped,i)),this.subscription.add(ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ge(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&jd(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(G(m.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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(to(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!zd.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(io(Ua(o,"addtrack"),Ua(o,"removetrack"),Ua(o,"change"),ro(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=io(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ro(["init"])).pipe(Qd(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){let e=this.selectManifest();if(qd(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(){ue(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:Fa.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Kd,assertNonNullable as ao,debounce as Xd,ErrorCategory as so,isHigher as Jd,isHigherOrEqual as Zd,isInvariantQuality as no,isLowerOrEqual as ec,isNonNullable as tc,merge as ic,observableFrom as rc,Subscription as ac,map as sc}from"@vkontakte/videoplayer-shared/evergreen";var Qi=class{constructor(e){this.subscription=new ac;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Se;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.max);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}),s.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[s.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 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 Kd(e)}};this.params=e,this.video=ae(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,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:so.WTF,message:"MpegProvider internal logic error",thrown:o})},r=oe(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(sc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Me(this.video,t.isLooped,i)),this.subscription.add(ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ge(this.video,t.playbackRate,r.playbackRateState$,i)),a(Te(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&&tc(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 d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=ic(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,rc(["init"])).pipe(Xd(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),se(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ao(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ao(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ai(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){ue(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:so.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!no(o.track.quality)&&ec(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&Zd(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(l=>!no(l.track.quality)&&Jd(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=Ze(r,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as uo,debounce as lc,merge as lo,observableFrom as dc,Subscription as cc,map as co,ValueSubject as pc,ErrorCategory as Qa,VideoQuality as hc}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as nc}from"@vkontakte/videoplayer-shared/evergreen";var oo=["stun:videostun.mycdn.me:80"],oc=1e3,uc=3,Ha=()=>null,Br=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=Ha;this.externalStopCallback=Ha;this.externalErrorCallback=Ha;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:oo}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=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:nc.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:oo,maxRetryNumber:uc,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ji=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new pc(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 uo(e)}};this.subscription=new cc,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ae(e.container,e.tuning),this.liveStreamClient=new Br(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),se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:Qa.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};lo(this.videoState.stateChangeStarted$.pipe(co(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(co(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=oe(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(Te(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(ne(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return uo(s.to)}},i)).add(lo(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,dc(["init"])).pipe(lc(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(G(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:hc.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:Qa.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ue(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:Qa.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var qi=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 Wi,assertNonNullable as st,ErrorCategory as Or,filter as go,isNonNullable as So,isNullable as yc,map as Ic,merge as Ec,once as xc,Subject as ce,Subscription as vo,ValueSubject as w,flattenObject as To}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as mc,map as po,Subscription as fc,Subject as bc}from"@vkontakte/videoplayer-shared/evergreen";var ho=n=>new mc(e=>{let t=new fc,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(po(({from:l,to:d})=>`${l}-${d}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(po(({type:l})=>l!==void 0)),s=new bc,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 Sc,combine as vc,filter as fo,once as bo}from"@vkontakte/videoplayer-shared/evergreen";function mo(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as Tc}from"@vkontakte/videoplayer-shared/evergreen";var Ft=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 Sc;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(fo(a=>!!a.type),bo()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Tc.isSafari&&e!=="MPEG"||this.subscriptions.add(vc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(fo(({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=mo();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 kc={chunkDuration:5e3,maxParallelRequests:5},Gi=class{constructor(e){this.current$=new w({type:void 0});this.providerError$=new ce;this.noAvailableProvidersError$=new ce;this.volumeMultiplierError$=new ce;this.providerOutput={position$:new w(0),duration$:new w(1/0),volume$:new w({muted:!1,volume:1}),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableVideoTracks$:new w([]),currentVideoTrack$:new w(void 0),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0),isAudioAvailable$:new w(!0),autoVideoTrackLimitingAvailable$:new w(!1),autoVideoTrackLimits$:new w(void 0),currentBuffer$:new w(void 0),isBuffering$:new w(!0),error$:new ce,warning$:new ce,willSeekEvent$:new ce,soundProhibitedEvent$:new ce,seekedEvent$:new ce,loopedEvent$:new ce,endedEvent$:new ce,firstBytesEvent$:new ce,loadedMetadataEvent$:new ce,firstFrameEvent$:new ce,canplay$:new ce,isLive$:new w(void 0),isLowLatency$:new w(!1),canChangePlaybackSpeed$:new w(!0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),inPiP$:new w(!1),inFullscreen$:new w(!1),element$:new w(void 0),elementVisible$:new w(!0),availableSources$:new w(void 0),is3DVideo$:new w(!1),playbackState$:new w(""),getCurrentTime$:new w(null)};this.subscription=new vo;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=tn([...an(this.params.tuning),...rn(this.params.tuning)],this.params.tuning).filter(l=>So(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",To(a)),this.screenFormatsIterator=new qi(a);let s=[...ma(!0),...ma(!1)];this.chromecastFormatsIterator=new qi(s.filter(l=>So(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ft.isSupported()&&(this.volumeMultiplierManager=new Ft(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(yc(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Or.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 Wi(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 st(o),new Oi({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return st(o),new Ni({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return st(o),Vt||!this.params.tuning.useHlsJs?new Hi({...s,source:o}):new Fi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return st(o),new Ui({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return st(o),new Qi({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return st(o),new zs({...s,source:o,config:{...kc,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return st(o),new ji({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 Wi(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 st(o),new jt({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 Wi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Wi(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 Wi(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 vo,t=!1,i=0;return e.add(Ec(this.providerOutput.error$.pipe(go(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),ho({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Ic(r=>({id:`ProviderHangup:${r}`,category:Or.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(go(({to:a})=>a==="playing"),xc()).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===Or.NETWORK,u=r.category===Or.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);s={...s,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}this.tracer.error("providerError",To(s))})),e}};import{fromEvent as Nr,once as Pc,combine as Ac,Subscription as yo,ValueSubject as ja,map as $c,filter as wc,isNonNullable as _r,now as fe,safeStorage as qa}from"@vkontakte/videoplayer-shared/evergreen";var Lc=5e3,Io="one_video_throughput",Eo="one_video_rtt",Yi=window.navigator.connection,xo=()=>{let n=Yi?.downlink;if(_r(n)&&n!==10)return n*1e3},ko=()=>{let n=Yi?.rtt;if(_r(n)&&n!==3e3)return n},Po=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Wa=class n{constructor(e){this.subscription=new yo;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Io)||(e.useBrowserEstimation?xo():void 0)||Lc,i=n.load(Eo)??(e.useBrowserEstimation?ko():void 0)??0;if(this.throughput$=new ja(t),this.rtt$=new ja(i),this.rttAdjustedThroughput$=new ja(Po(t,i,e.rttPenaltyRequestSize)),this.throughput=vt.getSmoothedValue(t,-1,e),this.rtt=vt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=xo();s&&this.throughput.next(s);let o=ko();_r(o)&&this.rtt.next(o)};Yi&&"onchange"in Yi&&this.subscription.add(Nr(Yi,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{qa.set(Io,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{qa.set(Eo,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ac({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($c(({throughput:r,rtt:a})=>Po(r,a,e.rttPenaltyRequestSize)),wc(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 yo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Nr(e,"progress").pipe(Pc()).subscribe(a=>{t=a.loaded,i=fe()}));break;case 1:case 0:r.add(Nr(e,"loadstart").subscribe(()=>{t=0,i=fe()}));break}r.add(Nr(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=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,fe()-a,1),this.concurrentDownloads.delete(e);else if(c){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=c.byteLength,a=fe()}else s+=c.byteLength;o=fe()}else r+=c.byteLength,s+=c.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=qa.get(e);if(_r(t))return parseInt(t,10)??void 0}},Ao=Wa;import{fillWithDefault as Mc,VideoQuality as $o}from"@vkontakte/videoplayer-shared/evergreen";var wo={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:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:$o.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:$o.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:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!0,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:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,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},Lo=n=>({...Mc(n,wo),configName:[...n.configName??[],...wo.configName]});import{assertNonNullable as Fr,combine as je,ErrorCategory as Ur,filter as J,filterChanged as V,fromEvent as Ya,isNonNullable as Nc,isNullable as _c,Logger as Fc,map as D,mapTo as Co,merge as nt,now as Hr,once as Ce,Subject as U,Subscription as Vo,tap as Bo,ValueSubject as E,isHigher as Uc,isInvariantQuality as Oo,flattenObject as ot,throttle as za,getTraceSubscriptionMethod as No,Tracer as Hc}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Dc,map as Rc,filter as Mo,isNonNullable as Cc}from"@vkontakte/videoplayer-shared/evergreen";var Ga=({seekState:n,position$:e})=>Dc(n.stateChangeEnded$.pipe(Rc(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Mo(Cc)),e.pipe(Mo(()=>n.getState().state==="none")));import{assertNonNullable as Vc}from"@vkontakte/videoplayer-shared/evergreen";var Do=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return Vc(e,`Wrong container or containerId {${n.container}}`),e};import{filter as Bc,once as Oc}from"@vkontakte/videoplayer-shared/evergreen";var Ro=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Bc(r=>r.length>0),Oc()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Qr=class{constructor(e={configName:[]},t=Hc.createRootTracer(!1)){this.subscription=new Vo;this.logger=new Fc;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!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 E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),liveLatency$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new U,ready$:new U,started$:new U,playing$:new U,paused$:new U,stopped$:new U,willStart$:new U,willResume$:new U,willPause$:new U,willStop$:new U,willDestruct$:new U,watchCoverageRecord$:new U,watchCoverageLive$:new U,managedError$:new U,fatalError$:new U,ended$:new U,looped$:new U,seeked$:new U,willSeek$:new U,autoplaySoundProhibited$:new U,firstBytes$:new U,loadedMetadata$:new U,firstFrame$:new U,canplay$:new U,log$:new U};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:ws,getCurrentTime$:new E(null)};if(this.initLogs(),this.tuning=Lo(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new rr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ao(this.tuning.throughputEstimator),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}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Ur.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",ot(i)),this.domContainer=Do(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Gi({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}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()}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&&!Zt()?(this.tracer.log("request play from hidden tab"),Ya(document,"visibilitychange").pipe(Ce()).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-.1),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),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){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Fr(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(J(i=>i.length>0),Ce()).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",ot(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Fr(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",ot(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Ro(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(_c(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Nc(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(nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(J(({from:e})=>e==="stopped"),Ce()).subscribe(()=>{this.initedAt=Hr(),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",ot(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Ur.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ce()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ot(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(s=>s.destination),V()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(je({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(J(({currentVideoStream:s})=>!!s),D(({availableVideoTracks:s,currentVideoStream:o})=>s.filter(u=>o?.id===u.streamId).map(({quality:u})=>u).sort((u,l)=>Oo(u)?1:Oo(l)?-1:Uc(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(V()).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(V((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(V((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(V()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(V()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(V()).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(D(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(je({hasLiveOffsetByPaused:nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(s=>s.to),V(),D(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(je({atLiveEdge:je({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ga({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:s,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return s&&Math.abs(o)<l/1e3}),V(),Bo(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(je({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),V(),Bo(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(s=>s.muted),V()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(s=>s.volume),V()).subscribe(this.info.volume$)).add(Ga({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(nt(e.providerOutput.endedEvent$.pipe(Co(!0)),e.providerOutput.seekedEvent$.pipe(Co(!1))).pipe(V()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(s=>({id:s?`No${s}`:"NoProviders",category:Ur.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(Ce(),D(s=>s??Hr()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ce(),D(()=>Hr()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ce(),D(()=>Hr()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(J(({to:s})=>s==="playing"),Ce()).subscribe(()=>i.next(!1)));let r=0,a=nt(e.providerOutput.isBuffering$,t,i).pipe(D(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),V());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(nt(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(nt(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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?s?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Vo;this.subscription.add(t),this.subscription.add(e.current$.pipe(V((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(J(i=>i.length>0),Ce()).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=Ze(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(nt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Fr(this.providerContainer),Fr(e),$s(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>As(t)),this.providerContainer.current$.subscribe(({type:t})=>Gt("provider",t)),e.duration$.subscribe(t=>Gt("duration",t)),e.availableVideoTracks$.pipe(J(t=>!!t.length),Ce()).subscribe(t=>Gt("tracks",t)),this.events.fatalError$.subscribe(new ee("fatalError")),this.events.managedError$.subscribe(new ee("managedError")),e.position$.subscribe(new ee("position")),e.currentVideoTrack$.pipe(D(t=>t?.quality)).subscribe(new ee("quality")),this.info.currentBuffer$.subscribe(new ee("buffer")),e.isBuffering$.subscribe(new ee("isBuffering"))].forEach(t=>this.subscription.add(t)),Gt("codecs",en())}initTracerSubscription(){let e=No(this.tracer.log.bind(this.tracer)),t=No(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(V()).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(je({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(J(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),V((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(J(i=>i>0),V()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(J(i=>i>0),V()).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(je({currentBuffer:this.info.currentBuffer$.pipe(J(i=>i.end>0),V((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(V())}).pipe(za(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(V()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(V()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(V()).subscribe(e("canChangePlaybackSpeed"))).add(je({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(J(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),za(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(V(),J(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(V(),J(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(V()).subscribe(e("muted"))).add(this.info.volume$.pipe(V()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(V(),J(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(je({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(J(({throughputEstimation:i,rtt:r})=>!!i&&!!r),za(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(V(),J(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:Ur.DOM,message:String(r)})})};this.subscription.add(nt(Ya(document,"visibilitychange"),Ya(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",ot({quality:t,availableTracks:ot(e),track:ot(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 Wk,Observable as Gk,Subject as Yk,ValueSubject as zk,VideoQuality as Kk}from"@vkontakte/videoplayer-shared/evergreen";var Xk=`@vkontakte/videoplayer-core@${Xa}`;export{tr as ChromecastState,qr as HttpConnectionType,Gk as Observable,re as PlaybackState,Qr as Player,Xk as SDK_VERSION,Yk as Subject,Wk as Subscription,Wr as Surface,Xa as VERSION,zk as ValueSubject,Ye as VideoFormat,Kk as VideoQuality};
|