@vkontakte/videoplayer-core 2.0.126-dev.aef633ec.0 → 2.0.126-dev.c7a026f6.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 +12 -12
- package/es2015.esm.js +12 -12
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +12 -12
- package/esnext.cjs.js +6 -6
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +4 -4
- package/package.json +2 -2
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.126-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.126-dev.c7a026f6.0
|
|
3
|
+
* Wed, 12 Feb 2025 09:47:13 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-126/doc/
|
|
5
5
|
*/
|
|
6
|
-
var ds="2.0.126-dev.aef633ec.0";var ae=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ae||{}),Ze=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(Ze||{});var ur=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ur||{}),ia=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ia||{});var ra=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(ra||{}),lr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(lr||{});import{assertNever as bs,assertNonNullable as au,isNonNullable as dr,ValueSubject as aa,Subject as su,Subscription as nu,merge as ou,observableFrom as uu,fromEvent as ps,map as hs,tap as ms,filterChanged as lu,isNullable as sa,ErrorCategory as fs}from"@vkontakte/videoplayer-shared/evergreen";var cs=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var cr=class{constructor(e){this.connection$=new aa(void 0);this.castState$=new aa("NOT_AVAILABLE");this.errorEvent$=new su;this.realCastState$=new aa("NOT_AVAILABLE");this.subscription=new nu;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=dr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||cs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:fs.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){dr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();sa(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();sa(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(ps(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 bs(r.sessionState)}})).add(ou(ps(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ms(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),hs(r=>r.castState)),uu([i.getCastState()])).pipe(lu(),hs(du),ms(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=dr(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();au(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(sa(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?dr(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:fs.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},du=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 bs(n)}};import{assertNever as gs}from"@vkontakte/videoplayer-shared/evergreen";var K=(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:gs(t)}return n},pr=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:gs(e)}};var v=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as cu,Subject as hr,merge as Ss}from"@vkontakte/videoplayer-shared/evergreen";var w=class{constructor(e){this.transitionStarted$=new hr;this.transitionEnded$=new hr;this.transitionUpdated$=new hr;this.forceChanged$=new hr;this.stateChangeStarted$=Ss(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ss(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||cu(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 pu}from"@vkontakte/videoplayer-shared/evergreen";var vs=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 pu(n)}};import{assertNever as Ct,assertNonNullable as ft,debounce as ys,ErrorCategory as Ts,fromEvent as bt,isNonNullable as Is,map as Es,merge as xs,observableFrom as hu,Subject as mu,Subscription as na,timeout as fu,getHighestQuality as bu}from"@vkontakte/videoplayer-shared/evergreen";var gu=5,Su=5,vu=500,ks=7e3,Yt=class{constructor(e){this.subscription=new na;this.loadMediaTimeoutSubscription=new na;this.videoState=new w("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ct(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ct(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ct(e)}break}default:Ct(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(vs(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 na;this.subscription.add(e),this.subscription.add(xs(this.videoState.stateChangeStarted$.pipe(Es(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Es(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 mu;e.add(r.pipe(ys(vu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>gu)&&r.next(o),a=o})),e.add(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Su&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),v(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Ct(s)}}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=xs(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hu(["init"])).pipe(ys(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&v(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];ft(l);let c=bu(Object.keys(l));ft(c);let d=l[c];ft(d),i=d,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];ft(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];ft(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];ft(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];ft(l),i=K(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ts.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ct(e)}let s=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Is(o)&&(s.metadata.title=o),Is(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(fu(ks).subscribe(()=>a(`timeout(${ks})`)))});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:Ts.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as As}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as yu}from"@vkontakte/videoplayer-shared/evergreen";var Ps=n=>{try{n.pause(),n.playbackRate=0,yu(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Tu,Subscription as Iu}from"@vkontakte/videoplayer-shared/evergreen";var oa=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)}},ua=window.WeakMap?new WeakMap:new oa,la=window.WeakMap?new WeakMap:new Map,Eu=(n,e=20)=>{let t=0;return Tu(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},se=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?As(i):(i=document.createElement("video"),n.appendChild(i)),ua.set(i,r);let a=new Iu;return a.add(Eu(i,e)),la.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ne=n=>{la.get(n)?.unsubscribe(),la.delete(n);let t=ua.get(n);ua.delete(n),t?As(n):Ps(n)};import{assertNonNullable as zt,isNonNullable as Ve,isNullable as Pu,fromEvent as Vt,merge as Ls,observableFrom as ws,filterChanged as $s,map as Kt,Subject as Ms,Subscription as Au,ValueSubject as Lu,ErrorCategory as wu}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as da,isNullable as xu,Subscription as ku}from"@vkontakte/videoplayer-shared/evergreen";var mr=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=xu(r),l=new ku;return r&&l.add(r.subscribe(c=>{let d=n.getState();i(c,d)&&n.setState(c)},a)),i(o,s)||(t(s),u&&n.setState(s)),l.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),u&&n.setState(c.to)},a)),l},Ce=(n,e,t)=>mr(e,()=>n.loop,i=>{da(i)&&(n.loop=i)},{onError:t}),oe=(n,e,t,i)=>mr(e,()=>({muted:n.muted,volume:n.volume}),r=>{da(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),ye=(n,e,t,i)=>mr(e,()=>n.playbackRate,r=>{da(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),et=mr;var $u=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},ca=class n{constructor(e){this.available$=new Ms;this.current$=new Lu(void 0);this.error$=new Ms;this.subscription=new Au;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:wu.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(et(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ve(a)&&this.setInternal(a)},{equal:(a,s)=>Ve(a)&&Ve(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Kt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(et(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ve(a)&&this.setExternal(a)},{equal:(a,s)=>Ve(a)&&Ve(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Kt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(et(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(et(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){zt(this.video);let{textTracks:e}=this.video;this.subscription.add(Vt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ls(Vt(e,"addtrack"),Vt(e,"removetrack"),ws(["init"])).pipe(Kt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),$s((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(Ls(Vt(e,"change"),ws(["init"])).pipe(Kt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Kt(i=>i&&this.htmlTextTrackToITextTrack(i).id),$s()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Vt(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Vt(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Ve(t.align)&&(r.align=t.align),Ve(t.position)&&(r.position=t.position),Ve(t.size)&&(r.size=t.size),Ve(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){zt(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:$u(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){zt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Pu(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){zt(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){zt(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Te=ca;var Qe=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Rs=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},pa=n=>{let e=Rs(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Ds=n=>{let e=Rs(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as Ie,map as tt,merge as Vs,filterChanged as Du,isNonNullable as Bs,Subject as Cu,filter as Os,mapTo as Ns,combine as Vu,once as Bu,ErrorCategory as Ou,ValueSubject as _s,clientChecker as Nu}from"@vkontakte/videoplayer-shared/evergreen";var Ru=3,Cs=(n,e,t=Ru)=>{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 ue=n=>{let e=E=>Ie(n,E).pipe(Ns(void 0)),i=Vs(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>Ie(n,E))).pipe(tt(E=>E.type==="ended"?n.readyState<2:n.readyState<3),Du()),r=Vs(Ie(n,"progress"),Ie(n,"timeupdate")).pipe(tt(()=>Cs(n.buffered,n.currentTime))),a=Nu.isSafari?Vu({play:e("play").pipe(Bu()),playing:e("playing")}).pipe(Ns(void 0)):e("playing"),s=Ie(n,"volumechange").pipe(tt(()=>({muted:n.muted,volume:n.volume}))),o=Ie(n,"ratechange").pipe(tt(()=>n.playbackRate)),u=Ie(n,"error").pipe(Os(()=>!!(n.error||n.played.length)),tt(()=>{let E=n.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:Ou.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=Ie(n,"timeupdate").pipe(tt(()=>n.currentTime)),c=new Cu,d=.3,p;l.subscribe(E=>{n.loop&&Bs(p)&&Bs(E)&&p>=n.duration-d&&E<=d&&c.next(p),p=E});let h=e("pause").pipe(Os(()=>!n.error&&p!==n.duration)),m=Ie(n,"enterpictureinpicture"),f=Ie(n,"leavepictureinpicture"),g=new _s(Ds(n));m.subscribe(()=>g.next(!0)),f.subscribe(()=>g.next(!1));let y=new _s(pa(n));return Ie(n,"fullscreenchange").pipe(tt(()=>pa(n))).subscribe(y),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ie(n,"durationchange").pipe(tt(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:g,inFullscreen$:y,enterPip$:m,leavePip$:f}};import{VideoQuality as it}from"@vkontakte/videoplayer-shared/evergreen";var rt=n=>{switch(n){case"mobile":return it.Q_144P;case"lowest":return it.Q_240P;case"low":return it.Q_360P;case"sd":case"medium":return it.Q_480P;case"hd":case"high":return it.Q_720P;case"fullhd":case"full":return it.Q_1080P;case"quadhd":case"quad":return it.Q_1440P;case"ultrahd":case"ultra":return it.Q_2160P}};import{isNonNullable as me,isNullable as qs,now as zs,isHigher as Ws,isHigherOrEqual as ba,isInvariantQuality as Gs,isLowerOrEqual as ga,videoSizeToQuality as Uu,assertNotEmptyArray as Ks,assertNonNullable as Hu}from"@vkontakte/videoplayer-shared/evergreen";var ha=!1,je={},Fs=n=>{ha=n},Us=()=>{je={}},Hs=n=>{n(je)},Xt=(n,e)=>{ha&&(je.meta=je.meta??{},je.meta[n]=e)},ee=class{constructor(e){this.name=e}next(e){if(!ha)return;je.series=je.series??{};let t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}};import{isHigher as _u,isHigherOrEqual as Dh,isLower as Qs,isLowerOrEqual as Ch,isNonNullable as fr,isNullable as Fu,videoHeightToQuality as br}from"@vkontakte/videoplayer-shared/evergreen";function ma({limits:n,highQualityLimit:e,trafficSavingLimit:t}){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function fa({limits:n,highQualityLimit:e,trafficSavingLimit:t}){return!!n&&ma({limits:n,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Jt({limits:n,highestAvailableQuality:e,lowestAvailableQuality:t}){return Fu(n)||fr(n.min)&&fr(n.max)&&Qs(n.max,n.min)||fr(n.min)&&e&&_u(n.min,e)||fr(n.max)&&t&&Qs(n.max,t)}function js({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return Jt({limits:{max:n?.max?br(n.max):void 0,min:n?.min?br(n.min):void 0},highestAvailableQuality:e?br(e):void 0,lowestAvailableQuality:t?br(t):void 0})}var Qu=new ee("best_bitrate"),Xs=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var Sa=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),Zt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=zs()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Js='Assertion "ABR Tracks is empty array" failed',gr=(n,e,t,i)=>{let r=[...e].sort(Sa(1)),a=[...t].sort(Sa(1)),s=a.filter(u=>me(u.bitrate)&&me(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=a.at(Math.round(a.length*r.indexOf(n)/(r.length+1)))??a.at(-1);return o&&s.includes(o)?o:s.length?s.at(-1):a.at(0)},Ys=n=>"quality"in n,Zs=(n,e,t,i)=>{let r=me(i?.last?.bitrate)&&me(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&zs()-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=Ys(s)?"video":"audio",u=Ys(s)?s.quality:s.bitrate;return e({message:`
|
|
6
|
+
var ds="2.0.126-dev.c7a026f6.0";var ae=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ae||{}),Ze=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(Ze||{});var ur=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ur||{}),ia=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ia||{});var ra=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(ra||{}),lr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(lr||{});import{assertNever as bs,assertNonNullable as au,isNonNullable as dr,ValueSubject as aa,Subject as su,Subscription as nu,merge as ou,observableFrom as uu,fromEvent as ps,map as hs,tap as ms,filterChanged as lu,isNullable as sa,ErrorCategory as fs}from"@vkontakte/videoplayer-shared/evergreen";var cs=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var cr=class{constructor(e){this.connection$=new aa(void 0);this.castState$=new aa("NOT_AVAILABLE");this.errorEvent$=new su;this.realCastState$=new aa("NOT_AVAILABLE");this.subscription=new nu;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=dr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||cs("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:fs.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){dr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();sa(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();sa(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(ps(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 bs(r.sessionState)}})).add(ou(ps(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ms(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),hs(r=>r.castState)),uu([i.getCastState()])).pipe(lu(),hs(du),ms(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=dr(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();au(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(sa(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?dr(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:fs.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},du=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 bs(n)}};import{assertNever as gs}from"@vkontakte/videoplayer-shared/evergreen";var K=(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:gs(t)}return n},pr=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:gs(e)}};var v=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as cu,Subject as hr,merge as Ss}from"@vkontakte/videoplayer-shared/evergreen";var w=class{constructor(e){this.transitionStarted$=new hr;this.transitionEnded$=new hr;this.transitionUpdated$=new hr;this.forceChanged$=new hr;this.stateChangeStarted$=Ss(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ss(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||cu(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 pu}from"@vkontakte/videoplayer-shared/evergreen";var vs=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 pu(n)}};import{assertNever as Ct,assertNonNullable as ft,debounce as ys,ErrorCategory as Ts,fromEvent as bt,isNonNullable as Is,map as Es,merge as xs,observableFrom as hu,Subject as mu,Subscription as na,timeout as fu,getHighestQuality as bu}from"@vkontakte/videoplayer-shared/evergreen";var gu=5,Su=5,vu=500,ks=7e3,Yt=class{constructor(e){this.subscription=new na;this.loadMediaTimeoutSubscription=new na;this.videoState=new w("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ct(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ct(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ct(e)}break}default:Ct(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(vs(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 na;this.subscription.add(e),this.subscription.add(xs(this.videoState.stateChangeStarted$.pipe(Es(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Es(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 mu;e.add(r.pipe(ys(vu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>gu)&&r.next(o),a=o})),e.add(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Su&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),v(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Ct(s)}}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(bt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=xs(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hu(["init"])).pipe(ys(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&v(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];ft(l);let c=bu(Object.keys(l));ft(c);let d=l[c];ft(d),i=d,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];ft(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];ft(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];ft(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];ft(l),i=K(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ts.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ct(e)}let s=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Is(o)&&(s.metadata.title=o),Is(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(fu(ks).subscribe(()=>a(`timeout(${ks})`)))});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:Ts.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as As}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as yu}from"@vkontakte/videoplayer-shared/evergreen";var Ps=n=>{try{n.pause(),n.playbackRate=0,yu(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Tu,Subscription as Iu}from"@vkontakte/videoplayer-shared/evergreen";var oa=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)}},ua=window.WeakMap?new WeakMap:new oa,la=window.WeakMap?new WeakMap:new Map,Eu=(n,e=20)=>{let t=0;return Tu(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},se=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?As(i):(i=document.createElement("video"),n.appendChild(i)),ua.set(i,r);let a=new Iu;return a.add(Eu(i,e)),la.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ne=n=>{la.get(n)?.unsubscribe(),la.delete(n);let t=ua.get(n);ua.delete(n),t?As(n):Ps(n)};import{assertNonNullable as zt,isNonNullable as Ve,isNullable as Pu,fromEvent as Vt,merge as Ls,observableFrom as ws,filterChanged as $s,map as Kt,Subject as Ms,Subscription as Au,ValueSubject as Lu,ErrorCategory as wu}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as da,isNullable as xu,Subscription as ku}from"@vkontakte/videoplayer-shared/evergreen";var mr=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=xu(r),l=new ku;return r&&l.add(r.subscribe(c=>{let d=n.getState();i(c,d)&&n.setState(c)},a)),i(o,s)||(t(s),u&&n.setState(s)),l.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),u&&n.setState(c.to)},a)),l},Ce=(n,e,t)=>mr(e,()=>n.loop,i=>{da(i)&&(n.loop=i)},{onError:t}),oe=(n,e,t,i)=>mr(e,()=>({muted:n.muted,volume:n.volume}),r=>{da(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),ye=(n,e,t,i)=>mr(e,()=>n.playbackRate,r=>{da(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),et=mr;var $u=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},ca=class n{constructor(e){this.available$=new Ms;this.current$=new Lu(void 0);this.error$=new Ms;this.subscription=new Au;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:wu.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(et(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ve(a)&&this.setInternal(a)},{equal:(a,s)=>Ve(a)&&Ve(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Kt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(et(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ve(a)&&this.setExternal(a)},{equal:(a,s)=>Ve(a)&&Ve(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Kt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(et(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(et(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){zt(this.video);let{textTracks:e}=this.video;this.subscription.add(Vt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ls(Vt(e,"addtrack"),Vt(e,"removetrack"),ws(["init"])).pipe(Kt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),$s((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(Ls(Vt(e,"change"),ws(["init"])).pipe(Kt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Kt(i=>i&&this.htmlTextTrackToITextTrack(i).id),$s()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Vt(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Vt(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Ve(t.align)&&(r.align=t.align),Ve(t.position)&&(r.position=t.position),Ve(t.size)&&(r.size=t.size),Ve(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){zt(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:$u(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){zt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Pu(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){zt(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){zt(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Te=ca;var Qe=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Rs=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},pa=n=>{let e=Rs(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Ds=n=>{let e=Rs(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as Ie,map as tt,merge as Vs,filterChanged as Du,isNonNullable as Bs,Subject as Cu,filter as Os,mapTo as Ns,combine as Vu,once as Bu,ErrorCategory as Ou,ValueSubject as _s,clientChecker as Nu}from"@vkontakte/videoplayer-shared/evergreen";var Ru=3,Cs=(n,e,t=Ru)=>{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 ue=n=>{let e=E=>Ie(n,E).pipe(Ns(void 0)),i=Vs(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>Ie(n,E))).pipe(tt(E=>E.type==="ended"?n.readyState<2:n.readyState<3),Du()),r=Vs(Ie(n,"progress"),Ie(n,"timeupdate")).pipe(tt(()=>Cs(n.buffered,n.currentTime))),a=Nu.isSafari?Vu({play:e("play").pipe(Bu()),playing:e("playing")}).pipe(Ns(void 0)):e("playing"),s=Ie(n,"volumechange").pipe(tt(()=>({muted:n.muted,volume:n.volume}))),o=Ie(n,"ratechange").pipe(tt(()=>n.playbackRate)),u=Ie(n,"error").pipe(Os(()=>!!(n.error||n.played.length)),tt(()=>{let E=n.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:Ou.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=Ie(n,"timeupdate").pipe(tt(()=>n.currentTime)),c=new Cu,d=.3,p;l.subscribe(E=>{n.loop&&Bs(p)&&Bs(E)&&p>=n.duration-d&&E<=d&&c.next(p),p=E});let h=e("pause").pipe(Os(()=>!n.error&&p!==n.duration)),m=Ie(n,"enterpictureinpicture"),f=Ie(n,"leavepictureinpicture"),g=new _s(Ds(n));m.subscribe(()=>g.next(!0)),f.subscribe(()=>g.next(!1));let y=new _s(pa(n));return Ie(n,"fullscreenchange").pipe(tt(()=>pa(n))).subscribe(y),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ie(n,"durationchange").pipe(tt(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:g,inFullscreen$:y,enterPip$:m,leavePip$:f}};import{VideoQuality as it}from"@vkontakte/videoplayer-shared/evergreen";var rt=n=>{switch(n){case"mobile":return it.Q_144P;case"lowest":return it.Q_240P;case"low":return it.Q_360P;case"sd":case"medium":return it.Q_480P;case"hd":case"high":return it.Q_720P;case"fullhd":case"full":return it.Q_1080P;case"quadhd":case"quad":return it.Q_1440P;case"ultrahd":case"ultra":return it.Q_2160P}};import{isNonNullable as me,isNullable as qs,now as zs,isHigher as Ws,isHigherOrEqual as ba,isInvariantQuality as Gs,isLowerOrEqual as ga,videoSizeToQuality as Uu,assertNotEmptyArray as Ks,assertNonNullable as Hu}from"@vkontakte/videoplayer-shared/evergreen";var ha=!1,je={},Fs=n=>{ha=n},Us=()=>{je={}},Hs=n=>{n(je)},Xt=(n,e)=>{ha&&(je.meta=je.meta??{},je.meta[n]=e)},ee=class{constructor(e){this.name=e}next(e){if(!ha)return;je.series=je.series??{};let t=je.series[this.name]??[];t.push([Date.now(),e]),je.series[this.name]=t}};import{isHigher as _u,isHigherOrEqual as Dh,isLower as Qs,isLowerOrEqual as Ch,isNonNullable as fr,isNullable as Fu,videoHeightToQuality as br}from"@vkontakte/videoplayer-shared/evergreen";function ma({limits:n,highQualityLimit:e,trafficSavingLimit:t}){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function fa({limits:n,highQualityLimit:e,trafficSavingLimit:t}){return!!n&&ma({limits:n,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Jt({limits:n,highestAvailableQuality:e,lowestAvailableQuality:t}){return Fu(n)||fr(n.min)&&fr(n.max)&&Qs(n.max,n.min)||fr(n.min)&&e&&_u(n.min,e)||fr(n.max)&&t&&Qs(n.max,t)}function js({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return Jt({limits:{max:n?.max?br(n.max):void 0,min:n?.min?br(n.min):void 0},highestAvailableQuality:e?br(e):void 0,lowestAvailableQuality:t?br(t):void 0})}var Qu=new ee("best_bitrate"),Xs=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var Sa=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),Zt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=zs()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Js='Assertion "ABR Tracks is empty array" failed',gr=(n,e,t,i)=>{let r=[...e].sort(Sa(1)),a=[...t].sort(Sa(1)),s=a.filter(u=>me(u.bitrate)&&me(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=a.at(Math.round(a.length*r.indexOf(n)/(r.length+1)))??a.at(-1);return o&&s.includes(o)?o:s.length?s.at(-1):a.at(0)},Ys=n=>"quality"in n,Zs=(n,e,t,i)=>{let r=me(i?.last?.bitrate)&&me(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&zs()-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=Ys(s)?"video":"audio",u=Ys(s)?s.quality:s.bitrate;return e({message:`
|
|
7
7
|
[last ${o} selected] ${u}
|
|
8
8
|
`}),s}return i?.recordSwitch(t),t},ju=(n,e)=>Math.log(e)/Math.log(n),qu=({tuning:n,container:e,limits:t})=>{let i=n.containerSizeFactor;if(n.usePixelRatio&&window.devicePixelRatio){let r=window.devicePixelRatio;if(n.pixelRatioMultiplier)i*=n.pixelRatioMultiplier*(r-1)+1;else{let a=n.pixelRatioLogBase,[s=0,o=0,u=0]=n.pixelRatioLogCoefficients,l=ju(a,s*r+o)+u;Number.isFinite(l)&&(i*=l)}}return fa({highQualityLimit:n.highQualityLimit,trafficSavingLimit:n.trafficSavingLimit,limits:t})&&(i*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*i,height:e.height*i}:void 0,containerSizeFactor:i}},at=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{Ks(n,Js);let{containerSizeFactor:f,containerSizeLimit:g}=qu({container:e,tuning:i,limits:r}),y=i.considerPlaybackRate&&me(o)?o:1,R=n.filter(b=>!Gs(b.quality)).sort((b,x)=>Ws(b.quality,x.quality)?-1:1),E=R.at(-1)?.quality,L=R.at(0)?.quality,S=Jt({limits:r,lowestAvailableQuality:E,highestAvailableQuality:L}),T=y*Xs(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),A={},N=R.filter(b=>{let x=!0;if(g)if(b.size)x=b.size.width<=g.width&&b.size.height<=g.height;else{let Se=g&&Uu(g);x=Se?ga(b.quality,Se):!0}if(!x)return A[b.quality]="FitsContainer",!1;let F=h||t,be=me(F)&&isFinite(F)&&me(b.bitrate)?F-a>=b.bitrate*T:!0,ge=fa({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&r?.min===b.quality;if(!be&&!ge)return A[b.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&me(i.minBufferToSwitchUp)&&u&&!Gs(u.quality)&&(s??0)<i.minBufferToSwitchUp&&Ws(b.quality,u.quality))return A[b.quality]="Buffer",!1;if(!!d&&ba(b.quality,d)&&!ge)return A[b.quality]="DroppedFramesLimit",!1;if(!!p&&ba(b.quality,p)&&!ge)return A[b.quality]="StallsLimit",!1;let k=S||(qs(r?.max)||ga(b.quality,r.max))&&(qs(r?.min)||ba(b.quality,r.min)),U=me(c)&&!c?ga(b.quality,i.backgroundVideoQualityLimit):!0;return!k||!U?(A[b.quality]="FitsQualityLimits",!1):!0})[0];N&&N.bitrate&&Qu.next(N.bitrate);let _=N??R.at(-1)??n[0];return _.quality!==l?.last?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
@@ -122,4 +122,4 @@ void main(void) {
|
|
|
122
122
|
}
|
|
123
123
|
`;var Br=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Cr(this.params.fov,this.params.orientation),this.cameraRotationManager=new Vr(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(to,this.gl.VERTEX_SHADER),i=this.createShader(io,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,p=t+r;return[a,s,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as gd,now as ro,Subscription as Sd,filter as vd,combine as ao,ValueSubject as qa,isNonNullable as yd}from"@vkontakte/videoplayer-shared/evergreen";var Wa=class{constructor(){this.isSeeked$=new qa(!1);this.isBuffering$=new qa(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Sd;this.severeStallOccurred$=new qa(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(ao({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(vd(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(ao({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(gd(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a}=this.qualityLimitsOnStall,s=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=ro(),c=r&&this.currentStallsCount>=r,d=i&&l-this.lastUniqueVideoTrackSelectedTimestamp>=i+s&&l-u>=i+s&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,yd(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ro(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},so=Wa;import{combine as Td,map as Id,observeElementSize as Ed,Subscription as xd,ValueSubject as Ga,noop as kd}from"@vkontakte/videoplayer-shared/evergreen";var Or=class{constructor(){this.subscription=new xd;this.pipSize$=new Ga(void 0);this.videoSize$=new Ga(void 0);this.elementSize$=new Ga(void 0);this.pictureInPictureWindowRemoveEventListener=kd}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(Ed(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(Td({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Id(({videoSize:r,inPip:a,pipSize:s})=>a?s:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var At=class{constructor(e){this.subscription=new Rd;this.videoState=new w("stopped");this.droppedFramesManager=new Tr;this.stallsManager=new so;this.elementSizeManager=new Or;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Zt;this.audioTrackSwitchHistory=new Zt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let s=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-s,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&v(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return Ld(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Br(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Te(e.source.url),this.params=e,this.video=se(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Dr({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=ue(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:no.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(oo(l=>!!l.length),lo()).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(Ya(l=>l.to.state!=="none"),Qi());this.stallsManager.connect({isSeeked$:s,currentStallDuration$:this.player.currentStallDuration$.pipe(Qi()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(oo(uo),lo()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(Ya(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ce(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ye(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ee(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(wd(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Da(h));let m=[];for(let f of h.representations){let g=Nn(f);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Ca(p));let h=[];for(let m of p.representations){let f=On({...m,streamId:p.id});f&&(h.push(f),this.videoTracksMap.set(f,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=_n(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(Nr(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Md(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=[...this.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);uo(m)&&(this.stallsManager.lastVideoTrackSelected=m);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Qi()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Ca(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qi()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Da(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Ya(({to:l})=>l==="ready"),Qi());this.subscription.add(Nr(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,za(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Nr(o,this.player.state$.stateChangeEnded$,za(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Nr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,za(["init"])).pipe($d(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:A})=>A===r),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:A})=>A===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Be(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:A})=>A===f?.id)??this.audioStreamsMap.keys().next().value,y=0;if(g){if(s&&!i){let A=gr(s,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,A?.bitrate??-1/0)}if(o){let A=gr(o,c,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,A?.bitrate??-1/0)}}let R=at(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),E=i?R??s:s??R,L=g&&en(E,c,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),S=this.videoTracksMap.get(E)?.representation,T=L&&this.audioTracksMap.get(L)?.representation;if(S&&T)return[S,T];if(S&&!T&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:no.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ne(this.video),this.tracer.end()}};var ji=class extends At{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as co,interval as Dd,map as po}from"@vkontakte/videoplayer-shared/evergreen";var qi=class extends At{constructor(e){super(e),this.liveOffset=new Qe,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),r(this.player.liveLatency$,e.liveLatency$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe(po(a=>a.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(co({interval:Dd(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(co({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(po(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(a=>{if(a){let s=Fn(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 Wi,assertNonNullable as ho,debounce as Cd,ErrorCategory as _r,filter as Vd,isNonNullable as Bd,isNullable as Od,map as Fr,merge as Nd,Observable as _d,observableFrom as Fd,Subscription as Ud,videoSizeToQuality as Hd}from"@vkontakte/videoplayer-shared/evergreen";var we={};var Qt=(n,e)=>new _d(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Gi=class{constructor(e){this.subscription=new Ud;this.videoState=new w("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Wi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Wi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Wi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Wi(e)}break;default:Wi(t)}};this.textTracksManager=new Te(e.source.url),this.video=se(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),ne(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_r.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(we.Hls=r.default,we.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){ho(we.Hls,"hls.js not loaded"),this.hls=new we.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){ho(we.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:_r.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=ue(this.video),a=(l,c)=>this.subscription.add(l.subscribe(c,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ce(this.video,e.isLooped,i)),this.subscription.add(oe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ye(this.video,e.playbackRate,r.playbackRateState$,i)),a(Ee(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Fr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Qt(this.hls,we.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:_r.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Qt(this.hls,we.Events.MANIFEST_PARSED).pipe(Fr(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:m}=d,f=rt(d.attrs.QUALITY??"")??Hd({width:h,height:m});if(!f)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:p.toString(),quality:f,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:y,level:d}),c.push(y),c},[]))),t.availableVideoTracks$),a(Qt(this.hls,we.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),a(Qt(this.hls,we.Events.LEVEL_LOADING).pipe(Fr(({url:l})=>G(l))),t.hostname$),a(Qt(this.hls,we.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(et(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let s=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=Qt(this.hls,we.Events.LEVEL_SWITCHED).pipe(Fr(({level:l})=>s(this.hls.levels[l])));o.pipe(Vd(Bd)).subscribe(t.currentVideoTrack$,i),this.subscription.add(et(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),l=>{if(Od(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=Nd(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Fd(["init"])).pipe(Cd(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 le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_r.DOM,thrown:t}))||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0)}};var mo="X-Playback-Duration",Ka=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(mo)?parseInt(e.headers.get(mo),10):void 0};import{assertNever as Zd,combine as ec,debounce as tc,ErrorCategory as Qr,filter as ic,filterChanged as rc,isNonNullable as go,isNullable as jr,map as So,merge as ac,observableFrom as sc,Subscription as nc,ValueSubject as Ja,VideoQuality as oc}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Qd,getExponentialDelay as jd}from"@vkontakte/videoplayer-shared/evergreen";var qd=n=>{let e=null;if(n.QUALITY&&(e=rt(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Qd({width:t,height:i})}return e??null},Wd=(n,e)=>{let t=n.split(`
|
|
124
124
|
`),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),u=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=Object.fromEntries(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=qd(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[g,y]=l.RESOLUTION.split("x").map(R=>parseInt(R,10));g&&y&&(m={width:g,height:y})}let f=new URL(t[++a],e).toString();d&&i.push({id:c,quality:d,url:f,bandwidth:p,size:m,fps:h})}if(u){let l=Object.fromEntries(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&r.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Gd=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Xa=0,fo=async(n,e=n,t,i)=>{let a=await(await fetch(n,i)).text();Xa+=1;try{let{qualityManifests:s,textTracks:o}=Wd(a,e);return{qualityManifests:s,textTracks:o}}catch{if(Xa<=t.manifestRetryMaxCount)return await Gd(jd(Xa-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),fo(n,e,t)}return{qualityManifests:[],textTracks:[]}},Ur=fo;import{isNonNullable as Yd,Subscription as zd,throttle as Kd,ValueSubject as bo,Subject as Xd,ErrorCategory as Jd}from"@vkontakte/videoplayer-shared/evergreen";var Hr=class{constructor(e,t,i,r,a){this.subscription=new zd;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new bo(null);this.getCurrentTime$=new bo(null);this.error$=new Xd;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(Kd(1e3)).subscribe(s=>{this.processLiveTime(s)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),s=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(s,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
125
|
-
`),a=0;for(let s=0;s<r.length;++s){let o=r[s];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++s],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+c},url:l}),a=a+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Yd(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let s of t)if(s.time.from<=e&&s.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:s.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Jd.WTF,thrown:t,message:e})}};var Yi=class{constructor(e){this.subscription=new nc;this.videoState=new w("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ja([]);this.liveOffset=new Qe;this.manifestStartTime$=new Ja(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(v(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Zd(t)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:oc.INVARIANT,url:this.params.source.url};let t=(i,r)=>Ur(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Hr(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Te(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Qr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Qr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ja(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Qr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ue(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(oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ee(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(rc(),So(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&go(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(ec({startTime:this.manifestStartTime$.pipe(ic(go)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(So(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let s=ac(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,sc(["init"])).pipe(tc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(jr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=K(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(s),this.video.setAttribute("src",s),this.video.load(),Ka(s).then(o=>{if(!jr(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(jr(u)||!isFinite(u))&&fetch(s).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,s).toString();Ka(d).then(p=>{jr(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qr.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=K(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as uc,debounce as lc,ErrorCategory as Za,fromEvent as es,isNonNullable as dc,isNullable as cc,map as vo,merge as yo,observableFrom as To,Subscription as pc,ValueSubject as hc,VideoQuality as mc,clientChecker as fc}from"@vkontakte/videoplayer-shared/evergreen";var zi=class{constructor(e){this.subscription=new pc;this.videoState=new w("stopped");this.manifests$=new hc([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return uc(t)}};this.textTracksManager=new Te(e.source.url),this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:mc.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ur(K(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:Za.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Za.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ue(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(vo(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ce(this.video,t.isLooped,i)),this.subscription.add(oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&dc(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(G(m.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(vo(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!fc.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(yo(es(o,"addtrack"),es(o,"removetrack"),es(o,"change"),To(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=yo(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,To(["init"])).pipe(lc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(cc(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:s}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[s,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Za.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as bc,assertNonNullable as Io,debounce as gc,ErrorCategory as Eo,isHigherOrEqual as Sc,isLowerOrEqual as vc,isNonNullable as yc,merge as Tc,observableFrom as Ic,Subscription as Ec,map as xc}from"@vkontakte/videoplayer-shared/evergreen";var Ki=class{constructor(e){this.subscription=new Ec;this.videoState=new w("stopped");this.trackUrls={};this.textTracksManager=new Te;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?v(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return bc(e)}};this.params=e,this.video=se(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:Eo.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ue(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(xc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ce(this.video,t.isLooped,i)),this.subscription.add(oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ee(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&yc(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Tc(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ic(["init"])).pipe(gc(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),ne(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=Vi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Eo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let c=at(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),s=Object.values(this.trackUrls).map(l=>l.track);if(!r||!a||Jt({limits:e,lowestAvailableQuality:s.at(-1)?.quality,highestAvailableQuality:s[0].quality})){i();return}let o=e.max?vc(r,e.max):!0,u=e.min?Sc(r,e.min):!0;o&&u||i(e)}};import{assertNever as ko,debounce as Lc,merge as Po,observableFrom as wc,Subscription as $c,map as Ao,ValueSubject as Mc,ErrorCategory as is,VideoQuality as Rc}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as kc}from"@vkontakte/videoplayer-shared/evergreen";var xo=["stun:videostun.mycdn.me:80"],Pc=1e3,Ac=3,ts=()=>null,qr=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=ts;this.externalStopCallback=ts;this.externalErrorCallback=ts;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:xo}]};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:kc.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),Pc)}normalizeOptions(e={}){let t={stunServerList:xo,maxRetryNumber:Ac,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xi=class{constructor(e){this.videoState=new w("stopped");this.maxSeekBackTime$=new Mc(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return ko(e)}};this.subscription=new $c,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=se(e.container,e.tuning),this.liveStreamClient=new qr(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),ne(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:is.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};Po(this.videoState.stateChangeStarted$.pipe(Ao(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ao(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=ue(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Ee(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(oe(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 ko(s.to)}},i)).add(Po(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,wc(["init"])).pipe(Lc(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Rc.INVARIANT}),this.video.srcObject=e,v(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:is.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:is.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ji=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Zi,assertNonNullable as lt,ErrorCategory as Wr,filter as Do,isNonNullable as Co,isNullable as Fc,map as Uc,merge as Hc,once as Qc,Subject as he,Subscription as Vo,ValueSubject as $,flattenObject as Bo}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as Dc,map as Lo,Subscription as Cc,Subject as Vc}from"@vkontakte/videoplayer-shared/evergreen";var wo=n=>new Dc(e=>{let t=new Cc,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(Lo(({from:l,to:c})=>`${l}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(Lo(({type:l})=>l!==void 0)),s=new Vc,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>s.next(l),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as Bc,Subscription as Oc,combine as Nc,filter as Mo,once as Ro}from"@vkontakte/videoplayer-shared/evergreen";function $o(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as _c}from"@vkontakte/videoplayer-shared/evergreen";var jt=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Oc;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Mo(a=>!!a.type),Ro()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){_c.isSafari&&e!=="MPEG"||this.subscriptions.add(Nc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Mo(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),Ro()).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=$o();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:Bc.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var jc={chunkDuration:5e3,maxParallelRequests:5},er=class{constructor(e){this.current$=new $({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new $(0),duration$:new $(1/0),volume$:new $({muted:!1,volume:1}),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableVideoTracks$:new $([]),currentVideoTrack$:new $(void 0),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0),isAudioAvailable$:new $(!0),autoVideoTrackLimitingAvailable$:new $(!1),autoVideoTrackLimits$:new $(void 0),currentBuffer$:new $(void 0),isBuffering$:new $(!0),error$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new $(void 0),isLowLatency$:new $(!1),canChangePlaybackSpeed$:new $(!0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),liveLatency$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),inPiP$:new $(!1),inFullscreen$:new $(!1),element$:new $(void 0),elementVisible$:new $(!0),availableSources$:new $(void 0),is3DVideo$:new $(!1),playbackState$:new $(""),getCurrentTime$:new $(null)};this.subscription=new Vo;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=vn([...Tn(this.params.tuning),...yn(this.params.tuning)],this.params.tuning).filter(l=>Co(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Bo(a)),this.screenFormatsIterator=new Ji(a);let s=[...ka(!0),...ka(!1)];this.chromecastFormatsIterator=new Ji(s.filter(l=>Co(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&jt.isSupported()&&(this.volumeMultiplierManager=new jt(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Fc(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Wr.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}e.destroy();let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Zi(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return lt(o),new ji({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return lt(o),new qi({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return lt(o),Nt||!this.params.tuning.useHlsJs?new zi({...s,source:o}):new Gi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return lt(o),new Yi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return lt(o),new Ki({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return lt(o),new hn({...s,source:o,config:{...jc,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return lt(o),new Xi({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Zi(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return lt(o),new Yt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Zi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Zi(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Zi(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new Vo,t=!1,i=0;return e.add(Hc(this.providerOutput.error$.pipe(Do(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),wo({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Uc(r=>({id:`ProviderHangup:${r}`,category:Wr.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(Do(({to:a})=>a==="playing"),Qc()).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===Wr.NETWORK,u=r.category===Wr.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);s={...s,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}this.tracer.error("providerError",Bo(s))})),e}};import{fromEvent as Gr,once as qc,combine as Wc,Subscription as Oo,ValueSubject as rs,map as Gc,filter as Yc,isNonNullable as Yr,now as fe,safeStorage as as}from"@vkontakte/videoplayer-shared/evergreen";var zc=5e3,No="one_video_throughput",_o="one_video_rtt",tr=window.navigator.connection,Fo=()=>{let n=tr?.downlink;if(Yr(n)&&n!==10)return n*1e3},Uo=()=>{let n=tr?.rtt;if(Yr(n)&&n!==3e3)return n},Ho=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},ss=class n{constructor(e){this.subscription=new Oo;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(No)||(e.useBrowserEstimation?Fo():void 0)||zc,i=n.load(_o)??(e.useBrowserEstimation?Uo():void 0)??0;if(this.throughput$=new rs(t),this.rtt$=new rs(i),this.rttAdjustedThroughput$=new rs(Ho(t,i,e.rttPenaltyRequestSize)),this.throughput=It.getSmoothedValue(t,-1,e),this.rtt=It.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=Fo();s&&this.throughput.next(s);let o=Uo();Yr(o)&&this.rtt.next(o)};tr&&"onchange"in tr&&this.subscription.add(Gr(tr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{as.set(No,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{as.set(_o,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Wc({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Gc(({throughput:r,rtt:a})=>Ho(r,a,e.rttPenaltyRequestSize)),Yc(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 Oo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Gr(e,"progress").pipe(qc()).subscribe(a=>{t=a.loaded,i=fe()}));break;case 1:case 0:r.add(Gr(e,"loadstart").subscribe(()=>{t=0,i=fe()}));break}r.add(Gr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=fe(),u=s-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=fe(),s=0,o=fe(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,fe()-a,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=fe();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(s,m,1,t),s=d.byteLength,a=fe()}else s+=d.byteLength;o=fe()}else r+=d.byteLength,s+=d.byteLength,s>=this.tuningConfig.streamMinSampleSize&&fe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,fe()-o,this.concurrentDownloads.size),s=0,o=fe());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=as.get(e);if(Yr(t))return parseInt(t,10)??void 0}},Qo=ss;import{fillWithDefault as Kc,VideoQuality as zr}from"@vkontakte/videoplayer-shared/evergreen";var jo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:zr.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zr.Q_720P,trafficSavingLimit:zr.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zr.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1},qo=n=>({...Kc(n,jo),configName:[...n.configName??[],...jo.configName]});import{assertNonNullable as Kr,combine as ze,ErrorCategory as Xr,filter as re,filterChanged as O,fromEvent as os,isNonNullable as rp,isNullable as ap,Logger as sp,map as V,mapTo as zo,merge as dt,now as Jr,once as Ne,Subject as H,Subscription as Ko,tap as Xo,ValueSubject as I,isHigher as np,isInvariantQuality as Jo,flattenObject as ct,throttle as us,getTraceSubscriptionMethod as Zo,Tracer as op,InternalsExposure as up}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Xc,map as Jc,filter as Wo,isNonNullable as Zc}from"@vkontakte/videoplayer-shared/evergreen";var ns=({seekState:n,position$:e})=>Xc(n.stateChangeEnded$.pipe(Jc(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Wo(Zc)),e.pipe(Wo(()=>n.getState().state==="none")));import{assertNonNullable as ep}from"@vkontakte/videoplayer-shared/evergreen";var Go=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return ep(e,`Wrong container or containerId {${n.container}}`),e};import{filter as tp,once as ip}from"@vkontakte/videoplayer-shared/evergreen";var Yo=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(tp(r=>r.length>0),ip()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Zr=class{constructor(e={configName:[]},t=op.createRootTracer(!1)){this.subscription=new Ko;this.logger=new sp;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new I(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new w("stopped"),seekState:new w({state:"none"}),volume:new w({volume:1,muted:!1}),videoTrack:new w(void 0),videoStream:new w(void 0),audioStream:new w(void 0),autoVideoTrackSwitching:new w(!0),autoVideoTrackLimits:new w({}),isLooped:new w(!1),isLowLatency:new w(!1),playbackRate:new w(1),externalTextTracks:new w([]),internalTextTracks:new w([]),currentTextTrack:new w(void 0),textTrackCuesSettings:new w({}),cameraOrientation:new w({x:0,y:0})};this.info={playbackState$:new I("stopped"),position$:new I(0),duration$:new I(1/0),muted$:new I(!1),volume$:new I(1),availableVideoStreams$:new I([]),currentVideoStream$:new I(void 0),availableQualities$:new I([]),availableQualitiesFps$:new I({}),currentQuality$:new I(void 0),isAutoQualityEnabled$:new I(!0),autoQualityLimitingAvailable$:new I(!1),autoQualityLimits$:new I({}),predefinedQualityLimitType$:new I("unknown"),availableAudioStreams$:new I([]),currentAudioStream$:new I(void 0),availableAudioTracks$:new I([]),isAudioAvailable$:new I(!0),currentPlaybackRate$:new I(1),currentBuffer$:new I({start:0,end:0}),isBuffering$:new I(!0),isStalled$:new I(!1),isEnded$:new I(!1),isLooped$:new I(!1),isLive$:new I(void 0),canChangePlaybackSpeed$:new I(void 0),atLiveEdge$:new I(void 0),atLiveDurationEdge$:new I(void 0),liveTime$:new I(void 0),liveBufferTime$:new I(void 0),liveLatency$:new I(void 0),currentFormat$:new I(void 0),availableTextTracks$:new I([]),currentTextTrack$:new I(void 0),throughputEstimation$:new I(void 0),rttEstimation$:new I(void 0),videoBitrate$:new I(void 0),hostname$:new I(void 0),httpConnectionType$:new I(void 0),httpConnectionReused$:new I(void 0),surface$:new I("none"),chromecastState$:new I("NOT_AVAILABLE"),chromecastDeviceName$:new I(void 0),intrinsicVideoSize$:new I(void 0),availableSources$:new I(void 0),is3DVideo$:new I(!1),currentVideoSegmentLength$:new I(0),currentAudioSegmentLength$:new I(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new I(void 0),tuningConfigName$:new I([]),enableDebugTelemetry$:new I(!1),dumpTelemetry:Hs,getCurrentTime$:new I(null)};if(this.initLogs(),this.tuning=qo(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new cr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Qo(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new up("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let s=Reflect.get(i,r,a);return typeof s!="function"?s:(...o)=>{try{return s.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Xr.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",ct(i)),this.domContainer=Go(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new er({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ai()?(this.tracer.log("request play from hidden tab"),os(document,"visibilitychange").pipe(Ne()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;return e>=i&&!r&&(a=i-.2),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),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){Kr(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(re(i=>i.length>0),Ne()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",ct(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}return this.setAutoQualityLimits(r),this}setPlaybackRate(e){Kr(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",ct(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Yo(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(ap(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return rp(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(dt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ma({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),Ne()).subscribe(()=>{this.initedAt=Jr(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",ct(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Xr.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ne()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ct(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(s=>s.destination),O()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ze({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(V(({availableVideoTracks:s,currentVideoStream:o})=>s.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Jo(u)?1:Jo(l)?-1:np(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(O()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(O((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(O((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(O()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(O()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(O()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(s=>{this.desiredState.autoVideoTrackLimits.setState(s??{})})).add(e.providerOutput.currentBuffer$.pipe(V(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ze({hasLiveOffsetByPaused:dt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(s=>s.to),O(),V(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ze({atLiveEdge:ze({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ns({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:s,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return s&&Math.abs(o)<l/1e3}),O(),Xo(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(ze({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),O(),Xo(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(s=>s.muted),O()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(s=>s.volume),O()).subscribe(this.info.volume$)).add(ns({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(dt(e.providerOutput.endedEvent$.pipe(zo(!0)),e.providerOutput.seekedEvent$.pipe(zo(!1))).pipe(O()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(V(s=>({id:s?`No${s}`:"NoProviders",category:Xr.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Ne(),V(s=>s??Jr()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ne(),V(()=>Jr()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ne(),V(()=>Jr()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new I(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new I(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:s})=>s==="playing"),Ne()).subscribe(()=>i.next(!1)));let r=0,a=dt(e.providerOutput.isBuffering$,t,i).pipe(V(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),O());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(dt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(dt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?s?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(V(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Ko;this.subscription.add(t),this.subscription.add(e.current$.pipe(O((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),Ne()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=at(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(dt(this.desiredState.videoTrack.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(V(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Kr(this.providerContainer),Kr(e),Us(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Fs(t)),this.providerContainer.current$.subscribe(({type:t})=>Xt("provider",t)),e.duration$.subscribe(t=>Xt("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),Ne()).subscribe(t=>Xt("tracks",t)),this.events.fatalError$.subscribe(new ee("fatalError")),this.events.managedError$.subscribe(new ee("managedError")),e.position$.subscribe(new ee("position")),e.currentVideoTrack$.pipe(V(t=>t?.quality)).subscribe(new ee("quality")),this.info.currentBuffer$.subscribe(new ee("buffer")),e.isBuffering$.subscribe(new ee("isBuffering"))].forEach(t=>this.subscription.add(t)),Xt("codecs",Sn())}initTracerSubscription(){let e=Zo(this.tracer.log.bind(this.tracer)),t=Zo(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(O()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ze({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),O((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(i=>i>0),O()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(i=>i>0),O()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ze({currentBuffer:this.info.currentBuffer$.pipe(re(i=>i.end>0),O((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(O())}).pipe(us(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(O()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(O()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(O()).subscribe(e("canChangePlaybackSpeed"))).add(ze({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),us(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(O(),re(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(O(),re(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(O()).subscribe(e("muted"))).add(this.info.volume$.pipe(O()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(O(),re(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ze({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:i,rtt:r})=>!!i&&!!r),us(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(O(),re(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:Xr.DOM,message:String(r)})})};this.subscription.add(dt(os(document,"visibilitychange"),os(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",ct({quality:t,availableTracks:ct(e),track:ct(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as GP,Observable as YP,Subject as zP,ValueSubject as KP,VideoQuality as XP}from"@vkontakte/videoplayer-shared/evergreen";var JP=`@vkontakte/videoplayer-core@${ds}`;export{ur as ChromecastState,ia as HttpConnectionType,YP as Observable,ae as PlaybackState,Zr as Player,lr as PredefinedQualityLimits,JP as SDK_VERSION,zP as Subject,GP as Subscription,ra as Surface,ds as VERSION,KP as ValueSubject,Ze as VideoFormat,XP as VideoQuality};
|
|
125
|
+
`),a=0;for(let s=0;s<r.length;++s){let o=r[s];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++s],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+c},url:l}),a=a+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Yd(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let s of t)if(s.time.from<=e&&s.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:s.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Jd.WTF,thrown:t,message:e})}};var Yi=class{constructor(e){this.subscription=new nc;this.videoState=new w("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ja([]);this.liveOffset=new Qe;this.manifestStartTime$=new Ja(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(v(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Zd(t)}};this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:oc.INVARIANT,url:this.params.source.url};let t=(i,r)=>Ur(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Hr(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Te(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Qr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Qr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ja(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Qr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ue(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(oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ee(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(rc(),So(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&go(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(ec({startTime:this.manifestStartTime$.pipe(ic(go)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(So(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let s=ac(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,sc(["init"])).pipe(tc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(jr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=K(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(s),this.video.setAttribute("src",s),this.video.load(),Ka(s).then(o=>{if(!jr(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(jr(u)||!isFinite(u))&&fetch(s).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,s).toString();Ka(d).then(p=>{jr(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qr.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=K(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as uc,debounce as lc,ErrorCategory as Za,fromEvent as es,isNonNullable as dc,isNullable as cc,map as vo,merge as yo,observableFrom as To,Subscription as pc,ValueSubject as hc,VideoQuality as mc,clientChecker as fc}from"@vkontakte/videoplayer-shared/evergreen";var zi=class{constructor(e){this.subscription=new pc;this.videoState=new w("stopped");this.manifests$=new hc([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return uc(t)}};this.textTracksManager=new Te(e.source.url),this.params=e,this.video=se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:mc.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ur(K(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:Za.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Za.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ue(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(vo(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ce(this.video,t.isLooped,i)),this.subscription.add(oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&dc(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(G(m.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(vo(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!fc.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(yo(es(o,"addtrack"),es(o,"removetrack"),es(o,"change"),To(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=yo(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,To(["init"])).pipe(lc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){let e=this.selectManifest();if(cc(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:s}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[s,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Za.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as bc,assertNonNullable as Io,debounce as gc,ErrorCategory as Eo,isHigherOrEqual as Sc,isLowerOrEqual as vc,isNonNullable as yc,merge as Tc,observableFrom as Ic,Subscription as Ec,map as xc}from"@vkontakte/videoplayer-shared/evergreen";var Ki=class{constructor(e){this.subscription=new Ec;this.videoState=new w("stopped");this.trackUrls={};this.textTracksManager=new Te;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?v(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return bc(e)}};this.params=e,this.video=se(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:Eo.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ue(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(xc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ce(this.video,t.isLooped,i)),this.subscription.add(oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ye(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ee(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&yc(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Tc(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ic(["init"])).pipe(gc(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),ne(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=Vi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Eo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let c=at(s,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),s=Object.values(this.trackUrls).map(l=>l.track);if(!r||!a||Jt({limits:e,lowestAvailableQuality:s.at(-1)?.quality,highestAvailableQuality:s[0].quality})){i();return}let o=e.max?vc(r,e.max):!0,u=e.min?Sc(r,e.min):!0;o&&u||i(e)}};import{assertNever as ko,debounce as Lc,merge as Po,observableFrom as wc,Subscription as $c,map as Ao,ValueSubject as Mc,ErrorCategory as is,VideoQuality as Rc}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as kc}from"@vkontakte/videoplayer-shared/evergreen";var xo=["stun:videostun.mycdn.me:80"],Pc=1e3,Ac=3,ts=()=>null,qr=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=ts;this.externalStopCallback=ts;this.externalErrorCallback=ts;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:xo}]};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:kc.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),Pc)}normalizeOptions(e={}){let t={stunServerList:xo,maxRetryNumber:Ac,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xi=class{constructor(e){this.videoState=new w("stopped");this.maxSeekBackTime$=new Mc(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return ko(e)}};this.subscription=new $c,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=se(e.container,e.tuning),this.liveStreamClient=new qr(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),ne(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:is.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};Po(this.videoState.stateChangeStarted$.pipe(Ao(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ao(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=ue(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Ee(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(oe(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 ko(s.to)}},i)).add(Po(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,wc(["init"])).pipe(Lc(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Rc.INVARIANT}),this.video.srcObject=e,v(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:is.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:is.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ji=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Zi,assertNonNullable as lt,ErrorCategory as Wr,filter as Do,isNonNullable as Co,isNullable as Fc,map as Uc,merge as Hc,once as Qc,Subject as he,Subscription as Vo,ValueSubject as $,flattenObject as Bo}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as Dc,map as Lo,Subscription as Cc,Subject as Vc}from"@vkontakte/videoplayer-shared/evergreen";var wo=n=>new Dc(e=>{let t=new Cc,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(Lo(({from:l,to:c})=>`${l}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(Lo(({type:l})=>l!==void 0)),s=new Vc,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>s.next(l),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as Bc,Subscription as Oc,combine as Nc,filter as Mo,once as Ro}from"@vkontakte/videoplayer-shared/evergreen";function $o(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as _c}from"@vkontakte/videoplayer-shared/evergreen";var jt=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Oc;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Mo(a=>!!a.type),Ro()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){_c.isSafari&&e!=="MPEG"||this.subscriptions.add(Nc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Mo(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),Ro()).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=$o();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:Bc.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var jc={chunkDuration:5e3,maxParallelRequests:5},er=class{constructor(e){this.current$=new $({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new $(0),duration$:new $(1/0),volume$:new $({muted:!1,volume:1}),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableVideoTracks$:new $([]),currentVideoTrack$:new $(void 0),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0),isAudioAvailable$:new $(!0),autoVideoTrackLimitingAvailable$:new $(!1),autoVideoTrackLimits$:new $(void 0),currentBuffer$:new $(void 0),isBuffering$:new $(!0),error$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new $(void 0),isLowLatency$:new $(!1),canChangePlaybackSpeed$:new $(!0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),liveLatency$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),inPiP$:new $(!1),inFullscreen$:new $(!1),element$:new $(void 0),elementVisible$:new $(!0),availableSources$:new $(void 0),is3DVideo$:new $(!1),playbackState$:new $(""),getCurrentTime$:new $(null)};this.subscription=new Vo;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=vn([...Tn(this.params.tuning),...yn(this.params.tuning)],this.params.tuning).filter(l=>Co(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Bo(a)),this.screenFormatsIterator=new Ji(a);let s=[...ka(!0),...ka(!1)];this.chromecastFormatsIterator=new Ji(s.filter(l=>Co(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&jt.isSupported()&&(this.volumeMultiplierManager=new jt(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Fc(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Wr.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}e.destroy();let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Zi(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return lt(o),new ji({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return lt(o),new qi({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return lt(o),Nt||!this.params.tuning.useHlsJs?new zi({...s,source:o}):new Gi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return lt(o),new Yi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return lt(o),new Ki({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return lt(o),new hn({...s,source:o,config:{...jc,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return lt(o),new Xi({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Zi(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return lt(o),new Yt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Zi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Zi(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Zi(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new Vo,t=!1,i=0;return e.add(Hc(this.providerOutput.error$.pipe(Do(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),wo({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Uc(r=>({id:`ProviderHangup:${r}`,category:Wr.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(Do(({to:a})=>a==="playing"),Qc()).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===Wr.NETWORK,u=r.category===Wr.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);s={...s,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}this.tracer.error("providerError",Bo(s))})),e}};import{fromEvent as Gr,once as qc,combine as Wc,Subscription as Oo,ValueSubject as rs,map as Gc,filter as Yc,isNonNullable as Yr,now as fe,safeStorage as as}from"@vkontakte/videoplayer-shared/evergreen";var zc=5e3,No="one_video_throughput",_o="one_video_rtt",tr=window.navigator.connection,Fo=()=>{let n=tr?.downlink;if(Yr(n)&&n!==10)return n*1e3},Uo=()=>{let n=tr?.rtt;if(Yr(n)&&n!==3e3)return n},Ho=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},ss=class n{constructor(e){this.subscription=new Oo;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(No)||(e.useBrowserEstimation?Fo():void 0)||zc,i=n.load(_o)??(e.useBrowserEstimation?Uo():void 0)??0;if(this.throughput$=new rs(t),this.rtt$=new rs(i),this.rttAdjustedThroughput$=new rs(Ho(t,i,e.rttPenaltyRequestSize)),this.throughput=It.getSmoothedValue(t,-1,e),this.rtt=It.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=Fo();s&&this.throughput.next(s);let o=Uo();Yr(o)&&this.rtt.next(o)};tr&&"onchange"in tr&&this.subscription.add(Gr(tr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{as.set(No,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{as.set(_o,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Wc({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Gc(({throughput:r,rtt:a})=>Ho(r,a,e.rttPenaltyRequestSize)),Yc(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 Oo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Gr(e,"progress").pipe(qc()).subscribe(a=>{t=a.loaded,i=fe()}));break;case 1:case 0:r.add(Gr(e,"loadstart").subscribe(()=>{t=0,i=fe()}));break}r.add(Gr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=fe(),u=s-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=fe(),s=0,o=fe(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,fe()-a,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=fe();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(s,m,1,t),s=d.byteLength,a=fe()}else s+=d.byteLength;o=fe()}else r+=d.byteLength,s+=d.byteLength,s>=this.tuningConfig.streamMinSampleSize&&fe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,fe()-o,this.concurrentDownloads.size),s=0,o=fe());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=as.get(e);if(Yr(t))return parseInt(t,10)??void 0}},Qo=ss;import{fillWithDefault as Kc,VideoQuality as zr}from"@vkontakte/videoplayer-shared/evergreen";var jo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:zr.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:zr.Q_720P,trafficSavingLimit:zr.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zr.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1},qo=n=>({...Kc(n,jo),configName:[...n.configName??[],...jo.configName]});import{assertNonNullable as Kr,combine as ze,ErrorCategory as Xr,filter as re,filterChanged as O,fromEvent as os,isNonNullable as rp,isNullable as ap,Logger as sp,map as V,mapTo as zo,merge as dt,now as Jr,once as Ne,Subject as H,Subscription as Ko,tap as Xo,ValueSubject as I,isHigher as np,isInvariantQuality as Jo,flattenObject as ct,throttle as us,getTraceSubscriptionMethod as Zo,Tracer as op,InternalsExposure as up}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Xc,map as Jc,filter as Wo,isNonNullable as Zc}from"@vkontakte/videoplayer-shared/evergreen";var ns=({seekState:n,position$:e})=>Xc(n.stateChangeEnded$.pipe(Jc(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Wo(Zc)),e.pipe(Wo(()=>n.getState().state==="none")));import{assertNonNullable as ep}from"@vkontakte/videoplayer-shared/evergreen";var Go=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return ep(e,`Wrong container or containerId {${n.container}}`),e};import{filter as tp,once as ip}from"@vkontakte/videoplayer-shared/evergreen";var Yo=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(tp(r=>r.length>0),ip()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Zr=class{constructor(e={configName:[]},t=op.createRootTracer(!1)){this.subscription=new Ko;this.logger=new sp;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new I(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new w("stopped"),seekState:new w({state:"none"}),volume:new w({volume:1,muted:!1}),videoTrack:new w(void 0),videoStream:new w(void 0),audioStream:new w(void 0),autoVideoTrackSwitching:new w(!0),autoVideoTrackLimits:new w({}),isLooped:new w(!1),isLowLatency:new w(!1),playbackRate:new w(1),externalTextTracks:new w([]),internalTextTracks:new w([]),currentTextTrack:new w(void 0),textTrackCuesSettings:new w({}),cameraOrientation:new w({x:0,y:0})};this.info={playbackState$:new I("stopped"),position$:new I(0),duration$:new I(1/0),muted$:new I(!1),volume$:new I(1),availableVideoStreams$:new I([]),currentVideoStream$:new I(void 0),availableQualities$:new I([]),availableQualitiesFps$:new I({}),currentQuality$:new I(void 0),isAutoQualityEnabled$:new I(!0),autoQualityLimitingAvailable$:new I(!1),autoQualityLimits$:new I({}),predefinedQualityLimitType$:new I("unknown"),availableAudioStreams$:new I([]),currentAudioStream$:new I(void 0),availableAudioTracks$:new I([]),isAudioAvailable$:new I(!0),currentPlaybackRate$:new I(1),currentBuffer$:new I({start:0,end:0}),isBuffering$:new I(!0),isStalled$:new I(!1),isEnded$:new I(!1),isLooped$:new I(!1),isLive$:new I(void 0),canChangePlaybackSpeed$:new I(void 0),atLiveEdge$:new I(void 0),atLiveDurationEdge$:new I(void 0),liveTime$:new I(void 0),liveBufferTime$:new I(void 0),liveLatency$:new I(void 0),currentFormat$:new I(void 0),availableTextTracks$:new I([]),currentTextTrack$:new I(void 0),throughputEstimation$:new I(void 0),rttEstimation$:new I(void 0),videoBitrate$:new I(void 0),hostname$:new I(void 0),httpConnectionType$:new I(void 0),httpConnectionReused$:new I(void 0),surface$:new I("none"),chromecastState$:new I("NOT_AVAILABLE"),chromecastDeviceName$:new I(void 0),intrinsicVideoSize$:new I(void 0),availableSources$:new I(void 0),is3DVideo$:new I(!1),currentVideoSegmentLength$:new I(0),currentAudioSegmentLength$:new I(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new I(void 0),tuningConfigName$:new I([]),enableDebugTelemetry$:new I(!1),dumpTelemetry:Hs,getCurrentTime$:new I(null)};if(this.initLogs(),this.tuning=qo(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new cr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Qo(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new up("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let s=Reflect.get(i,r,a);return typeof s!="function"?s:(...o)=>{try{return s.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Xr.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",ct(i)),this.domContainer=Go(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new er({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ai()?(this.tracer.log("request play from hidden tab"),os(document,"visibilitychange").pipe(Ne()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;return e>=i&&!r&&(a=i-.2),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),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){Kr(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(re(i=>i.length>0),Ne()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",ct(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}return this.setAutoQualityLimits(r),this}setPlaybackRate(e){Kr(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",ct(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Yo(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(ap(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return rp(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(dt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ma({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),Ne()).subscribe(()=>{this.initedAt=Jr(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",ct(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Xr.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ne()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",ct(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(s=>s.destination),O()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ze({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(V(({availableVideoTracks:s,currentVideoStream:o})=>s.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Jo(u)?1:Jo(l)?-1:np(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(O()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(O((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(O((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(O()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(O()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(O()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(s=>{this.desiredState.autoVideoTrackLimits.setState(s??{})})).add(e.providerOutput.currentBuffer$.pipe(V(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ze({hasLiveOffsetByPaused:dt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(s=>s.to),O(),V(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ze({atLiveEdge:ze({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:ns({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:s,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return s&&Math.abs(o)<l/1e3}),O(),Xo(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(ze({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),O(),Xo(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(s=>s.muted),O()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(s=>s.volume),O()).subscribe(this.info.volume$)).add(ns({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(dt(e.providerOutput.endedEvent$.pipe(zo(!0)),e.providerOutput.seekedEvent$.pipe(zo(!1))).pipe(O()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(V(s=>({id:s?`No${s}`:"NoProviders",category:Xr.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Ne(),V(s=>s??Jr()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ne(),V(()=>Jr()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ne(),V(()=>Jr()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new I(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new I(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:s})=>s==="playing"),Ne()).subscribe(()=>i.next(!1)));let r=0,a=dt(e.providerOutput.isBuffering$,t,i).pipe(V(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),O());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(dt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(dt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?s?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(V(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Ko;this.subscription.add(t),this.subscription.add(e.current$.pipe(O((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),Ne()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=at(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(dt(this.desiredState.videoTrack.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(V(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Kr(this.providerContainer),Kr(e),Us(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Fs(t)),this.providerContainer.current$.subscribe(({type:t})=>Xt("provider",t)),e.duration$.subscribe(t=>Xt("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),Ne()).subscribe(t=>Xt("tracks",t)),this.events.fatalError$.subscribe(new ee("fatalError")),this.events.managedError$.subscribe(new ee("managedError")),e.position$.subscribe(new ee("position")),e.currentVideoTrack$.pipe(V(t=>t?.quality)).subscribe(new ee("quality")),this.info.currentBuffer$.subscribe(new ee("buffer")),e.isBuffering$.subscribe(new ee("isBuffering"))].forEach(t=>this.subscription.add(t)),Xt("codecs",Sn())}initTracerSubscription(){let e=Zo(this.tracer.log.bind(this.tracer)),t=Zo(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(O()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ze({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),O((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(i=>i>0),O()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(i=>i>0),O()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ze({currentBuffer:this.info.currentBuffer$.pipe(re(i=>i.end>0),O((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(O())}).pipe(us(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(O()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(O()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(O()).subscribe(e("canChangePlaybackSpeed"))).add(ze({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),us(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(O(),re(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(O(),re(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(O()).subscribe(e("muted"))).add(this.info.volume$.pipe(O()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(O(),re(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ze({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:i,rtt:r})=>!!i&&!!r),us(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(O(),re(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:Xr.DOM,message:String(r)})})};this.subscription.add(dt(os(document,"visibilitychange"),os(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",ct({quality:t,availableTracks:ct(e),track:ct(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as GP,Observable as YP,Subject as zP,ValueSubject as KP,VideoQuality as XP}from"@vkontakte/videoplayer-shared/evergreen";var JP=`@vkontakte/videoplayer-core@${ds}`;export{ur as ChromecastState,ia as HttpConnectionType,YP as Observable,ae as PlaybackState,Zr as Player,lr as PredefinedQualityLimits,JP as SDK_VERSION,zP as Subject,GP as Subscription,ra as Surface,ds as VERSION,KP as ValueSubject,Ze as VideoFormat,XP as VideoQuality};
|