@vkontakte/videoplayer-core 2.0.119-dev.c81726f6.0 → 2.0.119-dev.dc40b896.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 +5 -5
- package/es2015.esm.js +7 -7
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +8 -8
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +4 -4
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +1 -1
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.119-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.119-dev.dc40b896.0
|
|
3
|
+
* Wed, 11 Dec 2024 12:41:21 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-119/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Ka="2.0.119-dev.c81726f6.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 Gr,Subject as Ho,Subscription as Qo,merge as jo,observableFrom as qo,fromEvent as Xa,map as Za,tap as es,filterChanged as Go,isNullable as Wr,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 Gr(void 0);this.castState$=new Gr("NOT_AVAILABLE");this.errorEvent$=new Ho;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: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();Wr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Wr(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(Go(),Za(Wo),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;(Wr(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})}}},Wo=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 Gt,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(Gt(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(Gt(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(Gt(()=>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(Gt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Gt(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 G,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)},Wt=(n,e)=>{ta&&(Fe.meta=Fe.meta??{},Fe.meta[n]=e)},Z=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 Z("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=>G(u.bitrate)&&G(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=G(i?.last?.bitrate)&&G(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 Ka="2.0.119-dev.dc40b896.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 Gr,Subject as Ho,Subscription as Qo,merge as jo,observableFrom as qo,fromEvent as Xa,map as Za,tap as es,filterChanged as Go,isNullable as Wr,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 Gr(void 0);this.castState$=new Gr("NOT_AVAILABLE");this.errorEvent$=new Ho;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: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();Wr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Wr(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(Go(),Za(Wo),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;(Wr(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})}}},Wo=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 Gt,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(Gt(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(Gt(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(Gt(()=>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(Gt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Gt(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 G,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)},Wt=(n,e)=>{ta&&(Fe.meta=Fe.meta??{},Fe.meta[n]=e)},Z=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 Z("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=>G(u.bitrate)&&G(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=G(i?.last?.bitrate)&&G(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:`
|
|
7
7
|
[last ${o} selected] ${u}
|
|
8
8
|
`}),s}return i?.recordSwitch(t),t},ku=(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:d,visible:l,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{Ds(n,Vs);let f=i.containerSizeFactor;if(i.usePixelRatio&&window.devicePixelRatio){let g=window.devicePixelRatio;if(i.pixelRatioMultiplier)f*=i.pixelRatioMultiplier*(g-1)+1;else{let y=i.pixelRatioLogBase,[_=0,pe=0,Ie=0]=i.pixelRatioLogCoefficients,x=ku(y,_*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&&G(o)?o:1,L=n.filter(g=>!ws(g.quality)).sort((g,y)=>ra(g.quality,y.quality)?-1:1),I=L.at(-1)?.quality,k=L.at(0)?.quality,S=ia(r)||G(r.min)&&G(r.max)&&Ls(r.max,r.min)||G(r.min)&&k&&ra(r.min,k)||G(r.max)&&I&&Ls(r.max,I),A=v*Cs(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),C={},B=L.filter(g=>{let y=!0;if(b)if(g.size)y=g.size.width<=b.width&&g.size.height<=b.height;else{let z=b&&Iu(b);y=z?sa(g.quality,z):!0}if(!y)return C[g.quality]="FitsContainer",!1;let _=h||t;if(!(G(_)&&isFinite(_)&&G(g.bitrate)?_-a>=g.bitrate*A:!0))return C[g.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&G(i.minBufferToSwitchUp)&&u&&!ws(u.quality)&&(s??0)<i.minBufferToSwitchUp&&ra(g.quality,u.quality))return C[g.quality]="Buffer",!1;if(!!c&&aa(g.quality,c))return C[g.quality]="DroppedFramesLimit",!1;if(!!p&&aa(g.quality,p))return C[g.quality]="StallsLimit",!1;let P=S||(ia(r.max)||sa(g.quality,r.max))&&(ia(r.min)||aa(g.quality,r.min)),q=G(l)&&!l?sa(g.quality,i.backgroundVideoQualityLimit):!0;return!P||!q?(C[g.quality]="FitsQualityLimits",!1):!0})[0];B&&B.bitrate&&xu.next(B.bitrate);let F=B??L.at(-1)??n[0];return F.quality!==d?.last?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
@@ -119,5 +119,5 @@ 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(W(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new 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 Gn,interval as ll,map as Wn}from"@vkontakte/videoplayer-shared/evergreen";var Ni=class extends Et{constructor(e){super(e),this.liveOffset=new _e,this.textTracksManager?.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),r(this.player.liveLatency$,e.liveLatency$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe(Wn(a=>a.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Gn({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(Gn({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Wn(({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(W(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),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})=>W(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(`
|
|
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(W(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new 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 Gn,interval as ll,map as Wn}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(Wn(a=>a.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Gn({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(Gn({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Wn(({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(W(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),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})=>W(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
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(W(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(W(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(W(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(W(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 Gl,isNonNullable as Wl,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&&Wl(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(W(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)&&Gl(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(W(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality: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 Gi,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},Wi=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 Gi(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 Gi(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 Gi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Gi(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 Gi(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:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!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,exposeInternalsToGlobal:!1},$o=n=>({...Ec(n,Ao),configName:[...n.configName??[],...Ao.configName]});import{assertNonNullable as _r,combine as je,ErrorCategory as Fr,filter as te,filterChanged as V,fromEvent as Wa,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,InternalsExposure as Vc}from"@vkontakte/videoplayer-shared/evergreen";import{merge as xc,map as kc,filter as wo,isNonNullable as Pc}from"@vkontakte/videoplayer-shared/evergreen";var Ga=({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.internalsExposure=null;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),e.exposeInternalsToGlobal&&(this.internalsExposure=new Vc("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let s=Reflect.get(i,r,a);return typeof s!="function"?s:(...o)=>{try{return s.apply(i,o)}catch(u){let 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 Wi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Zt()?(this.tracer.log("request play from hidden tab"),Wa(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(te(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(te(({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(R(({availableVideoTracks:s,currentVideoStream:o})=>s.filter(u=>o?o.id===u.streamId:!0).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:Ga({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(Ga({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(te(({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(te(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})=>Wt("provider",t)),e.duration$.subscribe(t=>Wt("duration",t)),e.availableVideoTracks$.pipe(te(t=>!!t.length),Ce()).subscribe(t=>Wt("tracks",t)),this.events.fatalError$.subscribe(new Z("fatalError")),this.events.managedError$.subscribe(new Z("managedError")),e.position$.subscribe(new Z("position")),e.currentVideoTrack$.pipe(R(t=>t?.quality)).subscribe(new Z("quality")),this.info.currentBuffer$.subscribe(new Z("buffer")),e.isBuffering$.subscribe(new Z("isBuffering"))].forEach(t=>this.subscription.add(t)),Wt("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(te(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),V((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(te(i=>i>0),V()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(te(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(te(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(te(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Ya(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(V(),te(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(V(),te(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(),te(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(je({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(te(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Ya(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(V(),te(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(Wa(document,"visibilitychange"),Wa(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.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 Lk,Subject as Mk,ValueSubject as Rk,VideoQuality as Dk}from"@vkontakte/videoplayer-shared/evergreen";var Ck=`@vkontakte/videoplayer-core@${Ka}`;export{tr as ChromecastState,jr as HttpConnectionType,Lk as Observable,re as PlaybackState,Hr as Player,Ck as SDK_VERSION,Mk as Subject,wk as Subscription,qr as Surface,Ka as VERSION,Rk as ValueSubject,Ye as VideoFormat,Dk as VideoQuality};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vkontakte/videoplayer-core",
|
|
3
|
-
"version": "2.0.119-dev.
|
|
3
|
+
"version": "2.0.119-dev.dc40b896.0",
|
|
4
4
|
"author": "vk.com",
|
|
5
5
|
"description": "Videoplayer core library based on the vk.com platform",
|
|
6
6
|
"homepage": "https://vk.com",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"**/*.d.ts"
|
|
50
50
|
],
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@vkontakte/videoplayer-shared": "1.0.51-dev.
|
|
52
|
+
"@vkontakte/videoplayer-shared": "1.0.51-dev.64889560.0",
|
|
53
53
|
"hls.js": "~1.4.7"
|
|
54
54
|
}
|
|
55
55
|
}
|
|
@@ -22,7 +22,7 @@ export default abstract class BaseDashProvider implements IProvider {
|
|
|
22
22
|
protected params: IParams;
|
|
23
23
|
protected tracer: ITracer;
|
|
24
24
|
protected elementSize$: ValueSubject<IRectangle<number> | undefined>;
|
|
25
|
-
protected textTracksManager: TextTrackManager;
|
|
25
|
+
protected textTracksManager: TextTrackManager | null;
|
|
26
26
|
protected droppedFramesManager: DroppedFramesManager;
|
|
27
27
|
protected stallsManager: StallsManager;
|
|
28
28
|
protected videoTracksMap: Map<IVideoTrack, {
|