@vkontakte/videoplayer-core 2.0.111-dev.974e99b3.0 → 2.0.111-dev.ae3e5b42.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 +15 -15
- package/es2015.esm.js +15 -15
- package/es2018.cjs.js +10 -10
- package/es2018.esm.js +10 -10
- package/esnext.cjs.js +13 -13
- package/esnext.esm.js +12 -12
- package/evergreen.esm.js +14 -14
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +0 -6
- package/types/providers/DashProvider/lib/LiveTextManager.d.ts +21 -0
- package/types/providers/DashProvider/lib/player.d.ts +3 -1
- package/types/providers/DashProvider/lib/types.d.ts +6 -0
- package/types/providers/DashProvider/lib/utils.d.ts +3 -5
package/evergreen.esm.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.111-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.111-dev.ae3e5b42.0
|
|
3
|
+
* Wed, 02 Oct 2024 09:38:29 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-111/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Ua="2.0.111-dev.974e99b3.0";var Z=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Z||{}),Ve=(g=>(g.MPEG="MPEG",g.DASH="DASH",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_STREAMS="DASH_STREAMS",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(Ve||{});var Fi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Fi||{}),Vr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Vr||{});var Or=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Or||{});import{assertNever as Ya,assertNonNullable as Mo,isNonNullable as Ui,ValueSubject as _r,Subject as Ro,Subscription as Do,merge as Co,observableFrom as Bo,fromEvent as Qa,map as ja,tap as Ga,filterChanged as Vo,isNullable as Nr,ErrorCategory as Wa}from"@vkontakte/videoplayer-shared";var Ha=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Hi=class{constructor(e){this.connection$=new _r(void 0);this.castState$=new _r("NOT_AVAILABLE");this.errorEvent$=new Ro;this.realCastState$=new _r("NOT_AVAILABLE");this.subscription=new Do;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=Ui(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||Ha("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Wa.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(){Ui(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Nr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Nr(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Qa(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 Ya(r.sessionState)}})).add(Co(Qa(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ga(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),ja(r=>r.castState)),Bo([i.getCastState()])).pipe(Vo(),ja(Oo),Ga(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=Ui(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();Mo(o);let d=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;(Nr(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ui(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:Wa.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Oo=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 Ya(n)}};import{assertNever as qa}from"@vkontakte/videoplayer-shared";var Y=(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:qa(t)}return n},Fr=(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:qa(e)}};var y=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as _o,Subject as Qi,merge as za}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Qi;this.transitionEnded$=new Qi;this.transitionUpdated$=new Qi;this.forceChanged$=new Qi;this.stateChangeStarted$=za(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=za(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||_o(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 No}from"@vkontakte/videoplayer-shared";var Ka=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 No(n)}};import{assertNever as St,assertNonNullable as Ze,debounce as Ja,ErrorCategory as Xa,fromEvent as et,isNonNullable as Za,map as es,merge as ts,observableFrom as Fo,Subject as Uo,Subscription as Ur,timeout as Ho,getHighestQuality as Qo}from"@vkontakte/videoplayer-shared";var jo=5,Go=5,Wo=500,is=7e3,Ct=class{constructor(e){this.subscription=new Ur;this.loadMediaTimeoutSubscription=new Ur;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:St(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:St(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:St(e)}break}default:St(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ka(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 Ur;this.subscription.add(e),this.subscription.add(ts(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 Uo;e.add(r.pipe(Ja(Wo)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(et(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)>jo)&&r.next(o),a=o})),e.add(et(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(et(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(et(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(et(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(),d=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==d&&this.params.output.isBuffering$.next(d),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Go&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),y(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:St(s)}}),t(et(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(et(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=ts(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Fo(["init"])).pipe(Ja(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&y(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let u=t[e];Ze(u);let c=Qo(Object.keys(u));Ze(c);let l=u[c];Ze(l),i=l,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];Ze(u),i=u.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 u=t[e];Ze(u),i=u.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];Ze(u),i=u.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];Ze(u),i=Y(u.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Xa.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return St(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:d}=this.params.meta;return Za(o)&&(s.metadata.title=o),Za(d)&&(s.metadata.subtitle=d),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(Ho(is).subscribe(()=>a(`timeout(${is})`)))});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:Xa.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";import{clearVideoElement as Yo}from"@vkontakte/videoplayer-shared";var rs=n=>{try{n.pause(),n.playbackRate=0,Yo(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as qo,Subscription as zo}from"@vkontakte/videoplayer-shared";var Hr=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)}},Qr=window.WeakMap?new WeakMap:new Hr,jr=window.WeakMap?new WeakMap:new Map,Ko=(n,e=20)=>{let t=0;return qo(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ee=(n,{audioVideoSyncRate:e})=>{let t=n.querySelector("video"),i=!!t;t?as(t):(t=document.createElement("video"),n.appendChild(t)),Qr.set(t,i);let r=new zo;return r.add(Ko(t,e)),jr.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},te=n=>{jr.get(n)?.unsubscribe(),jr.delete(n);let t=Qr.get(n);Qr.delete(n),t?as(n):rs(n)};import{assertNonNullable as Bt,isNonNullable as ke,isNullable as Zo,fromEvent as gt,merge as ss,observableFrom as ns,filterChanged as os,map as Vt,Subject as us,Subscription as eu,ValueSubject as tu,ErrorCategory as iu}from"@vkontakte/videoplayer-shared";import{isNonNullable as Gr,isNullable as Jo,Subscription as Xo}from"@vkontakte/videoplayer-shared";var ji=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),d=Jo(r),u=new Xo;return r&&u.add(r.subscribe(c=>{let l=n.getState();i(c,l)&&n.setState(c)},a)),i(o,s)||(t(s),d&&n.setState(s)),u.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),d&&n.setState(c.to)},a)),u},xe=(n,e,t)=>ji(e,()=>n.loop,i=>{Gr(i)&&(n.loop=i)},{onError:t}),ie=(n,e,t,i)=>ji(e,()=>({muted:n.muted,volume:n.volume}),r=>{Gr(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}),ce=(n,e,t,i)=>ji(e,()=>n.playbackRate,r=>{Gr(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Oe=ji;var ru=n=>["__",n.language,n.label].join("|"),au=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Wr=class n{constructor(){this.available$=new us;this.current$=new tu(void 0);this.error$=new us;this.subscription=new eu;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:iu.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(Oe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{ke(a)&&this.setInternal(a)},{equal:(a,s)=>ke(a)&&ke(s)&&a.length===s.length&&a.every(({id:o},d)=>o===s[d].id),changed$:this.available$.pipe(Vt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Oe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{ke(a)&&this.setExternal(a)},{equal:(a,s)=>ke(a)&&ke(s)&&a.length===s.length&&a.every(({id:o},d)=>o===s[d].id),changed$:this.available$.pipe(Vt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Oe(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(Oe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Bt(this.video);let{textTracks:e}=this.video;this.subscription.add(gt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ss(gt(e,"addtrack"),gt(e,"removetrack"),ns(["init"])).pipe(Vt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),os((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(ss(gt(e,"change"),ns(["init"])).pipe(Vt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Vt(i=>i&&this.htmlTextTrackToITextTrack(i).id),os()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(gt(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(gt(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;ke(t.align)&&(r.align=t.align),ke(t.position)&&(r.position=t.position),ke(t.size)&&(r.size=t.size),ke(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Bt(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:ru(e),a=this.externalTracks.has(r),s=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){Bt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Zo(e)||!au(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){Bt(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Bt(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)}},pe=Wr;var Pe=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 ds=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Yr=n=>{let e=ds(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},ls=n=>{let e=ds(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as he,map as _e,merge as ps,filterChanged as nu,isNonNullable as hs,Subject as ou,filter as ms,mapTo as fs,combine as uu,once as du,ErrorCategory as lu,ValueSubject as bs,clientChecker as cu}from"@vkontakte/videoplayer-shared";var su=3,cs=(n,e,t=su)=>{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 d=a-1;d>=0;d--)n.end(d)+t>=i&&(i=n.start(d));for(let d=a+1;d<n.length;d++)n.start(d)-t<=r&&(r=n.end(d))}}return{from:i,to:r}};var re=n=>{let e=g=>he(n,g).pipe(fs(void 0)),i=ps(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>he(n,g))).pipe(_e(g=>g.type==="ended"?n.readyState<2:n.readyState<3),nu()),r=ps(he(n,"progress"),he(n,"timeupdate")).pipe(_e(()=>cs(n.buffered,n.currentTime))),a=cu.isSafari?uu({play:e("play").pipe(du()),playing:e("playing")}).pipe(fs(void 0)):e("playing"),s=he(n,"volumechange").pipe(_e(()=>({muted:n.muted,volume:n.volume}))),o=he(n,"ratechange").pipe(_e(()=>n.playbackRate)),d=he(n,"error").pipe(ms(()=>!!(n.error||n.played.length)),_e(()=>{let g=n.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:lu.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:n.error??void 0}})),u=he(n,"timeupdate").pipe(_e(()=>n.currentTime)),c=new ou,l=.3,p;u.subscribe(g=>{n.loop&&hs(p)&&hs(g)&&p>=n.duration-l&&g<=l&&c.next(p),p=g});let h=e("pause").pipe(ms(()=>!n.error&&p!==n.duration)),m=he(n,"enterpictureinpicture"),f=he(n,"leavepictureinpicture"),S=new bs(ls(n));m.subscribe(()=>S.next(!0)),f.subscribe(()=>S.next(!1));let A=new bs(Yr(n));return he(n,"fullscreenchange").pipe(_e(()=>Yr(n))).subscribe(A),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:he(n,"durationchange").pipe(_e(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:S,inFullscreen$:A}};import{VideoQuality as Ne}from"@vkontakte/videoplayer-shared";var Fe=n=>{switch(n){case"mobile":return Ne.Q_144P;case"lowest":return Ne.Q_240P;case"low":return Ne.Q_360P;case"sd":case"medium":return Ne.Q_480P;case"hd":case"high":return Ne.Q_720P;case"fullhd":case"full":return Ne.Q_1080P;case"quadhd":case"quad":return Ne.Q_1440P;case"ultrahd":case"ultra":return Ne.Q_2160P}};import{isNonNullable as ae,isNullable as zr,now as xs,isHigher as Kr,isHigherOrEqual as ys,isInvariantQuality as Ts,isLower as Jr,isLowerOrEqual as Is,videoSizeToQuality as pu,assertNotEmptyArray as ks,assertNonNullable as hu}from"@vkontakte/videoplayer-shared";var qr=!1,we={},Ss=n=>{qr=n},gs=()=>{we={}},vs=n=>{n(we)},Ot=(n,e)=>{qr&&(we.meta=we.meta??{},we.meta[n]=e)},q=class{constructor(e){this.name=e}next(e){if(!qr)return;we.series=we.series??{};let t=we.series[this.name]??[];t.push([Date.now(),e]),we.series[this.name]=t}};var mu=new q("best_bitrate"),As=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var Xr=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),_t=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=xs()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ps='Assertion "ABR Tracks is empty array" failed',Gi=(n,e,t,i)=>{let r=[...e].sort(Xr(1)),a=[...t].sort(Xr(1)),s=a.filter(d=>ae(d.bitrate)&&ae(n.bitrate)?n.bitrate/d.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)},Es=n=>"quality"in n,ws=(n,e,t,i)=>{let r=t&&i&&i.history[t.id]&&xs()-i.history[t.id]<=n.trackCooldown&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!r&&i.recordSelection(t),r&&i?.last){let a=i.last;i?.recordSwitch(a);let s=Es(a)?"video":"audio",o=Es(a)?a.quality:a.bitrate;return e({message:`
|
|
6
|
+
var Ya="2.0.111-dev.ae3e5b42.0";var te=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(te||{}),We=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(We||{});var Ji=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ji||{}),Ur=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ur||{});var Hr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Hr||{});import{assertNever as Za,assertNonNullable as Ro,isNonNullable as Xi,ValueSubject as Qr,Subject as Do,Subscription as Co,merge as Bo,observableFrom as Vo,fromEvent as za,map as Ka,tap as Ja,filterChanged as Oo,isNullable as jr,ErrorCategory as Xa}from"@vkontakte/videoplayer-shared";var qa=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Zi=class{constructor(e){this.connection$=new Qr(void 0);this.castState$=new Qr("NOT_AVAILABLE");this.errorEvent$=new Do;this.realCastState$=new Qr("NOT_AVAILABLE");this.subscription=new Co;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=Xi(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||qa("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Xa.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(){Xi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();jr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();jr(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(za(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Za(r.sessionState)}})).add(Bo(za(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ja(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Ka(r=>r.castState)),Vo([i.getCastState()])).pipe(Oo(),Ka(No),Ja(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=Xi(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();Ro(o);let d=o.getCastDevice(),u=o.getMediaSession()?.media?.contentId;(jr(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Xi(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:Xa.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},No=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 Za(n)}};import{assertNever as es}from"@vkontakte/videoplayer-shared";var q=(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:es(t)}return n},Gr=(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:es(e)}};var y=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as _o,Subject as er,merge as ts}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new er;this.transitionEnded$=new er;this.transitionUpdated$=new er;this.forceChanged$=new er;this.stateChangeStarted$=ts(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ts(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||_o(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 Fo}from"@vkontakte/videoplayer-shared";var is=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Fo(n)}};import{assertNever as At,assertNonNullable as dt,debounce as rs,ErrorCategory as as,fromEvent as lt,isNonNullable as ss,map as ns,merge as os,observableFrom as Uo,Subject as Ho,Subscription as Wr,timeout as Qo,getHighestQuality as jo}from"@vkontakte/videoplayer-shared";var Go=5,Wo=5,Yo=500,us=7e3,Qt=class{constructor(e){this.subscription=new Wr;this.loadMediaTimeoutSubscription=new Wr;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:At(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:At(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:At(e)}break}default:At(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(is(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Wr;this.subscription.add(e),this.subscription.add(os(this.videoState.stateChangeStarted$.pipe(ns(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(ns(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 Ho;e.add(r.pipe(rs(Yo)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(lt(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)>Go)&&r.next(o),a=o})),e.add(lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(lt(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(),d=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==d&&this.params.output.isBuffering$.next(d),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Wo&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),y(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:At(s)}}),t(lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=os(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Uo(["init"])).pipe(rs(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&y(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let u=t[e];dt(u);let c=jo(Object.keys(u));dt(c);let l=u[c];dt(l),i=l,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];dt(u),i=u.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 u=t[e];dt(u),i=u.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];dt(u),i=u.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];dt(u),i=q(u.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:as.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return At(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:d}=this.params.meta;return ss(o)&&(s.metadata.title=o),ss(d)&&(s.metadata.subtitle=d),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(Qo(us).subscribe(()=>a(`timeout(${us})`)))});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:as.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as ls}from"@vkontakte/videoplayer-shared";import{clearVideoElement as qo}from"@vkontakte/videoplayer-shared";var ds=n=>{try{n.pause(),n.playbackRate=0,qo(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as zo,Subscription as Ko}from"@vkontakte/videoplayer-shared";var Yr=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)}},qr=window.WeakMap?new WeakMap:new Yr,zr=window.WeakMap?new WeakMap:new Map,Jo=(n,e=20)=>{let t=0;return zo(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ie=(n,{audioVideoSyncRate:e})=>{let t=n.querySelector("video"),i=!!t;t?ls(t):(t=document.createElement("video"),n.appendChild(t)),qr.set(t,i);let r=new Ko;return r.add(Jo(t,e)),zr.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},re=n=>{zr.get(n)?.unsubscribe(),zr.delete(n);let t=qr.get(n);qr.delete(n),t?ls(n):ds(n)};import{assertNonNullable as jt,isNonNullable as Re,isNullable as eu,fromEvent as Pt,merge as cs,observableFrom as ps,filterChanged as hs,map as Gt,Subject as ms,Subscription as tu,ValueSubject as iu,ErrorCategory as ru}from"@vkontakte/videoplayer-shared";import{isNonNullable as Kr,isNullable as Xo,Subscription as Zo}from"@vkontakte/videoplayer-shared";var tr=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),d=Xo(r),u=new Zo;return r&&u.add(r.subscribe(c=>{let l=n.getState();i(c,l)&&n.setState(c)},a)),i(o,s)||(t(s),d&&n.setState(s)),u.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),d&&n.setState(c.to)},a)),u},Me=(n,e,t)=>tr(e,()=>n.loop,i=>{Kr(i)&&(n.loop=i)},{onError:t}),ae=(n,e,t,i)=>tr(e,()=>({muted:n.muted,volume:n.volume}),r=>{Kr(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}),me=(n,e,t,i)=>tr(e,()=>n.playbackRate,r=>{Kr(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Ye=tr;var au=n=>["__",n.language,n.label].join("|"),su=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Jr=class n{constructor(){this.available$=new ms;this.current$=new iu(void 0);this.error$=new ms;this.subscription=new tu;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:ru.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(Ye(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Re(a)&&this.setInternal(a)},{equal:(a,s)=>Re(a)&&Re(s)&&a.length===s.length&&a.every(({id:o},d)=>o===s[d].id),changed$:this.available$.pipe(Gt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Ye(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Re(a)&&this.setExternal(a)},{equal:(a,s)=>Re(a)&&Re(s)&&a.length===s.length&&a.every(({id:o},d)=>o===s[d].id),changed$:this.available$.pipe(Gt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Ye(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(Ye(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){jt(this.video);let{textTracks:e}=this.video;this.subscription.add(Pt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(cs(Pt(e,"addtrack"),Pt(e,"removetrack"),ps(["init"])).pipe(Gt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),hs((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(cs(Pt(e,"change"),ps(["init"])).pipe(Gt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Gt(i=>i&&this.htmlTextTrackToITextTrack(i).id),hs()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Pt(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(Pt(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Re(t.align)&&(r.align=t.align),Re(t.position)&&(r.position=t.position),Re(t.size)&&(r.size=t.size),Re(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){jt(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:au(e),a=this.externalTracks.has(r),s=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){jt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(eu(e)||!su(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){jt(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){jt(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)}},De=Jr;var Oe=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 fs=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Xr=n=>{let e=fs(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},bs=n=>{let e=fs(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as fe,map as qe,merge as Ss,filterChanged as ou,isNonNullable as vs,Subject as uu,filter as ys,mapTo as Ts,combine as du,once as lu,ErrorCategory as cu,ValueSubject as Is,clientChecker as pu}from"@vkontakte/videoplayer-shared";var nu=3,gs=(n,e,t=nu)=>{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 d=a-1;d>=0;d--)n.end(d)+t>=i&&(i=n.start(d));for(let d=a+1;d<n.length;d++)n.start(d)-t<=r&&(r=n.end(d))}}return{from:i,to:r}};var se=n=>{let e=S=>fe(n,S).pipe(Ts(void 0)),i=Ss(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>fe(n,S))).pipe(qe(S=>S.type==="ended"?n.readyState<2:n.readyState<3),ou()),r=Ss(fe(n,"progress"),fe(n,"timeupdate")).pipe(qe(()=>gs(n.buffered,n.currentTime))),a=pu.isSafari?du({play:e("play").pipe(lu()),playing:e("playing")}).pipe(Ts(void 0)):e("playing"),s=fe(n,"volumechange").pipe(qe(()=>({muted:n.muted,volume:n.volume}))),o=fe(n,"ratechange").pipe(qe(()=>n.playbackRate)),d=fe(n,"error").pipe(ys(()=>!!(n.error||n.played.length)),qe(()=>{let S=n.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:cu.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:n.error??void 0}})),u=fe(n,"timeupdate").pipe(qe(()=>n.currentTime)),c=new uu,l=.3,p;u.subscribe(S=>{n.loop&&vs(p)&&vs(S)&&p>=n.duration-l&&S<=l&&c.next(p),p=S});let h=e("pause").pipe(ys(()=>!n.error&&p!==n.duration)),m=fe(n,"enterpictureinpicture"),f=fe(n,"leavepictureinpicture"),g=new Is(bs(n));m.subscribe(()=>g.next(!0)),f.subscribe(()=>g.next(!1));let P=new Is(Xr(n));return fe(n,"fullscreenchange").pipe(qe(()=>Xr(n))).subscribe(P),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:fe(n,"durationchange").pipe(qe(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:g,inFullscreen$:P}};import{VideoQuality as ze}from"@vkontakte/videoplayer-shared";var Ke=n=>{switch(n){case"mobile":return ze.Q_144P;case"lowest":return ze.Q_240P;case"low":return ze.Q_360P;case"sd":case"medium":return ze.Q_480P;case"hd":case"high":return ze.Q_720P;case"fullhd":case"full":return ze.Q_1080P;case"quadhd":case"quad":return ze.Q_1440P;case"ultrahd":case"ultra":return ze.Q_2160P}};import{isNonNullable as ne,isNullable as ea,now as Ls,isHigher as ta,isHigherOrEqual as As,isInvariantQuality as Ps,isLower as ia,isLowerOrEqual as ws,videoSizeToQuality as hu,assertNotEmptyArray as Ms,assertNonNullable as mu}from"@vkontakte/videoplayer-shared";var Zr=!1,Ne={},Es=n=>{Zr=n},xs=()=>{Ne={}},ks=n=>{n(Ne)},Wt=(n,e)=>{Zr&&(Ne.meta=Ne.meta??{},Ne.meta[n]=e)},J=class{constructor(e){this.name=e}next(e){if(!Zr)return;Ne.series=Ne.series??{};let t=Ne.series[this.name]??[];t.push([Date.now(),e]),Ne.series[this.name]=t}};var fu=new J("best_bitrate"),Rs=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var ra=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),Yt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ls()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ds='Assertion "ABR Tracks is empty array" failed',ir=(n,e,t,i)=>{let r=[...e].sort(ra(1)),a=[...t].sort(ra(1)),s=a.filter(d=>ne(d.bitrate)&&ne(n.bitrate)?n.bitrate/d.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)},$s=n=>"quality"in n,Cs=(n,e,t,i)=>{let r=t&&i&&i.history[t.id]&&Ls()-i.history[t.id]<=n.trackCooldown&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!r&&i.recordSelection(t),r&&i?.last){let a=i.last;i?.recordSwitch(a);let s=$s(a)?"video":"audio",o=$s(a)?a.quality:a.bitrate;return e({message:`
|
|
7
7
|
[last ${s} selected] ${o}
|
|
8
|
-
`}),a}return i?.recordSwitch(t),t},
|
|
8
|
+
`}),a}return i?.recordSwitch(t),t},Je=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:d,history:u,visible:c,droppedVideoMaxQualityLimit:l,abrLogger:p})=>{Ms(n,Ds);let h=i.usePixelRatio?window.devicePixelRatio??1:1,m=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*i.containerSizeFactor,height:e.height*h*i.containerSizeFactor},f=m&&hu(m),g=i.considerPlaybackRate&&ne(o)?o:1,P=n.filter(k=>!Ps(k.quality)).sort((k,A)=>ta(k.quality,A.quality)?-1:1),R=P.at(-1)?.quality,S=P.at(0)?.quality,b=ea(r)||ne(r.min)&&ne(r.max)&&ia(r.max,r.min)||ne(r.min)&&S&&ta(r.min,S)||ne(r.max)&&R&&ia(r.max,R),v=g*Rs(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),T={},V=P.filter(k=>{if(!(f?ia(k.quality,f):!0))return T[k.quality]="FitsContainer",!1;if(!(ne(t)&&isFinite(t)&&ne(k.bitrate)?t-a>=k.bitrate*v:!0))return T[k.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ne(i.minBufferToSwitchUp)&&d&&!Ps(d.quality)&&(s??0)<i.minBufferToSwitchUp&&ta(k.quality,d.quality))return T[k.quality]="Buffer",!1;if(!!l&&As(k.quality,l))return T[k.quality]="DroppedFramesLimit",!1;let Z=b||(ea(r.max)||ws(k.quality,r.max))&&(ea(r.min)||As(k.quality,r.min)),I=ne(c)&&!c?ws(k.quality,i.backgroundVideoQualityLimit):!0;return!Z||!I?(T[k.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&fu.next(V.bitrate);let N=V??P[Math.ceil((P.length-1)/2)]??n[0];return N.quality!==u?.last?.quality&&p({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
|
-
${n.map(
|
|
11
|
+
${n.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(i??{}).map(([
|
|
15
|
+
${Object.entries(i??{}).map(([k,A])=>`${k}: ${A}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
@@ -20,7 +20,7 @@ var Ua="2.0.111-dev.974e99b3.0";var Z=(r=>(r.STOPPED="stopped",r.READY="ready",r
|
|
|
20
20
|
throughput: ${t},
|
|
21
21
|
reserve: ${a},
|
|
22
22
|
playbackRate: ${o},
|
|
23
|
-
playbackRateFactor: ${
|
|
23
|
+
playbackRateFactor: ${g},
|
|
24
24
|
forwardBufferHealth: ${s},
|
|
25
25
|
bitrateFactor: ${v},
|
|
26
26
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
@@ -30,12 +30,12 @@ var Ua="2.0.111-dev.974e99b3.0";var Z=(r=>(r.STOPPED="stopped",r.READY="ready",r
|
|
|
30
30
|
minQualityLimit: ${r?.min},
|
|
31
31
|
|
|
32
32
|
[limited video tracks]
|
|
33
|
-
${Object.entries(T).map(([
|
|
33
|
+
${Object.entries(T).map(([k,A])=>`${k}: ${A}`).join(`
|
|
34
34
|
`)||"All tracks are available"}
|
|
35
35
|
|
|
36
36
|
[best video track] ${V?.quality}
|
|
37
|
-
[selected video track] ${
|
|
38
|
-
`}),
|
|
37
|
+
[selected video track] ${N?.quality}
|
|
38
|
+
`}),Cs(i,p,N,u)},Bs=(n,e,t,{throughput:i,tuning:r,playbackRate:a,forwardBufferHealth:s,history:o,abrLogger:d})=>{Ms(t,Ds);let u=r.considerPlaybackRate&&ne(a)?a:1,c=[...t].sort(ra(-1)),l=n.bitrate;mu(l);let p=u*Rs(s??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h;return ne(i)&&isFinite(i)&&(h=c.find(m=>ne(m.bitrate)?i-l>=m.bitrate*p:!0)),h||(h=ir(n,e,t,r.minVideoAudioRatio)),h?.bitrate!==o?.last?.bitrate&&d({message:`
|
|
39
39
|
[AUDIO TRACKS ABR]
|
|
40
40
|
[available audio tracks]
|
|
41
41
|
${t.map(m=>`{ id: ${m.id}, bitrate: ${m.bitrate} }`).join(`
|
|
@@ -55,7 +55,7 @@ var Ua="2.0.111-dev.974e99b3.0";var Z=(r=>(r.STOPPED="stopped",r.READY="ready",r
|
|
|
55
55
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
56
56
|
|
|
57
57
|
[selected audio track] ${h?.id}
|
|
58
|
-
`}),h&&ws(r,d,h,o)};var j=n=>new URL(n).hostname;import{assertNever as Bs,assertNonNullable as Vs,combine as Cu,debounce as Bu,ErrorCategory as Os,filter as _s,filterChanged as Vu,isNonNullable as ra,map as Ki,merge as Ns,observableFrom as Ou,once as _u,Subscription as Nu,ValueSubject as aa,videoQualityToHeight as Fu,videoSizeToQuality as Uu}from"@vkontakte/videoplayer-shared";var Ls=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},se=async n=>{let e=n.muted;try{await n.play()}catch(t){if(!Ls(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{await n.play()}catch(i){return Ls(i)&&(n.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Yi,isNullable as Su,assertNonNullable as Ut}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ms,assertNonNullable as Wi,now as fu}from"@vkontakte/videoplayer-shared";function G(){return fu()}function Zr(n){return G()-n}function ea(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,d=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let u=s.indexOf("?")>-1?"&":"?";return d&&(s+=u+"lowLat=1",u="&"),o&&(s+=u+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Rs(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function vt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,d=!1,u=0,c,l,p=!1,h="arraybuffer",m=7e3,f=2e3,S=()=>{if(d)return;Wi(c);let w=Zr(c),F;if(w<f){F=f-w,setTimeout(S,F);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,T()},A=w=>(a=w,k),R=w=>(l=w,k),g=()=>(h="json",k),b=()=>{if(!d){if(--u>=0){S(),i&&i();return}d=!0,l&&l(),t&&t()}},v=w=>(p=w,k),T=()=>{c=G(),s=new r,s.open("get",n);let w=0,F,Se=0,J=()=>(Wi(c),Math.max(c,Math.max(F||0,Se||0)));if(a&&s.addEventListener("progress",I=>{let P=G();a.updateChunk&&I.loaded>w&&(a.updateChunk(J(),I.loaded-w),w=I.loaded,F=P)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>b())),s.addEventListener("load",()=>{if(d)return;Wi(s);let I=s.status;if(I>=200&&I<300){if(s.response.byteLength&&a){let P=s.response.byteLength-w;P&&a.updateChunk&&a.updateChunk(J(),P)}s.responseType==="json"&&!Object.values(s.response).length?b():(l&&l(),e(s.response))}else b()}),s.addEventListener("error",()=>{b()}),p){let I=()=>{Wi(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Se=G(),s.removeEventListener("readystatechange",I))};s.addEventListener("readystatechange",I)}return s.responseType=h,s.send(),k},k={withBitrateReporting:A,withParallel:v,withJSONResponse:g,withRetryCount:w=>(u=w,k),withRetryInterval:(w,F)=>(Ms(w)&&(f=w),Ms(F)&&(m=F),k),withTimeout:w=>(o=w,k),withFinally:R,send:T,abort:()=>{s&&(s.abort(),s=void 0),d=!0,l&&l()}};return k}var Nt=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let d=a.bytes*s/o;r+=d,a.start=t,a.bytes-=d}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ft=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=G(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=d=>{e._complete=1,e._responseData=d,e._downloadTime=G()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=vt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=G()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=G();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var qi=1e4,ta=3;var gu=6e4,vu=10,yu=1,Tu=500,Ht=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Nt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ea(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ea(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Yi(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{Rs(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ft(ta,qi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,d=null,u=null,c=!1,l=()=>{let b=a&&(!c||c===this.rep);return b||t("Not running!"),b},p=(b,v,T)=>{d&&d.abort(),d=vt(this.urlResolver.resolve(b,!1),v,T,()=>this._retryCallback()).withTimeout(qi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ta).withFinally(()=>{d=null}).send()},h=(b,v,T)=>{Ut(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),v,T,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=b=>{let v=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${v}=>${b}`),i.playbackRate=b)},f=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let T=G()-1e4,D=0;for(let _=0;_<this.bufferStates.length;_++){let x=this.bufferStates[_];b=Math.min(b,x.buf),x.ts<T&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${b} drop=${D} jitter=${this.sourceJitter}`);let V=b-yu;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?m(1.15):V>1?m(1.1):V>.3?m(1.05):m(1)}},A=b=>{let v,T=()=>v&&v.start?v.start.length:0,D=I=>v.start[I]/1e3,V=I=>v.dur[I]/1e3,_=I=>v.fragIndex+I,x=(I,P)=>({chunkIdx:_(I),startTS:D(I),dur:V(I),discontinuity:P}),k=()=>{let I=0;if(v&&v.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=P;this.sourceJitter>1&&(W+=this.sourceJitter-1);let ue=v.dur.length-1;for(;ue>=0&&(W-=v.dur[ue],!(W<=0));--ue);I=Math.min(ue,v.dur.length-1-H),I=Math.max(I,0)}return x(I,!0)},w=I=>{let P=T();if(!(P<=0)){if(Yi(I)){for(let H=0;H<P;H++)if(D(H)>I)return x(H)}return k()}},F=I=>{let P=T(),H=I?I.chunkIdx+1:0,W=H-v.fragIndex;if(!(P<=0)){if(!I||W<0||W-P>vu)return t(`Resync: offset=${W} bChunks=${P} chunk=`+JSON.stringify(I)),k();if(!(W>=P))return x(H-v.fragIndex,!1)}},Se=(I,P,H)=>{u&&u.abort(),u=vt(this.urlResolver.resolve(I,!0,this.lowLatency),P,H,()=>this._retryCallback()).withTimeout(qi).withRetryCount(ta).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(I,P)=>{Se(b,H=>{if(!l())return;v=H;let W=!!v.lowLatency;W!==this.lowLatency&&f(W);let ue=0;for(let Ie=0;Ie<v.dur.length;++Ie)ue+=v.dur[Ie];ue>0&&(Ut(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ue/v.dur.length)),r({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,I(w(P))},()=>this._handleNetworkError())},nextChunk:F}},R=()=>{a=!1,o&&o.abort(),d&&d.abort(),u&&u.abort(),Ut(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:b=>{let{videoElement:v,logger:T}=this.params,D=A(e.jidxUrl),V,_,x,k,w=0,F,Se,J,I=()=>{F&&(clearTimeout(F),F=void 0);let C=Math.max(Tu,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Q=w+C,X=G(),ge=Math.min(1e4,Q-X);w=X;let De=()=>{u||l()&&D.seek(()=>{l()&&(w=G(),P(),I())})};ge>0?F=window.setTimeout(()=>{this.paused?I():De()},ge):De()},P=()=>{let C;for(;C=D.nextChunk(k);)k=C,pt(C);let Q=D.nextChunk(x);if(Q){if(x&&Q.discontinuity){T("Detected discontinuity; restarting playback"),this.paused?I():(R(),this._initPlayerWith(e));return}Ie(Q)}else I()},H=(C,Q)=>{if(!l()||!this.sourceBuffer)return;let X,ge,De,ht=Ce=>{window.setTimeout(()=>{l()&&H(C,Q)},Ce)};if(this.sourceBuffer.updating)T("Source buffer is updating; delaying appendBuffer"),ht(100);else{let Ce=G(),mt=v.currentTime;!this.paused&&v.buffered.length>1&&Se===mt&&Ce-J>500&&(T("Stall suspected; trying to fix"),this._fixupStall()),Se!==mt&&(Se=mt,J=Ce);let Mt=this._getBufferSizeSec();if(Mt>30)T(`Buffered ${Mt} seconds; delaying appendBuffer`),ht(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:Ce,buf:Mt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Q&&Q()}catch(Bi){if(Bi.name==="QuotaExceededError")T("QuotaExceededError; delaying appendBuffer"),De=this.sourceBuffer.buffered.length,De!==0&&(X=this.sourceBuffer.buffered.start(0),ge=mt,ge-X>4&&this.sourceBuffer.remove(X,ge-3)),ht(1e3);else throw Bi}}},W=()=>{_&&V&&(T([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(x)]),H(_,function(){_=null,P()}))},ue=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),Ie=C=>{l()&&h(ue(C),(Q,X)=>{if(l()){if(X/=1e3,_=Q,x=C,s=C.startTS,X){let ge=Math.min(10,C.dur/X);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ge:ge}W()}},()=>this._handleNetworkError())},pt=C=>{l()&&(Ut(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ue(C),!1)))},qe=C=>{l()&&(e.cachedHeader=C,H(C,()=>{V=!0,W()}))};a=!0,D.seek(C=>{if(l()){if(w=G(),!C){I();return}k=C,!Su(b)||C.startTS>b?Ie(C):(x=C,P())}},b),e.cachedHeader?qe(e.cachedHeader):p(e.headerUrl,qe,()=>this._handleNetworkError())},stop:R,getTimestampSec:()=>s},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Yi(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ut(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Yi(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},a={updateChunk:(p,h)=>{let m=G();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},s=-1/0,o,d=!0,u=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(d&&l>o&&Zr(s)<3e4)return;i(l)}d=this.autoQuality};return{updateChunk:(l,p)=>{let h=a.updateChunk(l,p);return h&&u(),h},notifySwitch:l=>{let p=G();l<o&&(s=p),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=vt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(qi).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;se(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,o.push(d))}),o.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},gu))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Iu,filter as Ds,fromEvent as Eu,interval as xu,isHigher as ku,isInvariantQuality as Au,isLower as Pu,merge as wu,Subject as Cs,Subscription as $u}from"@vkontakte/videoplayer-shared";var ia=class{constructor(){this.onDroopedVideoFramesLimit$=new Cs;this.subscription=new $u;this.playing=!1;this.tracks=[];this.forceChecker$=new Cs;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Au(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&ku(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Eu(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=xu(this.droppedFramesChecker.checkTime).pipe(Ds(()=>this.playing),Ds(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Iu(this.droppedFramesChecker.checkTime)),i=wu(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>Pu(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},zi=ia;import{map as Lu,Observable as Mu}from"@vkontakte/videoplayer-shared";import{fromEvent as Ru}from"@vkontakte/videoplayer-shared";var Qt=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Du=(n,e)=>new Mu(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(d=>t.next(d.isIntersecting||Qt()))},{...i,...e});r.observe(n);let a=Ru(document,"visibilitychange").pipe(Lu(s=>!document.hidden||Qt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),me=Du;var Hu=["paused","playing","ready"],Qu=["paused","playing","ready"],jt=class{constructor(e){this.subscription=new Nu;this.videoState=new $("stopped");this.representations$=new aa([]);this.textTracksManager=new pe;this.droppedFramesManager=new zi;this.maxSeekBackTime$=new aa(1/0);this.zeroTime$=new aa(void 0);this.liveOffset=new Pe;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Os.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=Fe(r.name)??Uu(r.video),o=r.bitrate/1e3,d={...r.video};if(!s)continue;let u={id:a,quality:s,bitrate:o,size:d};i.push({track:u,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),ra(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Qu.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&Hu.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Y(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let d=r?.from;d&&d==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(Y(this.params.source.url,d))}return;default:return Bs(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Os.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Ns(this.videoState.stateChangeStarted$.pipe(Ki(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ki(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(j(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=re(this.video);this.subscription.add(this.representations$.pipe(Ki(r=>r.map(({track:a})=>a)),_s(r=>!!r.length),_u()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Vu(),Ki(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Cu({zeroTime:this.zeroTime$.pipe(_s(ra)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(xe(this.video,this.params.desiredState.isLooped,t)).add(ie(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ce(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(me(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Fu(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Bs(r.to)}},t)).add(Ns(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ou(["init"])).pipe(Bu(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),te(this.video)}createLiveDashPlayer(){let e=new Ht({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&ra(t)?t:Ue(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),d&&this.setAutoQuality(i),s||d||a!==o){let u=e.find(({track:c})=>c.id===a)?.representation;Vs(u,"Representations missing"),this.dash.startPlay(u,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Vs(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Y(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var Fs=jt;var $e=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Rd,assertNonNullable as Dd,debounce as Cd,ErrorCategory as xa,filter as Mn,filterChanged as ka,fromEvent as Bd,isNonNullable as Vd,map as Rn,merge as mr,observableFrom as Od,observeElementSize as _d,once as Dn,Subscription as Nd,ValueSubject as Fd}from"@vkontakte/videoplayer-shared";var Le=()=>window.ManagedMediaSource||window.MediaSource,Ji=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Us=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Hs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as tr,clientChecker as Zi}from"@vkontakte/videoplayer-shared";var er=document.createElement("video"),Wu='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Yu='video/mp4; codecs="hev1.1.6.L93.B0"',Qs='video/webm; codecs="vp09.00.10.08"',js='video/webm; codecs="av01.0.00M.08"',qu='audio/mp4; codecs="mp4a.40.2"',zu='audio/webm; codecs="opus"',tt={mms:Ji(),mse:Us(),hls:!!(er.canPlayType?.("application/x-mpegurl")||er.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ne={mp4:!!er.canPlayType?.("video/mp4"),webm:!!er.canPlayType?.("video/webm"),cmaf:!0},oe={h264:!!Le()?.isTypeSupported?.(Wu),h265:!!Le()?.isTypeSupported?.(Yu),vp9:!!Le()?.isTypeSupported?.(Qs),av1:!!Le()?.isTypeSupported?.(js),aac:!!Le()?.isTypeSupported?.(qu),opus:!!Le()?.isTypeSupported?.(zu)},yt=(oe.h264||oe.h265)&&oe.aac,it,Ku=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:js}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Qs}})]);it={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Ku()}catch(n){console.error(n)}var Tt=tt.hls&&ne.mp4,Gs=()=>Object.keys(oe).filter(n=>oe[n]),Ws=(n,e=!1,t=!1)=>{let i=tt.mse||tt.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&ne.mp4&&yt;case"DASH_WEBM":return i&&ne.webm&&oe.vp9&&oe.opus;case"DASH_WEBM_AV1":return i&&ne.webm&&oe.av1&&oe.opus;case"DASH_STREAMS":return i&&(ne.mp4&&yt||ne.webm&&(oe.vp9||oe.av1)&&(oe.opus||oe.aac));case"DASH_LIVE":return tt.mse&&ne.mp4&&yt;case"DASH_LIVE_CMAF":return i&&ne.mp4&&yt&&ne.cmaf;case"DASH_ONDEMAND":return i&&ne.mp4&&yt;case"HLS":case"HLS_ONDEMAND":return Tt||e&&tt.mse&&ne.mp4&&yt;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Tt;case"MPEG":return ne.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return tt.webrtc&&tt.ws&&oe.h264&&(ne.mp4||ne.webm);default:return tr(r)}})},Xi=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return it?it[t].smooth?[t,e]:it[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return it?it[t].powerEfficient?[t,e]:it[e].powerEfficient?[e,t]:[t,e]:[e,t];default:tr(n)}return[e,t]},Ys=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Xi(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Zi.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Xi(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Xi(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Xi(n),...r,"HLS","HLS_ONDEMAND"];default:tr(e)}return Tt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},qs=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,d=Zi.isMac&&Zi.isSafari;if(Zi.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:tr(n)}else Tt&&!d?o=s:d?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},sa=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],zs=n=>{if(n.size!==0){if(n.size===1)return n.values().next().value.split(".").at(0);for(let e of n){let t=e.split(".").at(0);if(t==="opus"||t==="vp09"||t==="av01")return t}return n.values().next().value.split(".").at(0)}};import{ErrorCategory as Gt}from"@vkontakte/videoplayer-shared";var Ks=n=>{if(!n)return{id:"EmptyResponse",category:Gt.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Gt.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Gt.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Gt.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Gt.PARSER,message:"Response is valid XML, but parser failed"}};var It=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};import{abortable as Ta,assertNonNullable as lt,combine as ur,ErrorCategory as Qe,filter as dr,filterChanged as xn,fromEvent as wt,interval as Ia,isNonNullable as kn,map as Ea,merge as $t,Subject as An,Subscription as Pn,tap as xd,throttle as kd,clientChecker as Ad,ValueSubject as z,flattenObject as vi,getTraceSubscriptionMethod as Pd}from"@vkontakte/videoplayer-shared";import{assertNever as Ju,ErrorCategory as Js,clientChecker as na,Subject as Xs}from"@vkontakte/videoplayer-shared";var Xu=16,Zs=!1;try{Zs=na.isSafari&&!!na.macVersion&&na.macVersion<=Xu}catch(n){console.error(n)}var oa=class{constructor(e){this.bufferFull$=new Xs;this.error$=new Xs;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Js.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Zs&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Js.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Ju(t)}}},en=oa;var ua=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as At,assertNonNullable as fe,ErrorCategory as ot,fromEvent as fa,getExponentialDelay as ba,isNonNullable as Sa,isNullable as be,once as bd,Subject as Sd,Subscription as gd,ValueSubject as hi}from"@vkontakte/videoplayer-shared";var O=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Et=class extends O{};var Wt=class extends O{};var Yt=class extends O{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var qt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Kt=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var U=class extends O{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var rt=class extends U{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,s=r<<1>>>1,o=this.readUint32();r=this.readUint32();let d=r>>>28,u=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:s,subsegmentDuration:o,SAPType:d,SAPDeltaTime:u})}}};var Jt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zt=class extends U{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ei=class extends U{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ti=class extends U{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ii=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ri=class extends U{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ai=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends U{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var oi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends U{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var di=class extends U{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var li=class extends U{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ed={ftyp:Yt,moov:qt,moof:zt,mdat:Kt,sidx:rt,trak:Jt,mdia:ii,mfhd:ni,tkhd:ri,traf:oi,tfhd:ui,tfdt:di,trun:li,minf:ai,sv3d:Xt,st3d:Zt,prhd:ei,proj:si,equi:ti,uuid:Wt,unknown:Et},at=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch{break}return t}createBox(e,t){let i=ed[e];return i?new i(t,new n):new Et(t,new n)}};var xt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var id=new TextDecoder("ascii"),rd=n=>id.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",ad=n=>{let e=new rt(n,new at),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},sd=(n,e)=>{let i=new at().parse(n),r=new xt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],d=s[s.length-1],u=o.source.byteOffset,l=d.source.byteOffset-o.source.byteOffset+d.size;return new DataView(n.buffer,u,l)},nd=(n,e)=>{let i=new at().parse(n),a=new xt(i).findAll("traf"),s=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),d=a[a.length-1].children.find(l=>l.type==="trun"),u=0;return d.sampleDuration.length?u=d.sampleDuration.reduce((l,p)=>l+p,0):u=s.defaultSampleDuration*d.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},od=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new at().parse(n),r=new xt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let d=r.find("equi");d&&(e.projectionData.bounds.top=d.projectionBoundsTop,e.projectionData.bounds.right=d.projectionBoundsRight,e.projectionData.bounds.bottom=d.projectionBoundsBottom,e.projectionData.bounds.left=d.projectionBoundsLeft)}return e},tn={validateData:rd,parseInit:od,getIndexRange:()=>{},parseSegments:ad,parseFeedableSegmentChunk:sd,getSegmentEndTime:nd};import{assertNonNullable as la,isNonNullable as nn,isNullable as dd}from"@vkontakte/videoplayer-shared";import{assertNever as ud}from"@vkontakte/videoplayer-shared";var rn={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},an=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ci(n,t),r=i in rn,a=r?rn[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let d=new DataView(n.buffer,n.byteOffset+t+1,o-1),u=s&255>>o,c=ci(d),l=u*2**((o-1)*8)+c,p=t+o,h;return p+l>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},ci=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ye=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ci(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:ud(e)}},st=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=an(i);if(!e(r))return;r.type==="master"&&st(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},sn=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=an(n);return st(r.value,({tag:a,type:s,value:o})=>(a===17143?e=ye(o,s):a===17026?t=ye(o,s):a===17029&&(i=ye(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var on=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ld=[231,22612,22743,167,171,163,160,175],cd=n=>{let e,t,i,r,a=!1,s=!1,o=!1,d,u,c=!1,l=0;return st(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let S=ye(m,h);u=ci(S)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=ye(m,h):p===17545?r=ye(m,h):p===21420&&u===475249515?d=ye(m,h):p===374648427?st(m,({tag:S,type:A,value:R})=>S===30321?(c=ye(R,A)===1,!1):!0):a&&s&&on.includes(p)&&(o=!0),!o}),la(e,"Failed to parse webm Segment start"),la(t,"Failed to parse webm Segment end"),la(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},pd=n=>{if(dd(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hd=(n,e)=>{let t=!1,i=!1,r=o=>nn(o.time)&&nn(o.position),a=[],s;return st(n,({tag:o,type:d,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=ye(u,d));break;case 183:break;case 241:s&&(s.position=ye(u,d));break;default:t&&on.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,d)=>{let{time:u,position:c}=o,l=a[d+1];return{status:"none",time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},md=n=>{let e=0,t=!1;try{st(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ld.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},un={validateData:sn,parseInit:cd,getIndexRange:pd,parseSegments:hd,parseFeedableSegmentChunk:md};var kt=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return un;case"mp4":return tn}}throw new ReferenceError(`Unsupported mime type ${n}`)};var ca=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as ln,isNullable as cn}from"@vkontakte/videoplayer-shared";var dn=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var pn=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let d=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(d)?0:d)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},nt=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,d)=>cn(a)?o:cn(d)?a:a.padStart(parseInt(d,10),"0"))}return t},mn=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=a.querySelector("BaseURL")?.textContent?.trim()??"",d=s.children,u=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=c?new Date(c).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),S=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=pn(h);else if(m){let b=pn(m);ln(b)&&(p=b)}else S&&(p=parseInt(S,10));let A=0,R=a.getAttribute("profiles")?.split(",")??[];for(let b of d){let v=b.getAttribute("id")??"id"+(A++).toString(10),T=b.getAttribute("mimeType")??"",D=b.getAttribute("codecs")??"",V=b.getAttribute("contentType")??T?.split("/")[0],_=b.getAttribute("profiles")?.split(",")??[],x=b.getAttribute("lang")??void 0,k=b.querySelector("Label")?.textContent?.trim()??void 0,w=b.querySelectorAll("Representation"),F=b.querySelector("SegmentTemplate"),Se=b.querySelector("Role")?.getAttribute("value")??void 0,J=V,I={id:v,language:x,isDefault:Se==="main",label:k,codecs:D,hdr:J==="video"&&ca(D),mime:T,representations:[]};for(let P of w){let H=P.getAttribute("lang")??void 0,W=P.getAttribute("label")??void 0,ue=P.querySelector("BaseURL")?.textContent?.trim()??"",Ie=new URL(ue||o,e).toString(),pt=P.getAttribute("mimeType")??T,qe=P.getAttribute("codecs")??D??"",C;if(V==="text"){let Q=P.getAttribute("id")||"",X=Q.includes("_auto");C={id:Q,isAuto:X,kind:"text",url:Ie}}else{let Q=P.getAttribute("contentType")??pt?.split("/")[0]??V,X=b.getAttribute("profiles")?.split(",")??[],ge=parseInt(P.getAttribute("width")??"",10),De=parseInt(P.getAttribute("height")??"",10),ht=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,Ce=P.getAttribute("frameRate")??"",mt=P.getAttribute("quality")??void 0,Mt=Ce?dn(Ce):void 0,Bi=P.getAttribute("id")??"id"+(A++).toString(10),Eo=Q==="video"?`${De}p`:Q==="audio"?`${ht}Kbps`:qe,xo=`${Bi}@${Eo}`,ko=[...R,..._,...X],$r,Ao=P.querySelector("SegmentBase"),ze=P.querySelector("SegmentTemplate")??F;if(Ao){let Ke=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Je,Mr]=Ke.split("-").map(ft=>parseInt(ft,10)),Be={from:Je,to:Mr},Rt=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[Rr,Vi]=Rt?Rt.split("-").map(ft=>parseInt(ft,10)):[],Dt=Rt?{from:Rr,to:Vi}:void 0;$r={type:"byteRange",url:Ie,initRange:Be,indexRange:Dt}}else if(ze){let Ke={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},Je=parseInt(ze.getAttribute("timescale")??"",10),Mr=ze.getAttribute("initialization")??"",Be=ze.getAttribute("media"),Rt=parseInt(ze.getAttribute("startNumber")??"",10)??1,Rr=nt(Mr,Ke);if(!Be)throw new ReferenceError("No media attribute in SegmentTemplate");let Vi=ze.querySelectorAll("SegmentTimeline S")??[],Dt=[],ft=0,Dr="",Cr=0;if(Vi.length){let Oi=Rt,ve=0;for(let bt of Vi){let Ee=parseInt(bt.getAttribute("d")??"",10),Xe=parseInt(bt.getAttribute("r")??"",10)||0,_i=parseInt(bt.getAttribute("t")??"",10);ve=Number.isFinite(_i)?_i:ve;let Br=Ee/Je*1e3,wo=ve/Je*1e3;for(let Ni=0;Ni<Xe+1;Ni++){let $o=nt(Be,{...Ke,segmentNumber:Oi.toString(10),segmentTime:(ve+Ni*Ee).toString(10)}),Fa=(wo??0)+Ni*Br,Lo=Fa+Br;Oi++,Dt.push({time:{from:Fa,to:Lo},url:$o})}ve+=(Xe+1)*Ee,ft+=(Xe+1)*Br}Cr=ve/Je*1e3,Dr=nt(Be,{...Ke,segmentNumber:Oi.toString(10),segmentTime:ve.toString(10)})}else if(ln(p)){let ve=parseInt(ze.getAttribute("duration")??"",10)/Je*1e3,bt=Math.ceil(p/ve),Ee=0;for(let Xe=1;Xe<bt;Xe++){let _i=nt(Be,{...Ke,segmentNumber:Xe.toString(10),segmentTime:Ee.toString(10)});Dt.push({time:{from:Ee,to:Ee+ve},url:_i}),Ee+=ve}Cr=Ee,Dr=nt(Be,{...Ke,segmentNumber:bt.toString(10),segmentTime:Ee.toString(10)})}let Po={time:{from:Cr,to:1/0},url:Dr};$r={type:"template",baseUrl:Ie,segmentTemplateUrl:Be,initUrl:Rr,totalSegmentsDurationMs:ft,segments:Dt,nextSegmentBeyondManifest:Po,timescale:Je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Q||!pt)continue;let Lr={video:"video",audio:"audio",text:"text"}[Q];if(!Lr)continue;J||=Lr,C={id:xo,kind:Lr,segmentReference:$r,profiles:ko,duration:p,bitrate:ht,mime:pt,codecs:qe,width:ge,height:De,fps:Mt,quality:mt}}I.language||=H,I.label||=W,I.mime||=pt,I.codecs||=qe,I.hdr||=J==="video"&&ca(qe),I.representations.push(C)}J&&r[J].push(I)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:r}};import{videoSizeToQuality as fd}from"@vkontakte/videoplayer-shared";var fn=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{let s=(a?Fe(a):void 0)??fd({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},bn=({id:n,bitrate:e})=>({id:n,bitrate:e}),ir=(n,e,t)=>{let i=e.indexOf(n);return t.at(Math.round(t.length*i/e.length))??t.at(-1)},Sn=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),ha=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),ma=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),rr=n=>"url"in n,Me=n=>n.type==="template",pi=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var mi=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:d=!1,manifest:u}){this.currentSegmentLength$=new hi(0);this.onLastSegment$=new hi(!1);this.fullyBuffered$=new hi(!1);this.playingRepresentation$=new hi(void 0);this.playingRepresentationInit$=new hi(void 0);this.error$=new Sd;this.gaps=[];this.subscription=new gd;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=At(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new en(this.sourceBuffer),this.subscription.add(fa(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,d=this.mediaSource.readyState;d!=="open"&&(o={id:`SegmentEjection_source_${d}`,category:ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(fa(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ot.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let d=Math.min(this.bufferLimit,ua(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=d,this.tuning.useNewPruneBufferStrategy){let u=$e(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,u<c)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);fe(i,"No init buffer for starting representation"),fe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=At(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);fe(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(be(a)||be(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),fe(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();Sa(s)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=At(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(d=>d.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let u=t.find(p=>p.id===d);u&&this.representations.set(d,u);let c=this.representations.get(d);if(!c||!Me(c.segmentReference))return;let l=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);fe(r);let a=this.segments.get(i);fe(a,"No segments for starting representation");let s=this.initData.get(i);if(fe(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=d,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(be(e)||be(this.downloadingRepresentationId)||be(this.playingRepresentationId)||be(this.sourceBuffer)||!be(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(fe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=$e(this.sourceBuffer.buffered,e),l=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(a=l)}if(isFinite(this.bufferLimit)&&ua(this.sourceBuffer.buffered)>=this.bufferLimit){let u=$e(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))u="high";else{let c=o.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&$e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=i.at(-1);d&&d.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;Sa(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Me(i.segmentReference))return;let r=i.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),a=this.segments.get(i.id)??[],s=a.at(-1)?.time.to??0,o=r?.findIndex(d=>Math.floor(s)>=Math.floor(d.time.from)&&Math.floor(s)<=Math.floor(d.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,d)}else{let d=r.slice(o+1);this.segments.set(i.id,[...a,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;fe(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!Me(i))return;let r=this.segments.get(t.id)??[],a=r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to),!!!r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),d=nt(i.segmentTemplateUrl,{segmentTime:o});r.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:l,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,S=p>i||f||m===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),R=this.preloadOnly&&p<=i+A||h<=i+A;return(l==="none"||l==="partially_ejected"&&S&&R&&this.sourceBuffer&&!(It(this.sourceBuffer.buffered,p)&&It(this.sourceBuffer.buffered,h)))&&S&&R});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(s<=u||o<=c);l++){let p=a[l];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")d.push(p);else break}return d}async loadSegments(e,t,i="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:d,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await At(o,async function*(){let c=ba(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;let l=new DataView(c);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=kt(t.mime);r.segment.time.to=h.getSegmentEndTime(l,p)}d&&r.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(l,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),pi(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let d of e)d.status="downloading",this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await At(s,async function*(){let d=ba(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,d),fa(window,"online").pipe(bd()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(d){this.abortActiveSegments(e),pi(d)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Me(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Me(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!a.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let s=this.representations.get(t);if(s)for(let o of this.activeSegments){let{segment:d}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=kt(s.mime).parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(d.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let d=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:l}=c,p=d==="byteRange",h=p?l.byte.to-l.byte.from+1:u;if(c.representationId!==t||!(!p||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let f=p?l.byte.from-i:0,S=p?l.byte.to-i:e.byteLength,A=f<r,R=S<=r;if(l.status==="downloading"&&A&&R){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+f,h),b=this.getCurrentPosition();Sa(b)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-b,this.bufferAccumulation.accumulated.push({segmentView:g,segmentProgress:c}),this.activeSegments.delete(c));let v=({segmentView:T,segmentProgress:D})=>this.sourceBufferTaskQueue.append(T,a).then(V=>V&&!a.aborted?this.onSegmentFullyAppended(D,t):s());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(v),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||be(b))&&(v({segmentView:g,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&A&&!R&&(c.loadedBytes=Math.min(h,r-f),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+f+c.feedingBytes,c.loadedBytes-c.feedingBytes),b=c.loadedBytes===h?g:kt(o.mime).parseFeedableSegmentChunk(g);b?.byteLength&&(l.status="partially_fed",c.feedingBytes+=b.byteLength,this.sourceBufferTaskQueue.append(b,a).then(v=>{if(a.aborted)s();else if(v)c.fedBytes+=b.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;s()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let d of this.activeSegments){let{segment:u}=d;if(d.representationId!==t)continue;if(a.aborted){s();continue}let c=u.byte.from-i,l=u.byte.to-i,p=l-c+1,h=c<r,m=l<=r;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(f,a)&&!a.aborted?this.onSegmentFullyAppended(d,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(d.loadedBytes=Math.min(p,r-c),d.loadedBytes>d.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+c+d.feedingBytes,d.loadedBytes-d.feedingBytes),S=d.loadedBytes===p?f:kt(o.mime).parseFeedableSegmentChunk(f);S?.byteLength&&(u.status="partially_fed",d.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(d.fedBytes+=S.byteLength,d.fedBytes===p&&this.onSegmentFullyAppended(d,t)):s())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",rr(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");fe(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;t||=s,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?At(this.destroyAbortController.signal,async function*(){let o=ba(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,kt(e.mime),r)).then(async o=>{if(!o)return;let{init:d,dataView:u,segments:c}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l);let p=c;this.isLive&&Me(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:ot.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||be(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=d=>{d.sort((c,l)=>c.from-l.from);let u=[d[0]];for(let c=1;c<d.length;c++){let{from:l,to:p}=d[c],h=u[u.length-1];h.to>=l?h.to=Math.max(h.to,p):u.push(d[c])}return u},o=d=>{if(a>=t)return r;r.push({...d.time}),r=s(r);let u=rr(d)?d.size??0:d.byte.to-d.byte.from;a+=u};for(let d of this.segments.values())for(let u of d){let c=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||l)&&u.status==="fed"&&o(u)}for(let d=0;d<this.sourceBuffer.buffered.length;d++){let u=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3,l=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(c)&&l++;if(l===this.segments.size){let p={time:{from:u,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let c of u)c.time.from>=e+d&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,c)=>u||c,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||be(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,d=u=>{a=Math.min(a,u.time.from),s=Math.max(s,u.time.to);let c=rr(u)?u.size??0:u.byte.to-u.byte.from;r+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&d(c)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&d(c)}}if(o=isFinite(a)&&isFinite(s),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)){a=c,s=l;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>e+u&&l.status==="fed"&&d(l)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){fe(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ot.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(be(this.sourceBuffer)||be(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=10;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),d=e.some(c=>c.from-t<=s&&c.to+t>=o),u=e.filter(c=>s>=c.from&&s<c.to-t||o>c.from+t&&o<=c.to);d||(u.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var fi=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var gn=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as bi,assertNever as vn,fromEvent as yn,merge as vd,now as Si,Subscription as yd,ValueSubject as ga,flattenObject as Pt}from"@vkontakte/videoplayer-shared";var ar=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1}){this.lastConnectionType$=new ga(void 0);this.lastConnectionReused$=new ga(void 0);this.lastRequestFirstBytes$=new ga(void 0);this.abortAllController=new AbortController;this.subscription=new yd;this.fetchManifest=bi(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=fi(i));let r=yield fetch(i,{signal:this.abortAllController.signal}).catch(gi);return r?(t.log("success",Pt({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Pt({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=bi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:d=!1}={}){let u=e,c=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(u,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),u=k.toString();break}default:vn(t)}this.requestQuic&&(u=fi(u));let p=this.abortAllController.signal,h;if(s){let k=new AbortController;if(h=vd(yn(this.abortAllController.signal,"abort"),yn(s,"abort")).subscribe(()=>{try{k.abort()}catch(w){gi(w)}}),this.abortAllController.signal.aborted||s.aborted)try{k.abort()}catch(w){gi(w)}p=k.signal}let m=Si();l.log("startRequest",Pt({url:u,priority:a,rangeMethod:t,range:i,isLowLatency:d,requestStartedAt:m}));let f=yield fetch(u,{priority:a,headers:c,signal:p}).catch(gi),S=Si();if(!f)return l.error("error",{message:"No response in request"}),l.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-m),!f.ok||!f.body){h?.unsubscribe();let k=`Fetch error ${f.status}: ${f.statusText}`;return l.error("error",{message:k}),l.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let k=Si(),w={requestStartedAt:m,requestEndedAt:k,duration:k-m};return l.log("endRequest",Pt(w)),l.end(),f.arrayBuffer()}let[A,R]=f.body.tee(),g=A.getReader();o&&this.throughputEstimator?.trackStream(R,d);let b=0,v=new Uint8Array(0),T=!1,D=k=>{h?.unsubscribe(),T=!0,gi(k)},V=bi(p,async function*({done:k,value:w}){if(b===0&&this.lastRequestFirstBytes$.next(Si()-m),p.aborted){h?.unsubscribe();return}if(!k&&w){let F=new Uint8Array(v.length+w.length);F.set(v),F.set(w,v.length),v=F,b+=w.byteLength,r?.(new DataView(v.buffer),b),yield g?.read().then(V,D)}}.bind(this));yield g?.read().then(V,D),h?.unsubscribe();let _=Si(),x={failed:T,requestStartedAt:m,requestEndedAt:_,duration:_-m};return T?(l.error("endRequest",Pt(x)),l.end(),null):(l.log("endRequest",Pt(x)),l.end(),v.buffer)}.bind(this));this.fetchByteRangeRepresentation=bi(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,d=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,d=a+1===u,d&&(s=Math.min(u,r),o=Math.max(c,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(d)f=new DataView(l,m.from-s,m.to-m.from+1);else{let A=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!A)return null;f=new DataView(A)}let S=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(l),segments:S}}.bind(this));this.fetchTemplateRepresentation=bi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(s=>({...s,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:i}=gn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:vn(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},gi=n=>{if(!pi(n))throw n};var ut=(n,e,t)=>t*e+(1-t)*n,va=(n,e)=>n.reduce((t,i)=>t+i,0)/e,Tn=(n,e,t,i)=>{let r=0,a=t,s=va(n,e),o=e<i?e:i;for(let d=0;d<o;d++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as Td,ValueSubject as In}from"@vkontakte/videoplayer-shared";var He=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new In(e.initial),this.debounced$=new In(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new q(`raw_${t}`),this.smoothedSeries$=new q(`smoothed_${t}`),this.reportedSeries$=new q(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(Td(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var sr=class extends He{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ut(this.slow,e,this.params.emaAlphaSlow),this.fast=ut(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var nr=class extends He{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=va(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ut(this.emaSmoothed,e,this.params.emaAlpha);let i=Tn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var or=class extends He{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?ut(this.smoothed,t,this.params.emaAlpha):t}};var dt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new sr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new nr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new or({initial:e,label:"liveEdgeDelay",...t})}};var ya=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var wn=["timeupdate","progress","play","seeked","stalled","waiting"];var lr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Pn;this.representationSubscription=new Pn;this.state$=new $("none");this.currentVideoRepresentation$=new z(void 0);this.currentVideoRepresentationInit$=new z(void 0);this.currentAudioRepresentation$=new z(void 0);this.currentVideoSegmentLength$=new z(0);this.currentAudioSegmentLength$=new z(0);this.error$=new An;this.lastConnectionType$=new z(void 0);this.lastConnectionReused$=new z(void 0);this.lastRequestFirstBytes$=new z(void 0);this.isLive$=new z(!1);this.liveDuration$=new z(0);this.liveAvailabilityStartTime$=new z(void 0);this.bufferLength$=new z(0);this.liveLoadBufferLength$=new z(0);this.livePositionFromPlayer$=new z(0);this.timeInWaiting=0;this.isActiveLowLatency$=new z(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new An;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Ta(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Y(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Qe.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ta(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Qe.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=mn(e??"",this.manifestUrlString)}catch(s){let o=Ks(e)??{id:"ManifestParsing",category:Qe.PARSER,message:"Failed to parse MPD manifest",thrown:s};this.error$.next(o)}if(!t)return null;let i=(s,o,d)=>!!(this.element?.canPlayType?.(o)&&Le()?.isTypeSupported?.(`${o}; codecs="${d}"`)||s==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let d=t.streams[s].filter(({mime:l,codecs:p})=>i(s,l,p)),u=new Set(d.map(({codecs:l})=>l)),c=zs(u);if(c&&(r[s]=d.filter(({codecs:l})=>l.startsWith(c))),s==="video"){let l=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);Ad.isHDR&&l&&p?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",vi(a)),a}.bind(this));this.initRepresentations=Ta(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",vi({initialVideo:e,initialAudio:t,sourceHls:i})),lt(this.manifest),lt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(wt(l,"error").pipe(dr(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Qe.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Hs():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Ji())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new mi("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],kn(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new mi("audio",this.source,l,s),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ia(1e3).subscribe(l=>{if(this.element?.paused){let p=Fr(this.manifestUrlString,2);this.manifestUrlString=Y(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add($t(...wn.filter(l=>l!=="waiting").map(l=>wt(this.element,l))).pipe(Ea(l=>this.element?$e(this.element.buffered,this.element.currentTime*1e3):0),xn(),dr(l=>!!l),xd(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(xn()).subscribe(p=>ya(this.element,1))),this.representationSubscription.add(ur({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(dr(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(ur({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,f=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=p-m,R=1;Math.abs(A)>f&&(R=1+Math.sign(A)*S),ya(this.element,R)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(ur({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(kd(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(lt(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,f=Fr(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),R=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,b=isFinite(p)?p:h,v=this.isActiveLowLatency$.getValue(),T=S<=this.tuning.live.activeLiveDelay&&f===0;this.isActiveLowLatency$.next(v&&T);let D="none";if(v?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&T?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),D="active_low_latency"):f!==0&&b<A?D="live_forward_buffering":b<A+g&&(D="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),D==="live_forward_buffering"||D==="live_with_target_offset"){let V=l-(A+R),_=this.normolizeLiveOffset(Math.trunc(f+V/m)),x=Math.abs(_-f),k;!p||x<=this.tuning.dashCmafLive.offsetCalculationError?k=f:_>0&&x>this.tuning.dashCmafLive.offsetCalculationError?k=_:k=0,this.manifestUrlString=Y(this.manifestUrlString,k,2)}D!=="none"&&D!=="active_low_latency"&&(l=0,this.updateLive())}))}let d=$t(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(Ea(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=$t(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(Ea(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add($t(this.forceEnded$,ur({allBuffersFull:d,someBufferEnded:u}).pipe(dr(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:Qe.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add($t(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(l=>this.source?.addEventListener("sourceopen",l)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),Me(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&kn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Ia(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Qe.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ar({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=dt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){lt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Y(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){lt(this.element),this.state$.setState("running"),this.subscription.add($t(...wn.map(e=>wt(this.element,e)),wt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Qe.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(wt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(wt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&It(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;this.timeInWaiting+=1e3;let t={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let i=this.element.currentTime*1e3;this.videoBufferManager?.maintain(i),this.audioBufferManager?.maintain(i),t={...t,position:i}}this.tracer.log("stallIntervalCallback",vi(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Ia(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Qe.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){lt(this.element),lt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),It(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",vi({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Pd(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let o of s.gaps)s.playingRepresentation$.getValue()===o.representation&&o.from-a<=i&&o.to+a>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():(this.element.currentTime=s/1e3,t={...t,gapEnds:r,jumpTo:s,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",vi(t)))}}};var cr=class{constructor(e,t){this.fov=e,this.orientation=t}};var pr=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var $n=`attribute vec2 a_vertex;
|
|
58
|
+
`}),h&&Cs(r,d,h,o)};var G=n=>new URL(n).hostname;import{assertNever as Us,assertNonNullable as Hs,combine as Bu,debounce as Vu,ErrorCategory as Qs,filter as js,filterChanged as Ou,isNonNullable as ua,map as or,merge as Gs,observableFrom as Nu,once as _u,Subscription as Fu,ValueSubject as da,videoQualityToHeight as Uu,videoSizeToQuality as Hu}from"@vkontakte/videoplayer-shared";var Vs=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},oe=async n=>{let e=n.muted;try{await n.play()}catch(t){if(!Vs(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{await n.play()}catch(i){return Vs(i)&&(n.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as ar,isNullable as Su,assertNonNullable as Kt}from"@vkontakte/videoplayer-shared";import{isNonNullable as Os,assertNonNullable as rr,now as bu}from"@vkontakte/videoplayer-shared";function W(){return bu()}function aa(n){return W()-n}function sa(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,d=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let u=s.indexOf("?")>-1?"&":"?";return d&&(s+=u+"lowLat=1",u="&"),o&&(s+=u+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Ns(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function wt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,d=!1,u=0,c,l,p=!1,h="arraybuffer",m=7e3,f=2e3,g=()=>{if(d)return;rr(c);let w=aa(c),F;if(w<f){F=f-w,setTimeout(g,F);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,T()},P=w=>(a=w,A),R=w=>(l=w,A),S=()=>(h="json",A),b=()=>{if(!d){if(--u>=0){g(),i&&i();return}d=!0,l&&l(),t&&t()}},v=w=>(p=w,A),T=()=>{c=W(),s=new r,s.open("get",n);let w=0,F,ye=0,Z=()=>(rr(c),Math.max(c,Math.max(F||0,ye||0)));if(a&&s.addEventListener("progress",I=>{let x=W();a.updateChunk&&I.loaded>w&&(a.updateChunk(Z(),I.loaded-w),w=I.loaded,F=x)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>b())),s.addEventListener("load",()=>{if(d)return;rr(s);let I=s.status;if(I>=200&&I<300){if(s.response.byteLength&&a){let x=s.response.byteLength-w;x&&a.updateChunk&&a.updateChunk(Z(),x)}s.responseType==="json"&&!Object.values(s.response).length?b():(l&&l(),e(s.response))}else b()}),s.addEventListener("error",()=>{b()}),p){let I=()=>{rr(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ye=W(),s.removeEventListener("readystatechange",I))};s.addEventListener("readystatechange",I)}return s.responseType=h,s.send(),A},A={withBitrateReporting:P,withParallel:v,withJSONResponse:S,withRetryCount:w=>(u=w,A),withRetryInterval:(w,F)=>(Os(w)&&(f=w),Os(F)&&(m=F),A),withTimeout:w=>(o=w,A),withFinally:R,send:T,abort:()=>{s&&(s.abort(),s=void 0),d=!0,l&&l()}};return A}var qt=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let d=a.bytes*s/o;r+=d,a.start=t,a.bytes-=d}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var zt=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=W(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=d=>{e._complete=1,e._responseData=d,e._downloadTime=W()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=wt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=W()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=W();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var sr=1e4,na=3;var vu=6e4,yu=10,Tu=1,Iu=500,Jt=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new qt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=sa(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=sa(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ar(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{Ns(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zt(na,sr,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,d=null,u=null,c=!1,l=()=>{let b=a&&(!c||c===this.rep);return b||t("Not running!"),b},p=(b,v,T)=>{d&&d.abort(),d=wt(this.urlResolver.resolve(b,!1),v,T,()=>this._retryCallback()).withTimeout(sr).withBitrateReporting(this.bitrateSwitcher).withRetryCount(na).withFinally(()=>{d=null}).send()},h=(b,v,T)=>{Kt(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),v,T,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=b=>{let v=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${v}=>${b}`),i.playbackRate=b)},f=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let T=W()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let k=this.bufferStates[N];b=Math.min(b,k.buf),k.ts<T&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${b} drop=${D} jitter=${this.sourceJitter}`);let V=b-Tu;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?m(1.15):V>1?m(1.1):V>.3?m(1.05):m(1)}},P=b=>{let v,T=()=>v&&v.start?v.start.length:0,D=I=>v.start[I]/1e3,V=I=>v.dur[I]/1e3,N=I=>v.fragIndex+I,k=(I,x)=>({chunkIdx:N(I),startTS:D(I),dur:V(I),discontinuity:x}),A=()=>{let I=0;if(v&&v.dur){let x=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=x;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let le=v.dur.length-1;for(;le>=0&&(Y-=v.dur[le],!(Y<=0));--le);I=Math.min(le,v.dur.length-1-H),I=Math.max(I,0)}return k(I,!0)},w=I=>{let x=T();if(!(x<=0)){if(ar(I)){for(let H=0;H<x;H++)if(D(H)>I)return k(H)}return A()}},F=I=>{let x=T(),H=I?I.chunkIdx+1:0,Y=H-v.fragIndex;if(!(x<=0)){if(!I||Y<0||Y-x>yu)return t(`Resync: offset=${Y} bChunks=${x} chunk=`+JSON.stringify(I)),A();if(!(Y>=x))return k(H-v.fragIndex,!1)}},ye=(I,x,H)=>{u&&u.abort(),u=wt(this.urlResolver.resolve(I,!0,this.lowLatency),x,H,()=>this._retryCallback()).withTimeout(sr).withRetryCount(na).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(I,x)=>{ye(b,H=>{if(!l())return;v=H;let Y=!!v.lowLatency;Y!==this.lowLatency&&f(Y);let le=0;for(let Pe=0;Pe<v.dur.length;++Pe)le+=v.dur[Pe];le>0&&(Kt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(le/v.dur.length)),r({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,I(w(x))},()=>this._handleNetworkError())},nextChunk:F}},R=()=>{a=!1,o&&o.abort(),d&&d.abort(),u&&u.abort(),Kt(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:b=>{let{videoElement:v,logger:T}=this.params,D=P(e.jidxUrl),V,N,k,A,w=0,F,ye,Z,I=()=>{F&&(clearTimeout(F),F=void 0);let C=Math.max(Iu,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Q=w+C,ee=W(),j=Math.min(1e4,Q-ee);w=ee;let Te=()=>{u||l()&&D.seek(()=>{l()&&(w=W(),x(),I())})};j>0?F=window.setTimeout(()=>{this.paused?I():Te()},j):Te()},x=()=>{let C;for(;C=D.nextChunk(A);)A=C,Tt(C);let Q=D.nextChunk(k);if(Q){if(k&&Q.discontinuity){T("Detected discontinuity; restarting playback"),this.paused?I():(R(),this._initPlayerWith(e));return}Pe(Q)}else I()},H=(C,Q)=>{if(!l()||!this.sourceBuffer)return;let ee,j,Te,Qe=we=>{window.setTimeout(()=>{l()&&H(C,Q)},we)};if(this.sourceBuffer.updating)T("Source buffer is updating; delaying appendBuffer"),Qe(100);else{let we=W(),Ie=v.currentTime;!this.paused&&v.buffered.length>1&&ye===Ie&&we-Z>500&&(T("Stall suspected; trying to fix"),this._fixupStall()),ye!==Ie&&(ye=Ie,Z=we);let st=this._getBufferSizeSec();if(st>30)T(`Buffered ${st} seconds; delaying appendBuffer`),Qe(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:we,buf:st}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Q&&Q()}catch(Ce){if(Ce.name==="QuotaExceededError")T("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(ee=this.sourceBuffer.buffered.start(0),j=Ie,j-ee>4&&this.sourceBuffer.remove(ee,j-3)),Qe(1e3);else throw Ce}}},Y=()=>{N&&V&&(T([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(k)]),H(N,function(){N=null,x()}))},le=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),Pe=C=>{l()&&h(le(C),(Q,ee)=>{if(l()){if(ee/=1e3,N=Q,k=C,s=C.startTS,ee){let j=Math.min(10,C.dur/ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*j:j}Y()}},()=>this._handleNetworkError())},Tt=C=>{l()&&(Kt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(le(C),!1)))},at=C=>{l()&&(e.cachedHeader=C,H(C,()=>{V=!0,Y()}))};a=!0,D.seek(C=>{if(l()){if(w=W(),!C){I();return}A=C,!Su(b)||C.startTS>b?Pe(C):(k=C,x())}},b),e.cachedHeader?at(e.cachedHeader):p(e.headerUrl,at,()=>this._handleNetworkError())},stop:R,getTimestampSec:()=>s},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),ar(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Kt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ar(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},a={updateChunk:(p,h)=>{let m=W();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},s=-1/0,o,d=!0,u=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(d&&l>o&&aa(s)<3e4)return;i(l)}d=this.autoQuality};return{updateChunk:(l,p)=>{let h=a.updateChunk(l,p);return h&&u(),h},notifySwitch:l=>{let p=W();l<o&&(s=p),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=wt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(sr).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;oe(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,o.push(d))}),o.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},vu))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Eu,filter as _s,fromEvent as xu,interval as ku,isHigher as Au,isInvariantQuality as Pu,isLower as wu,merge as $u,Subject as Fs,Subscription as Lu}from"@vkontakte/videoplayer-shared";var oa=class{constructor(){this.onDroopedVideoFramesLimit$=new Fs;this.subscription=new Lu;this.playing=!1;this.tracks=[];this.forceChecker$=new Fs;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Pu(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&Au(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(xu(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=ku(this.droppedFramesChecker.checkTime).pipe(_s(()=>this.playing),_s(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Eu(this.droppedFramesChecker.checkTime)),i=$u(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>wu(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},nr=oa;import{map as Mu,Observable as Ru}from"@vkontakte/videoplayer-shared";import{fromEvent as Du}from"@vkontakte/videoplayer-shared";var Xt=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Cu=(n,e)=>new Ru(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(d=>t.next(d.isIntersecting||Xt()))},{...i,...e});r.observe(n);let a=Du(document,"visibilitychange").pipe(Mu(s=>!document.hidden||Xt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),be=Cu;var Qu=["paused","playing","ready"],ju=["paused","playing","ready"],Zt=class{constructor(e){this.subscription=new Fu;this.videoState=new $("stopped");this.representations$=new da([]);this.textTracksManager=new De;this.droppedFramesManager=new nr;this.maxSeekBackTime$=new da(1/0);this.zeroTime$=new da(void 0);this.liveOffset=new Oe;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Qs.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=Ke(r.name)??Hu(r.video),o=r.bitrate/1e3,d={...r.video};if(!s)continue;let u={id:a,quality:s,bitrate:o,size:d};i.push({track:u,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),ua(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ju.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&Qu.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(q(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let d=r?.from;d&&d==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.dash.reinit(q(this.params.source.url,d))}return;default:return Us(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Qs.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Gs(this.videoState.stateChangeStarted$.pipe(or(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(or(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=se(this.video);this.subscription.add(this.representations$.pipe(or(r=>r.map(({track:a})=>a)),js(r=>!!r.length),_u()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Ou(),or(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Bu({zeroTime:this.zeroTime$.pipe(js(ua)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Me(this.video,this.params.desiredState.isLooped,t)).add(ae(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(me(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Uu(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Us(r.to)}},t)).add(Gs(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Nu(["init"])).pipe(Vu(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),re(this.video)}createLiveDashPlayer(){let e=new Jt({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&ua(t)?t:Je(e.map(({track:u})=>u),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),d&&this.setAutoQuality(i),s||d||a!==o){let u=e.find(({track:c})=>c.id===a)?.representation;Hs(u,"Representations missing"),this.dash.startPlay(u,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Hs(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(q(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var Ws=Zt;var _e=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Bd,assertNonNullable as Vd,debounce as Od,ErrorCategory as La,filter as Vn,filterChanged as Ma,fromEvent as Nd,isNonNullable as _d,map as On,merge as kr,observableFrom as Fd,observeElementSize as Ud,once as Nn,Subscription as Hd,ValueSubject as Qd}from"@vkontakte/videoplayer-shared";var Fe=()=>window.ManagedMediaSource||window.MediaSource,ur=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Ys=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),qs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as pr,clientChecker as lr}from"@vkontakte/videoplayer-shared";var cr=document.createElement("video"),Yu='video/mp4; codecs="avc1.42000a,mp4a.40.2"',qu='video/mp4; codecs="hev1.1.6.L93.B0"',zs='video/webm; codecs="vp09.00.10.08"',Ks='video/webm; codecs="av01.0.00M.08"',zu='audio/mp4; codecs="mp4a.40.2"',Ku='audio/webm; codecs="opus"',ct={mms:ur(),mse:Ys(),hls:!!(cr.canPlayType?.("application/x-mpegurl")||cr.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ue={mp4:!!cr.canPlayType?.("video/mp4"),webm:!!cr.canPlayType?.("video/webm"),cmaf:!0},de={h264:!!Fe()?.isTypeSupported?.(Yu),h265:!!Fe()?.isTypeSupported?.(qu),vp9:!!Fe()?.isTypeSupported?.(zs),av1:!!Fe()?.isTypeSupported?.(Ks),aac:!!Fe()?.isTypeSupported?.(zu),opus:!!Fe()?.isTypeSupported?.(Ku)},$t=(de.h264||de.h265)&&de.aac,pt,Ju=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Ks}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:zs}})]);pt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Ju()}catch(n){console.error(n)}var Lt=ct.hls&&ue.mp4,Js=()=>Object.keys(de).filter(n=>de[n]),Xs=(n,e=!1,t=!1)=>{let i=ct.mse||ct.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&ue.mp4&&$t;case"DASH_WEBM":return i&&ue.webm&&de.vp9&&de.opus;case"DASH_WEBM_AV1":return i&&ue.webm&&de.av1&&de.opus;case"DASH_STREAMS":return i&&(ue.mp4&&$t||ue.webm&&(de.vp9||de.av1)&&(de.opus||de.aac));case"DASH_LIVE":return ct.mse&&ue.mp4&&$t;case"DASH_LIVE_CMAF":return i&&ue.mp4&&$t&&ue.cmaf;case"DASH_ONDEMAND":return i&&ue.mp4&&$t;case"HLS":case"HLS_ONDEMAND":return Lt||e&&ct.mse&&ue.mp4&&$t;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Lt;case"MPEG":return ue.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ct.webrtc&&ct.ws&&de.h264&&(ue.mp4||ue.webm);default:return pr(r)}})},dr=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return pt?pt[t].smooth?[t,e]:pt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return pt?pt[t].powerEfficient?[t,e]:pt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:pr(n)}return[e,t]},Zs=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...dr(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(lr.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...dr(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...dr(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...dr(n),...r,"HLS","HLS_ONDEMAND"];default:pr(e)}return Lt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},en=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,d=lr.isMac&&lr.isSafari;if(lr.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:pr(n)}else Lt&&!d?o=s:d?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},la=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],tn=n=>{if(n.size!==0){if(n.size===1)return n.values().next().value.split(".").at(0);for(let e of n){let t=e.split(".").at(0);if(t==="opus"||t==="vp09"||t==="av01")return t}return n.values().next().value.split(".").at(0)}};import{ErrorCategory as ei}from"@vkontakte/videoplayer-shared";var rn=n=>{if(!n)return{id:"EmptyResponse",category:ei.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:ei.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ei.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ei.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ei.PARSER,message:"Response is valid XML, but parser failed"}};var Mt=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};import{abortable as Pa,assertNonNullable as vt,combine as vr,ErrorCategory as Ze,filter as yr,filterChanged as $n,fromEvent as Ot,interval as wa,isNonNullable as Ln,map as $a,merge as Nt,Subject as Mn,Subscription as Rn,tap as Pd,throttle as wd,clientChecker as $d,ValueSubject as z,flattenObject as $i,getTraceSubscriptionMethod as Ld}from"@vkontakte/videoplayer-shared";import{assertNever as Xu,ErrorCategory as an,clientChecker as ca,Subject as sn}from"@vkontakte/videoplayer-shared";var Zu=16,nn=!1;try{nn=ca.isSafari&&!!ca.macVersion&&ca.macVersion<=Zu}catch(n){console.error(n)}var pa=class{constructor(e){this.bufferFull$=new sn;this.error$=new sn;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:an.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;nn&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:an.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Xu(t)}}},on=pa;var ha=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as Bt,assertNonNullable as Se,ErrorCategory as bt,fromEvent as Ta,getExponentialDelay as Ia,isNonNullable as Ea,isNullable as ve,once as gd,Subject as Sd,Subscription as vd,ValueSubject as Ii}from"@vkontakte/videoplayer-shared";var O=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Rt=class extends O{};var ti=class extends O{};var ii=class extends O{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ri=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var U=class extends O{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ht=class extends U{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,s=r<<1>>>1,o=this.readUint32();r=this.readUint32();let d=r>>>28,u=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:s,subsegmentDuration:o,SAPType:d,SAPDeltaTime:u})}}};var ni=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends U{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var di=class extends U{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var li=class extends U{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ci=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends U{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var hi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends U{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var bi=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends U{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Si=class extends U{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var vi=class extends U{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var td={ftyp:ii,moov:ri,moof:ai,mdat:si,sidx:ht,trak:ni,mdia:ci,mfhd:fi,tkhd:pi,traf:bi,tfhd:gi,tfdt:Si,trun:vi,minf:hi,sv3d:oi,st3d:ui,prhd:di,proj:mi,equi:li,uuid:ti,unknown:Rt},mt=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch{break}return t}createBox(e,t){let i=td[e];return i?new i(t,new n):new Rt(t,new n)}};var Dt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var rd=new TextDecoder("ascii"),ad=n=>rd.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",sd=n=>{let e=new ht(n,new mt),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},nd=(n,e)=>{let i=new mt().parse(n),r=new Dt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],d=s[s.length-1],u=o.source.byteOffset,l=d.source.byteOffset-o.source.byteOffset+d.size;return new DataView(n.buffer,u,l)},od=(n,e)=>{let i=new mt().parse(n),a=new Dt(i).findAll("traf"),s=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),d=a[a.length-1].children.find(l=>l.type==="trun"),u=0;return d.sampleDuration.length?u=d.sampleDuration.reduce((l,p)=>l+p,0):u=s.defaultSampleDuration*d.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},ud=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new mt().parse(n),r=new Dt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let d=r.find("equi");d&&(e.projectionData.bounds.top=d.projectionBoundsTop,e.projectionData.bounds.right=d.projectionBoundsRight,e.projectionData.bounds.bottom=d.projectionBoundsBottom,e.projectionData.bounds.left=d.projectionBoundsLeft)}return e},un={validateData:ad,parseInit:ud,getIndexRange:()=>{},parseSegments:sd,parseFeedableSegmentChunk:nd,getSegmentEndTime:od};import{assertNonNullable as fa,isNonNullable as pn,isNullable as ld}from"@vkontakte/videoplayer-shared";import{assertNever as dd}from"@vkontakte/videoplayer-shared";var dn={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},ln=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=yi(n,t),r=i in dn,a=r?dn[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let d=new DataView(n.buffer,n.byteOffset+t+1,o-1),u=s&255>>o,c=yi(d),l=u*2**((o-1)*8)+c,p=t+o,h;return p+l>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},yi=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ke=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return yi(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:dd(e)}},ft=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=ln(i);if(!e(r))return;r.type==="master"&&ft(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},cn=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=ln(n);return ft(r.value,({tag:a,type:s,value:o})=>(a===17143?e=ke(o,s):a===17026?t=ke(o,s):a===17029&&(i=ke(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var hn=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],cd=[231,22612,22743,167,171,163,160,175],pd=n=>{let e,t,i,r,a=!1,s=!1,o=!1,d,u,c=!1,l=0;return ft(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let g=ke(m,h);u=yi(g)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=ke(m,h):p===17545?r=ke(m,h):p===21420&&u===475249515?d=ke(m,h):p===374648427?ft(m,({tag:g,type:P,value:R})=>g===30321?(c=ke(R,P)===1,!1):!0):a&&s&&hn.includes(p)&&(o=!0),!o}),fa(e,"Failed to parse webm Segment start"),fa(t,"Failed to parse webm Segment end"),fa(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},hd=n=>{if(ld(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},md=(n,e)=>{let t=!1,i=!1,r=o=>pn(o.time)&&pn(o.position),a=[],s;return ft(n,({tag:o,type:d,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=ke(u,d));break;case 183:break;case 241:s&&(s.position=ke(u,d));break;default:t&&hn.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,d)=>{let{time:u,position:c}=o,l=a[d+1];return{status:"none",time:{from:u,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},fd=n=>{let e=0,t=!1;try{ft(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):cd.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},mn={validateData:cn,parseInit:pd,getIndexRange:hd,parseSegments:md,parseFeedableSegmentChunk:fd};var Ct=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return mn;case"mp4":return un}}throw new ReferenceError(`Unsupported mime type ${n}`)};var ba=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as bn,isNullable as gn}from"@vkontakte/videoplayer-shared";var fn=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Sn=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let d=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(d)?0:d)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ue=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,d)=>gn(a)?o:gn(d)?a:a.padStart(parseInt(d,10),"0"))}return t},vn=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=a.querySelector("BaseURL")?.textContent?.trim()??"",d=s.children,u=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=c?new Date(c).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),g=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Sn(h);else if(m){let b=Sn(m);bn(b)&&(p=b)}else g&&(p=parseInt(g,10));let P=0,R=a.getAttribute("profiles")?.split(",")??[];for(let b of d){let v=b.getAttribute("id")??"id"+(P++).toString(10),T=b.getAttribute("mimeType")??"",D=b.getAttribute("codecs")??"",V=b.getAttribute("contentType")??T?.split("/")[0],N=b.getAttribute("profiles")?.split(",")??[],k=b.getAttribute("lang")??void 0,A=b.querySelector("Label")?.textContent?.trim()??void 0,w=b.querySelectorAll("Representation"),F=b.querySelector("SegmentTemplate"),ye=b.querySelector("Role")?.getAttribute("value")??void 0,Z=V,I={id:v,language:k,isDefault:ye==="main",label:A,codecs:D,hdr:Z==="video"&&ba(D),mime:T,representations:[]};for(let x of w){let H=x.getAttribute("lang")??void 0,Y=x.getAttribute("label")??void 0,le=x.querySelector("BaseURL")?.textContent?.trim()??"",Pe=new URL(le||o,e).toString(),Tt=x.getAttribute("mimeType")??T,at=x.getAttribute("codecs")??D??"",C;if(V==="text"){let Q=x.getAttribute("id")||"",ee=Q.includes("_auto"),j=x.querySelector("SegmentTemplate");if(!j)throw new Error("Unknown MPD segment text referencing type");let Te={representationId:x.getAttribute("id")??void 0,bandwidth:x.getAttribute("bandwidth")??void 0},Qe=parseInt(x.getAttribute("bandwidth")??"",10)/1e3,we=parseInt(j.getAttribute("startNumber")??"",10)??1,Ie=parseInt(j.getAttribute("timescale")??"",10),st=j.querySelectorAll("SegmentTimeline S")??[],Ce=j.getAttribute("media");if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let Gi=[],Wi=0,Yi="",It=0,Ft=we,K=0;for(let Ee of st){let nt=parseInt(Ee.getAttribute("d")??"",10),he=parseInt(Ee.getAttribute("r")??"",10)||0,je=parseInt(Ee.getAttribute("t")??"",10);K=Number.isFinite(je)?je:K;let ot=nt/Ie*1e3,Et=K/Ie*1e3;for(let $e=0;$e<he+1;$e++){let Ge=Ue(Ce,{...Te,segmentNumber:Ft.toString(10),segmentTime:(K+$e*nt).toString(10)}),xt=(Et??0)+$e*ot,Ht=xt+ot;Ft++,Gi.push({time:{from:xt,to:Ht},url:Ge})}K+=(he+1)*nt,Wi+=(he+1)*ot}It=K/Ie*1e3,Yi=Ue(Ce,{...Te,segmentNumber:Ft.toString(10),segmentTime:K.toString(10)});let Ut={time:{from:It,to:1/0},url:Yi},Be={type:"template",baseUrl:Pe,segmentTemplateUrl:Ce,initUrl:"",totalSegmentsDurationMs:Wi,segments:Gi,nextSegmentBeyondManifest:Ut,timescale:Ie};C={id:Q,kind:"text",segmentReference:Be,profiles:[],duration:p,bitrate:Qe,mime:"",codecs:"",width:0,height:0,isAuto:ee}}else{let Q=x.getAttribute("contentType")??Tt?.split("/")[0]??V,ee=b.getAttribute("profiles")?.split(",")??[],j=parseInt(x.getAttribute("width")??"",10),Te=parseInt(x.getAttribute("height")??"",10),Qe=parseInt(x.getAttribute("bandwidth")??"",10)/1e3,we=x.getAttribute("frameRate")??"",Ie=x.getAttribute("quality")??void 0,st=we?fn(we):void 0,Ce=x.getAttribute("id")??"id"+(P++).toString(10),Gi=Q==="video"?`${Te}p`:Q==="audio"?`${Qe}Kbps`:at,Wi=`${Ce}@${Gi}`,Yi=[...R,...N,...ee],It,Ft=x.querySelector("SegmentBase"),K=x.querySelector("SegmentTemplate")??F;if(Ft){let Be=x.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ee,nt]=Be.split("-").map(Ge=>parseInt(Ge,10)),he={from:Ee,to:nt},je=x.querySelector("SegmentBase")?.getAttribute("indexRange"),[ot,Et]=je?je.split("-").map(Ge=>parseInt(Ge,10)):[],$e=je?{from:ot,to:Et}:void 0;It={type:"byteRange",url:Pe,initRange:he,indexRange:$e}}else if(K){let Be={representationId:x.getAttribute("id")??void 0,bandwidth:x.getAttribute("bandwidth")??void 0},Ee=parseInt(K.getAttribute("timescale")??"",10),nt=K.getAttribute("initialization")??"",he=K.getAttribute("media"),je=parseInt(K.getAttribute("startNumber")??"",10)??1,ot=Ue(nt,Be);if(!he)throw new ReferenceError("No media attribute in SegmentTemplate");let Et=K.querySelectorAll("SegmentTimeline S")??[],$e=[],Ge=0,xt="",Ht=0;if(Et.length){let qi=je,xe=0;for(let kt of Et){let Le=parseInt(kt.getAttribute("d")??"",10),ut=parseInt(kt.getAttribute("r")??"",10)||0,zi=parseInt(kt.getAttribute("t")??"",10);xe=Number.isFinite(zi)?zi:xe;let Fr=Le/Ee*1e3,$o=xe/Ee*1e3;for(let Ki=0;Ki<ut+1;Ki++){let Lo=Ue(he,{...Be,segmentNumber:qi.toString(10),segmentTime:(xe+Ki*Le).toString(10)}),Wa=($o??0)+Ki*Fr,Mo=Wa+Fr;qi++,$e.push({time:{from:Wa,to:Mo},url:Lo})}xe+=(ut+1)*Le,Ge+=(ut+1)*Fr}Ht=xe/Ee*1e3,xt=Ue(he,{...Be,segmentNumber:qi.toString(10),segmentTime:xe.toString(10)})}else if(bn(p)){let xe=parseInt(K.getAttribute("duration")??"",10)/Ee*1e3,kt=Math.ceil(p/xe),Le=0;for(let ut=1;ut<kt;ut++){let zi=Ue(he,{...Be,segmentNumber:ut.toString(10),segmentTime:Le.toString(10)});$e.push({time:{from:Le,to:Le+xe},url:zi}),Le+=xe}Ht=Le,xt=Ue(he,{...Be,segmentNumber:kt.toString(10),segmentTime:Le.toString(10)})}let wo={time:{from:Ht,to:1/0},url:xt};It={type:"template",baseUrl:Pe,segmentTemplateUrl:he,initUrl:ot,totalSegmentsDurationMs:Ge,segments:$e,nextSegmentBeyondManifest:wo,timescale:Ee}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Q||!Tt)continue;let Ut={video:"video",audio:"audio",text:"text"}[Q];if(!Ut)continue;Z||=Ut,C={id:Wi,kind:Ut,segmentReference:It,profiles:Yi,duration:p,bitrate:Qe,mime:Tt,codecs:at,width:j,height:Te,fps:st,quality:Ie}}I.language||=H,I.label||=Y,I.mime||=Tt,I.codecs||=at,I.hdr||=Z==="video"&&ba(at),I.representations.push(C)}Z&&r[Z].push(I)}return{dynamic:u,liveAvailabilityStartTime:l,duration:p,streams:r}};import{videoSizeToQuality as bd}from"@vkontakte/videoplayer-shared";var yn=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{let s=(a?Ke(a):void 0)??bd({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},Tn=({id:n,bitrate:e})=>({id:n,bitrate:e}),hr=(n,e,t)=>{let i=e.indexOf(n);return t.at(Math.round(t.length*i/e.length))??t.at(-1)},In=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),va=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),ya=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),mr=n=>"url"in n,ge=n=>n.type==="template",Ti=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Ei=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:d=!1,manifest:u}){this.currentSegmentLength$=new Ii(0);this.onLastSegment$=new Ii(!1);this.fullyBuffered$=new Ii(!1);this.playingRepresentation$=new Ii(void 0);this.playingRepresentationInit$=new Ii(void 0);this.error$=new Sd;this.gaps=[];this.subscription=new vd;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Bt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Se(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new on(this.sourceBuffer),this.subscription.add(Ta(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,d=this.mediaSource.readyState;d!=="open"&&(o={id:`SegmentEjection_source_${d}`,category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(Ta(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:bt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let d=Math.min(this.bufferLimit,ha(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=d,this.tuning.useNewPruneBufferStrategy){let u=_e(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,u<c)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Se(i,"No init buffer for starting representation"),Se(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Bt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Se(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ve(a)||ve(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Se(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let s=this.getCurrentPosition();Ea(s)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Bt(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(d=>d.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let u=t.find(p=>p.id===d);u&&this.representations.set(d,u);let c=this.representations.get(d);if(!c||!ge(c.segmentReference))return;let l=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Se(r);let a=this.segments.get(i);Se(a,"No segments for starting representation");let s=this.initData.get(i);if(Se(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=d,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!u?.dynamic,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!ve(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Se(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=_e(this.sourceBuffer.buffered,e),l=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(a=l)}if(isFinite(this.bufferLimit)&&ha(this.sourceBuffer.buffered)>=this.bufferLimit){let u=_e(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))u="high";else{let c=o.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&_e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=i.at(-1);d&&d.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;Ea(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!ge(i.segmentReference))return;let r=i.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),a=this.segments.get(i.id)??[],s=a.at(-1)?.time.to??0,o=r?.findIndex(d=>Math.floor(s)>=Math.floor(d.time.from)&&Math.floor(s)<=Math.floor(d.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,d)}else{let d=r.slice(o+1);this.segments.set(i.id,[...a,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Se(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!ge(i))return;let r=this.segments.get(t.id)??[],a=r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to),!!!r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),d=Ue(i.segmentTemplateUrl,{segmentTime:o});r.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:l,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,g=p>i||f||m===0&&i===0,P=Math.min(this.forwardBufferTarget,this.bufferLimit),R=this.preloadOnly&&p<=i+P||h<=i+P;return(l==="none"||l==="partially_ejected"&&g&&R&&this.sourceBuffer&&!(Mt(this.sourceBuffer.buffered,p)&&Mt(this.sourceBuffer.buffered,h)))&&g&&R});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(s<=u||o<=c);l++){let p=a[l];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")d.push(p);else break}return d}async loadSegments(e,t,i="auto"){ge(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:d,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Bt(o,async function*(){let c=Ia(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;let l=new DataView(c);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=Ct(t.mime);r.segment.time.to=h.getSegmentEndTime(l,p)}d&&r.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(l,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ti(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let d of e)d.status="downloading",this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await Bt(s,async function*(){let d=Ia(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,d),Ta(window,"online").pipe(gd()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(d){this.abortActiveSegments(e),Ti(d)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(ge(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ge(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!a.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let s=this.representations.get(t);if(s)for(let o of this.activeSegments){let{segment:d}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Ct(s.mime).parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(d.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let d=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:l}=c,p=d==="byteRange",h=p?l.byte.to-l.byte.from+1:u;if(c.representationId!==t||!(!p||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let f=p?l.byte.from-i:0,g=p?l.byte.to-i:e.byteLength,P=f<r,R=g<=r;if(l.status==="downloading"&&P&&R){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+f,h),b=this.getCurrentPosition();Ea(b)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-b,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:c}),this.activeSegments.delete(c));let v=({segmentView:T,segmentProgress:D})=>this.sourceBufferTaskQueue.append(T,a).then(V=>V&&!a.aborted?this.onSegmentFullyAppended(D,t):s());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(v),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||ve(b))&&(v({segmentView:S,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&P&&!R&&(c.loadedBytes=Math.min(h,r-f),c.loadedBytes>c.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+f+c.feedingBytes,c.loadedBytes-c.feedingBytes),b=c.loadedBytes===h?S:Ct(o.mime).parseFeedableSegmentChunk(S);b?.byteLength&&(l.status="partially_fed",c.feedingBytes+=b.byteLength,this.sourceBufferTaskQueue.append(b,a).then(v=>{if(a.aborted)s();else if(v)c.fedBytes+=b.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;s()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let d of this.activeSegments){let{segment:u}=d;if(d.representationId!==t)continue;if(a.aborted){s();continue}let c=u.byte.from-i,l=u.byte.to-i,p=l-c+1,h=c<r,m=l<=r;if(h){if(u.status==="downloading"&&m){u.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(f,a)&&!a.aborted?this.onSegmentFullyAppended(d,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.status==="downloading"||u.status==="partially_fed")&&(d.loadedBytes=Math.min(p,r-c),d.loadedBytes>d.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+c+d.feedingBytes,d.loadedBytes-d.feedingBytes),g=d.loadedBytes===p?f:Ct(o.mime).parseFeedableSegmentChunk(f);g?.byteLength&&(u.status="partially_fed",d.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(d.fedBytes+=g.byteLength,d.fedBytes===p&&this.onSegmentFullyAppended(d,t)):s())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",mr(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");Se(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;t||=s,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?Bt(this.destroyAbortController.signal,async function*(){let o=Ia(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ct(e.mime),r)).then(async o=>{if(!o)return;let{init:d,dataView:u,segments:c}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l);let p=c;this.isLive&&ge(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:bt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ve(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=d=>{d.sort((c,l)=>c.from-l.from);let u=[d[0]];for(let c=1;c<d.length;c++){let{from:l,to:p}=d[c],h=u[u.length-1];h.to>=l?h.to=Math.max(h.to,p):u.push(d[c])}return u},o=d=>{if(a>=t)return r;r.push({...d.time}),r=s(r);let u=mr(d)?d.size??0:d.byte.to-d.byte.from;a+=u};for(let d of this.segments.values())for(let u of d){let c=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||l)&&u.status==="fed"&&o(u)}for(let d=0;d<this.sourceBuffer.buffered.length;d++){let u=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3,l=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(c)&&l++;if(l===this.segments.size){let p={time:{from:u,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let c of u)c.time.from>=e+d&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,c)=>u||c,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ve(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,d=u=>{a=Math.min(a,u.time.from),s=Math.max(s,u.time.to);let c=mr(u)?u.size??0:u.byte.to-u.byte.from;r+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&d(c)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&d(c)}}if(o=isFinite(a)&&isFinite(s),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)){a=c,s=l;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>e+u&&l.status==="fed"&&d(l)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){Se(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:bt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||ve(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),d=e.some(c=>c.from-t<=s&&c.to+t>=o),u=e.filter(c=>s>=c.from&&s<c.to-t||o>c.from+t&&o<=c.to);d||(u.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var xi=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var En=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ki,assertNever as xn,fromEvent as kn,merge as yd,now as Ai,Subscription as Td,ValueSubject as xa,flattenObject as Vt}from"@vkontakte/videoplayer-shared";var fr=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1}){this.lastConnectionType$=new xa(void 0);this.lastConnectionReused$=new xa(void 0);this.lastRequestFirstBytes$=new xa(void 0);this.abortAllController=new AbortController;this.subscription=new Td;this.fetchManifest=ki(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=xi(i));let r=yield fetch(i,{signal:this.abortAllController.signal}).catch(Pi);return r?(t.log("success",Vt({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Vt({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ki(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:d=!1}={}){let u=e,c=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(u,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),u=A.toString();break}default:xn(t)}this.requestQuic&&(u=xi(u));let p=this.abortAllController.signal,h;if(s){let A=new AbortController;if(h=yd(kn(this.abortAllController.signal,"abort"),kn(s,"abort")).subscribe(()=>{try{A.abort()}catch(w){Pi(w)}}),this.abortAllController.signal.aborted||s.aborted)try{A.abort()}catch(w){Pi(w)}p=A.signal}let m=Ai();l.log("startRequest",Vt({url:u,priority:a,rangeMethod:t,range:i,isLowLatency:d,requestStartedAt:m}));let f=yield fetch(u,{priority:a,headers:c,signal:p}).catch(Pi),g=Ai();if(!f)return l.error("error",{message:"No response in request"}),l.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!f.ok||!f.body){h?.unsubscribe();let A=`Fetch error ${f.status}: ${f.statusText}`;return l.error("error",{message:A}),l.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let A=Ai(),w={requestStartedAt:m,requestEndedAt:A,duration:A-m};return l.log("endRequest",Vt(w)),l.end(),f.arrayBuffer()}let[P,R]=f.body.tee(),S=P.getReader();o&&this.throughputEstimator?.trackStream(R,d);let b=0,v=new Uint8Array(0),T=!1,D=A=>{h?.unsubscribe(),T=!0,Pi(A)},V=ki(p,async function*({done:A,value:w}){if(b===0&&this.lastRequestFirstBytes$.next(Ai()-m),p.aborted){h?.unsubscribe();return}if(!A&&w){let F=new Uint8Array(v.length+w.length);F.set(v),F.set(w,v.length),v=F,b+=w.byteLength,r?.(new DataView(v.buffer),b),yield S?.read().then(V,D)}}.bind(this));yield S?.read().then(V,D),h?.unsubscribe();let N=Ai(),k={failed:T,requestStartedAt:m,requestEndedAt:N,duration:N-m};return T?(l.error("endRequest",Vt(k)),l.end(),null):(l.log("endRequest",Vt(k)),l.end(),v.buffer)}.bind(this));this.fetchByteRangeRepresentation=ki(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,d=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,d=a+1===u,d&&(s=Math.min(u,r),o=Math.max(c,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(d)f=new DataView(l,m.from-s,m.to-m.from+1);else{let P=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!P)return null;f=new DataView(P)}let g=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(l),segments:g}}.bind(this));this.fetchTemplateRepresentation=ki(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(s=>({...s,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:i}=En(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:xn(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Pi=n=>{if(!Ti(n))throw n};var gt=(n,e,t)=>t*e+(1-t)*n,ka=(n,e)=>n.reduce((t,i)=>t+i,0)/e,An=(n,e,t,i)=>{let r=0,a=t,s=ka(n,e),o=e<i?e:i;for(let d=0;d<o;d++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as Id,ValueSubject as Pn}from"@vkontakte/videoplayer-shared";var Xe=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Pn(e.initial),this.debounced$=new Pn(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new J(`raw_${t}`),this.smoothedSeries$=new J(`smoothed_${t}`),this.reportedSeries$=new J(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(Id(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var br=class extends Xe{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=gt(this.slow,e,this.params.emaAlphaSlow),this.fast=gt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var gr=class extends Xe{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ka(this.pastMeasures,this.takenMeasures);this.emaSmoothed=gt(this.emaSmoothed,e,this.params.emaAlpha);let i=An(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Sr=class extends Xe{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?gt(this.smoothed,t,this.params.emaAlpha):t}};var St=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new br({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Sr({initial:e,label:"liveEdgeDelay",...t})}};var Aa=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as Ed,ValueSubject as xd}from"@vkontakte/videoplayer-shared";var wi=class n{constructor(e,t){this.currentRepresentation$=new xd(null);this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Ed(e))for(let t of this.representations){let i=t.segmentReference.segments.find(r=>r.time.from<=e&&r.time.to>=e);if(!i||this.currentSegment?.time.from===i.time.from&&this.currentSegment.time.to===i.time.to)return;this.currentSegment=i,this.currentRepresentation$.next({...t,label:"Live Text",language:"ru",isAuto:!0,url:new URL(i.url,t.segmentReference.baseUrl).toString()})}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations=i;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ge(t.segmentReference))}};var Dn=["timeupdate","progress","play","seeked","stalled","waiting"];var Tr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Rn;this.representationSubscription=new Rn;this.state$=new $("none");this.currentVideoRepresentation$=new z(void 0);this.currentVideoRepresentationInit$=new z(void 0);this.currentAudioRepresentation$=new z(void 0);this.currentVideoSegmentLength$=new z(0);this.currentAudioSegmentLength$=new z(0);this.error$=new Mn;this.lastConnectionType$=new z(void 0);this.lastConnectionReused$=new z(void 0);this.lastRequestFirstBytes$=new z(void 0);this.currentLiveTextRepresentation$=new z(null);this.isLive$=new z(!1);this.liveDuration$=new z(0);this.liveAvailabilityStartTime$=new z(void 0);this.bufferLength$=new z(0);this.liveLoadBufferLength$=new z(0);this.livePositionFromPlayer$=new z(0);this.timeInWaiting=0;this.isActiveLowLatency$=new z(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Mn;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Pa(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=q(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ze.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Pa(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ze.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t=null;try{t=vn(e??"",this.manifestUrlString)}catch(s){let o=rn(e)??{id:"ManifestParsing",category:Ze.PARSER,message:"Failed to parse MPD manifest",thrown:s};this.error$.next(o)}if(!t)return null;let i=(s,o,d)=>!!(this.element?.canPlayType?.(o)&&Fe()?.isTypeSupported?.(`${o}; codecs="${d}"`)||s==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let s of["video","audio"]){let d=t.streams[s].filter(({mime:l,codecs:p})=>i(s,l,p)),u=new Set(d.map(({codecs:l})=>l)),c=tn(u);if(c&&(r[s]=d.filter(({codecs:l})=>l.startsWith(c))),s==="video"){let l=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);$d.isHDR&&l&&p?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",$i(a)),a}.bind(this));this.initRepresentations=Pa(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",$i({initialVideo:e,initialAudio:t,sourceHls:i})),vt(this.manifest),vt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(Ot(l,"error").pipe(yr(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ze.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?qs():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&ur())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new Ei("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],Ln(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new Ei("audio",this.source,l,s),this.bufferManagers.push(this.audioBufferManager)}if(wi.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new wi(this.manifest.streams.text,s)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(wa(1e3).subscribe(l=>{if(this.element?.paused){let p=Gr(this.manifestUrlString,2);this.manifestUrlString=q(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(Nt(...Dn.filter(l=>l!=="waiting").map(l=>Ot(this.element,l))).pipe($a(l=>this.element?_e(this.element.buffered,this.element.currentTime*1e3):0),$n(),yr(l=>!!l),Pd(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe($n()).subscribe(p=>Aa(this.element,1))),this.representationSubscription.add(vr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(yr(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(vr({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,f=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=p-m,R=1;Math.abs(P)>f&&(R=1+Math.sign(P)*g),Aa(this.element,R)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(wd(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(vt(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,f=Gr(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),R=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,b=isFinite(p)?p:h,v=this.isActiveLowLatency$.getValue(),T=g<=this.tuning.live.activeLiveDelay&&f===0;this.isActiveLowLatency$.next(v&&T);let D="none";if(v?D="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&T?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),D="active_low_latency"):f!==0&&b<P?D="live_forward_buffering":b<P+S&&(D="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),D==="live_forward_buffering"||D==="live_with_target_offset"){let V=l-(P+R),N=this.normolizeLiveOffset(Math.trunc(f+V/m)),k=Math.abs(N-f),A;!p||k<=this.tuning.dashCmafLive.offsetCalculationError?A=f:N>0&&k>this.tuning.dashCmafLive.offsetCalculationError?A=N:A=0,this.manifestUrlString=q(this.manifestUrlString,A,2)}D!=="none"&&D!=="active_low_latency"&&(l=0,this.updateLive())}))}let d=Nt(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe($a(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),u=Nt(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe($a(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(Nt(this.forceEnded$,vr({allBuffersFull:d,someBufferEnded:u}).pipe(yr(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:Ze.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(Nt(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(l=>this.source?.addEventListener("sourceopen",l)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>{let p=[];return l.duration&&p.push(l.duration),ge(l.segmentReference)&&l.segmentReference.totalSegmentsDurationMs&&p.push(l.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Ln(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=wa(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ze.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new fr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=St.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){vt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=q(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){vt(this.element),this.state$.setState("running"),this.subscription.add(Nt(...Dn.map(e=>Ot(this.element,e)),Ot(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ze.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ot(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ot(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Mt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;this.timeInWaiting+=1e3;let t={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),t={...t,liveLastSeekOffset:this.liveLastSeekOffset};else{let i=this.element.currentTime*1e3;this.videoBufferManager?.maintain(i),this.audioBufferManager?.maintain(i),t={...t,position:i}}this.tracer.log("stallIntervalCallback",$i(t))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=wa(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ze.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){vt(this.element),vt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Mt(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",$i({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Ld(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let o of s.gaps)s.playingRepresentation$.getValue()===o.representation&&o.from-a<=i&&o.to+a>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():(this.element.currentTime=s/1e3,t={...t,gapEnds:r,jumpTo:s,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",$i(t)))}}};var Ir=class{constructor(e,t){this.fov=e,this.orientation=t}};var Er=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Cn=`attribute vec2 a_vertex;
|
|
59
59
|
attribute vec2 a_texel;
|
|
60
60
|
|
|
61
61
|
varying vec2 v_texel;
|
|
@@ -66,7 +66,7 @@ void main(void) {
|
|
|
66
66
|
// save texel vector to pass to fragment shader
|
|
67
67
|
v_texel = a_texel;
|
|
68
68
|
}
|
|
69
|
-
`;var
|
|
69
|
+
`;var Bn=`#ifdef GL_ES
|
|
70
70
|
precision highp float;
|
|
71
71
|
precision highp int;
|
|
72
72
|
#else
|
|
@@ -109,5 +109,5 @@ void main(void) {
|
|
|
109
109
|
// sample using new coordinates
|
|
110
110
|
gl_FragColor = texture2D(u_texture, tc);
|
|
111
111
|
}
|
|
112
|
-
`;var hr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new cr(this.params.fov,this.params.orientation),this.cameraRotationManager=new pr(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($n,this.gl.VERTEX_SHADER),i=this.createShader(Ln,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,d=t-r,u=e+i,c=t+r,l=e-i,p=t+r;return[a,s,o,d,u,c,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var ct=class{constructor(e){this.subscription=new Nd;this.videoState=new $("stopped");this.elementSize$=new Fd(void 0);this.textTracksManager=new pe;this.droppedFramesManager=new zi;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _t;this.audioTrackSwitchHistory=new _t;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let s=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-s,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&y(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Rd(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new hr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ee(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(j(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new lr({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=re(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:xa.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,d)=>this.subscription.add(o.subscribe(d,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Mn(u=>!!u.length),Dn()).subscribe(u=>{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:u})})),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(Mn(Vd),Dn()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(Rn(u=>u.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(xe(this.video,t.isLooped,r)),this.subscription.add(ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ce(this.video,t.playbackRate,i.playbackRateState$,r)),a(_d(this.video),this.elementSize$),a(me(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(Dd(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(ha(h));let m=[];for(let f of h.representations){let S=bn(f);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of c.video){l.push(ma(p));let h=[];for(let m of p.representations){let f=fn(m);f&&(h.push(f),this.videoTracksMap.set(f,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(l);for(let p of c.text)for(let h of p.representations){let m=Sn(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=u=>e.error$.next({id:"RepresentationSwitch",category:xa.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(mr(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Bd(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,h]=l,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(s),h){let f=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,f).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ka()).subscribe(u=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{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(l),e.currentVideoStream$.next(ma(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ka()).subscribe(u=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!c){e.currentAudioStream$.next(void 0);return}let[l,{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(ha(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),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(Rn(({to:u})=>u==="ready"),ka());this.subscription.add(mr(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(mr(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=mr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Od(["init"])).pipe(Cd(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:T})=>T===r),o=t.currentVideoTrack$.getValue(),d=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let u=[...this.videoStreamsMap.keys()].find(({id:T})=>T===d.id),c=u&&this.videoStreamsMap.get(u);if(!c)return;let l=$e(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),f=[...this.audioStreamsMap.keys()].find(({id:T})=>T===m?.id)??this.audioStreamsMap.keys().next().value,S=0;if(f){if(s&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let T=Gi(s,c,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,T?.bitrate??-1/0)}else{let T=ir(s,c,this.audioStreamsMap.get(f)??[]);S=Math.max(S,T?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let T=Gi(o,c,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,T?.bitrate??-1/0)}else{let T=ir(o,c,this.audioStreamsMap.get(f)??[]);S=Math.max(S,T?.bitrate??-1/0)}}let A=Ue(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),R=i?A??s:s??A,g;this.params.tuning.useSeparateAudioVideoABR?g=f&&$s(R,c,this.audioStreamsMap.get(f)??[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):g=f&&ir(R,c,this.audioStreamsMap.get(f)??[]);let b=this.videoTracksMap.get(R)?.representation,v=g&&this.audioTracksMap.get(g)?.representation;if(b&&v)return[b,v];if(b&&!v&&this.audioTracksMap.size===0)return[b,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){se(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xa.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),te(this.video),this.tracer.end()}};var Ti=class extends ct{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 Cn,interval as Ud,map as Hd}from"@vkontakte/videoplayer-shared";var Ii=class extends ct{constructor(e){super(e),this.liveOffset=new Pe}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Cn({interval:Ud(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()==="playing"){let a=e.position$.getValue()+(r-1);a<=0&&e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(Cn({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Hd(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(s,r)})}};import{assertNever as Ei,assertNonNullable as Bn,debounce as Qd,ErrorCategory as fr,filter as jd,isNonNullable as Gd,isNullable as Wd,map as br,merge as Yd,Observable as qd,observableFrom as zd,Subscription as Kd,videoSizeToQuality as Jd}from"@vkontakte/videoplayer-shared";var Te={};var Lt=(n,e)=>new qd(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),xi=class{constructor(e){this.subscription=new Kd;this.videoState=new $("initializing");this.textTracksManager=new pe;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:Ei(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ei(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ei(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ei(e)}break;default:Ei(t)}};this.video=ee(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(j(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),te(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:fr.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||(Te.Hls=r.default,Te.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){Bn(Te.Hls,"hls.js not loaded"),this.hls=new Te.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Bn(Te.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:fr.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=re(this.video),a=(u,c)=>this.subscription.add(u.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(xe(this.video,e.isLooped,i)),this.subscription.add(ie(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ce(this.video,e.playbackRate,r.playbackRateState$,i)),a(me(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(br(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Lt(this.hls,Te.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:fr.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Lt(this.hls,Te.Events.MANIFEST_PARSED).pipe(br(({levels:u})=>u.reduce((c,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,f=Fe(l.attrs.QUALITY??"")??Jd({width:h,height:m});if(!f)return c;let S=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,A={id:p.toString(),quality:f,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:A,level:l}),c.push(A),c},[]))),t.availableVideoTracks$),a(Lt(this.hls,Te.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let l of u.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),a(Lt(this.hls,Te.Events.LEVEL_LOADING).pipe(br(({url:u})=>j(u))),t.hostname$),a(Lt(this.hls,Te.Events.FRAG_CHANGED),u=>{let{video:c,audio:l}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(Oe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));let s=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=Lt(this.hls,Te.Events.LEVEL_SWITCHED).pipe(br(({level:u})=>s(this.hls.levels[u])));o.pipe(jd(Gd)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Oe(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),u=>{if(Wd(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let l=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let d=Yd(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zd(["init"])).pipe(Qd(0));this.subscription.add(d.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 se(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fr.DOM,thrown:t}))||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0)}};var Vn="X-Playback-Duration",Aa=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(Vn)?parseInt(e.headers.get(Vn),10):void 0};import{assertNever as rl,combine as al,debounce as sl,ErrorCategory as gr,filter as nl,filterChanged as ol,isNonNullable as _n,isNullable as vr,map as Nn,merge as ul,observableFrom as dl,Subscription as ll,ValueSubject as wa,VideoQuality as cl}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as Xd,getExponentialDelay as Zd}from"@vkontakte/videoplayer-shared";var el=n=>{let e=null;if(n.QUALITY&&(e=Fe(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Xd({width:t,height:i})}return e??null},tl=(n,e)=>{let t=n.split(`
|
|
113
|
-
`),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),d=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!d)){if(o){let u=Object.fromEntries(o[1].split(",").map(S=>S.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,l=el(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[S,A]=u.RESOLUTION.split("x").map(R=>parseInt(R,10));S&&A&&(m={width:S,height:A})}let f=new URL(t[++a],e).toString();l&&i.push({id:c,quality:l,url:f,bandwidth:p,size:m,fps:h})}if(d){let u=Object.fromEntries(d[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),l=u.LANGUAGE,p=u.NAME;c&&l&&r.push({type:"internal",id:l,label:p,language:l,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},il=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Pa=0,On=async(n,e=n,t)=>{let r=await(await fetch(n)).text();Pa+=1;try{let{qualityManifests:a,textTracks:s}=tl(r,e);return{qualityManifests:a,textTracks:s}}catch{if(Pa<=t.manifestRetryMaxCount)return await il(Zd(Pa-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),On(n,e,t)}return{qualityManifests:[],textTracks:[]}},Sr=On;var ki=class{constructor(e){this.subscription=new ll;this.videoState=new $("stopped");this.textTracksManager=new pe;this.manifests$=new wa([]);this.liveOffset=new Pe;this.manifestStartTime$=new wa(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=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),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(y(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return rl(t)}};this.params=e,this.video=ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:cl.INVARIANT,url:this.params.source.url},Sr(Y(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:gr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:gr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(j(this.params.source.url)),this.maxSeekBackTime$=new wa(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(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:gr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=re(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,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(ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ce(this.video,t.playbackRate,r.playbackRateState$,i)),a(me(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ol(),Nn(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&_n(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(j(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from==="changing_manifest"&&this.videoState.setState(d.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(al({startTime:this.manifestStartTime$.pipe(nl(_n)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:d})=>this.params.output.liveTime$.next(o+d*1e3),i)),this.subscription.add(this.manifests$.pipe(Nn(o=>o.map(({id:d,quality:u,size:c,bandwidth:l,fps:p})=>({id:d,quality:u,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let s=ul(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,dl(["init"])).pipe(sl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.selectManifest();if(vr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:d}=t?.to??i??{};for(let[u,c]of[[o,"mq"],[d,"lq"]]){let l=String(parseFloat(u||""));c&&u&&r.searchParams.set(c,l)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=Y(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),Aa(s).then(o=>{if(!vr(o))this.maxSeekBackTime$.next(o);else{let d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(vr(d)||!isFinite(d))try{fetch(s).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let l=new URL(c,s).toString();Aa(l).then(p=>{vr(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){se(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gr.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as pl,debounce as hl,ErrorCategory as $a,fromEvent as La,isNonNullable as ml,isNullable as fl,map as Fn,merge as Un,observableFrom as Hn,Subscription as bl,ValueSubject as Sl,VideoQuality as gl,clientChecker as vl}from"@vkontakte/videoplayer-shared";var Ai=class{constructor(e){this.subscription=new bl;this.videoState=new $("stopped");this.textTracksManager=new pe;this.manifests$=new Sl([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=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:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return pl(t)}};this.params=e,this.video=ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:gl.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(j(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Sr(Y(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:$a.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:$a.WTF,message:"HlsProvider internal logic error",thrown:o})},r=re(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d));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(Fn(o=>o.to)),this.params.output.playbackState$),this.subscription.add(xe(this.video,t.isLooped,i)),this.subscription.add(ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ce(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&ml(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(j(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(h),f.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from==="changing_manifest"&&this.videoState.setState(d.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(Fn(o=>o.map(({id:d,quality:u,size:c,bandwidth:l,fps:p})=>({id:d,quality:u,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!vl.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Un(La(o,"addtrack"),La(o,"removetrack"),La(o,"change"),Hn(["init"])).subscribe(()=>{for(let d=0;d<o.length;d++)o[d].mode="hidden"},i))}let s=Un(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Hn(["init"])).pipe(hl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.selectManifest();if(fl(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,d]of[[a,"mq"],[s,"lq"]]){let u=String(parseFloat(o||""));d&&o&&r.searchParams.set(d,u)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){se(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$a.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as yl,assertNonNullable as Qn,debounce as Tl,ErrorCategory as jn,isHigher as Il,isHigherOrEqual as El,isInvariantQuality as Gn,isLowerOrEqual as xl,isNonNullable as kl,merge as Al,observableFrom as Pl,Subscription as wl,map as $l}from"@vkontakte/videoplayer-shared";var Pi=class{constructor(e){this.subscription=new wl;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new pe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),s.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[s.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?y(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return yl(e)}};this.params=e,this.video=ee(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:jn.WTF,message:"MpegProvider internal logic error",thrown:o})},r=re(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,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($l(o=>o.to)),this.params.output.playbackState$),this.subscription.add(xe(this.video,t.isLooped,i)),this.subscription.add(ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ce(this.video,t.playbackRate,r.playbackRateState$,i)),a(me(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&kl(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(d!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(d),c.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Al(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Pl(["init"])).pipe(Tl(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),te(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Qn(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Qn(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=fi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(j(t))}playIfAllowed(){se(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!Gn(o.track.quality)&&xl(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&El(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(u=>!Gn(u.track.quality)&&Il(u.track.quality,e)),d=o.length;d&&(t=o[d-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=Ue(r,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as Yn,debounce as Dl,merge as qn,observableFrom as Cl,Subscription as Bl,map as zn,ValueSubject as Vl,ErrorCategory as Ra,VideoQuality as Ol}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Ll}from"@vkontakte/videoplayer-shared";var Wn=["stun:videostun.mycdn.me:80"],Ml=1e3,Rl=3,Ma=()=>null,yr=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=Ma;this.externalStopCallback=Ma;this.externalErrorCallback=Ma;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:Wn}]};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:Ll.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),Ml)}normalizeOptions(e={}){let t={stunServerList:Wn,maxRetryNumber:Rl,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var wi=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new Vl(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Yn(e)}};this.subscription=new Bl,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ee(e.container,e.tuning),this.liveStreamClient=new yr(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:Ra.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};qn(this.videoState.stateChangeStarted$.pipe(zn(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(zn(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=re(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(me(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(ie(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 Yn(s.to)}},i)).add(qn(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Cl(["init"])).pipe(Dl(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(j(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:Ol.INVARIANT}),this.video.srcObject=e,y(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ra.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){se(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ra.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var $i=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 Ri,assertNonNullable as je,ErrorCategory as Ir,filter as jl,isNonNullable as to,isNullable as Gl,map as Wl,merge as Yl,once as ql,Subject as de,Subscription as io,ValueSubject as L,flattenObject as ro}from"@vkontakte/videoplayer-shared";import{Observable as _l,map as Kn,Subscription as Nl,Subject as Fl}from"@vkontakte/videoplayer-shared";var Jn=n=>new _l(e=>{let t=new Nl,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(Kn(({from:u,to:c})=>`${u}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(Kn(({type:u})=>u!==void 0)),s=new Fl,o=0,d="unknown";return t.add(i.subscribe(u=>{o&&window.clearTimeout(o),d=u,o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),d="unknown",o=0})),t.add(a.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as Xn,Subscription as Ul,combine as Hl,filter as Zn,once as eo}from"@vkontakte/videoplayer-shared";var Li=null,Tr=null;function Da(){return Li||(Li=new(window.AudioContext||window.webkitAudioContext)),Tr||(Tr=new GainNode(Li,{gain:1}),Tr.connect(Li.destination)),{audioCtx:Li,gainNode:Tr}}import{clientChecker as Ql}from"@vkontakte/videoplayer-shared";var Mi=class n{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Ul;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(Zn(s=>!!s.type),eo()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Ql.isSafari&&e!=="MPEG"||this.subscriptions.add(Hl({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Zn(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),eo()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=Da(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${n.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(s){this.volumeMultiplierError$.next({id:n.errorId,category:Xn.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:s})}}).catch(s=>{this.volumeMultiplierError$.next({id:n.errorId,category:Xn.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=Da();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var zl={chunkDuration:5e3,maxParallelRequests:5},Di=class{constructor(e){this.current$=new L({type:void 0});this.providerError$=new de;this.noAvailableProvidersError$=new de;this.volumeMultiplierError$=new de;this.providerOutput={position$:new L(0),duration$:new L(1/0),volume$:new L({muted:!1,volume:1}),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableVideoTracks$:new L([]),currentVideoTrack$:new L(void 0),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0),isAudioAvailable$:new L(!0),autoVideoTrackLimitingAvailable$:new L(!1),autoVideoTrackLimits$:new L(void 0),currentBuffer$:new L(void 0),isBuffering$:new L(!0),error$:new de,warning$:new de,willSeekEvent$:new de,seekedEvent$:new de,loopedEvent$:new de,endedEvent$:new de,firstBytesEvent$:new de,loadedMetadataEvent$:new de,firstFrameEvent$:new de,canplay$:new de,isLive$:new L(void 0),isLowLatency$:new L(!1),canChangePlaybackSpeed$:new L(!0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),inPiP$:new L(!1),inFullscreen$:new L(!1),element$:new L(void 0),elementVisible$:new L(!0),availableSources$:new L(void 0),is3DVideo$:new L(!1),playbackState$:new L("")};this.subscription=new io;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Ws([...qs(this.params.tuning),...Ys(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>to(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",ro(a)),this.screenFormatsIterator=new $i(a);let s=[...sa(!0),...sa(!1)];this.chromecastFormatsIterator=new $i(s.filter(o=>to(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Mi(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Gl(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Ir.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 Ri(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]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return je(o),new Ti({...s,source:o,sourceHls:d})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return je(o),new Ii({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return je(o),Tt||!this.params.tuning.useHlsJs?new Ai({...s,source:o}):new xi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return je(o),new ki({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return je(o),new Pi({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return je(o),new Fs({...s,source:o,config:{...zl,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return je(o),new wi({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 Ri(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 je(o),new Ct({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 Ri(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ri(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 Ri(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 io,t=!1,i=0;return e.add(Yl(this.providerOutput.error$,Jn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Wl(r=>({id:`ProviderHangup:${r}`,category:Ir.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(jl(({to:a})=>a==="playing"),ql()).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===Ir.NETWORK,d=r.category===Ir.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!d,l=u&&!d&&(o&&t||!c);s={...s,isNetworkError:o,isFatalError:d,haveFailoverHost:u,tryFailover:l,canReinitProvider:c},l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}this.tracer.error("providerError",ro(s))})),e}};import{fromEvent as Er,once as Kl,combine as Jl,Subscription as ao,ValueSubject as Ca,map as Xl,filter as Zl,isNonNullable as xr,now as le,safeStorage as Ba}from"@vkontakte/videoplayer-shared";var ec=5e3,so="one_video_throughput",no="one_video_rtt",Ci=window.navigator.connection,oo=()=>{let n=Ci?.downlink;if(xr(n)&&n!==10)return n*1e3},uo=()=>{let n=Ci?.rtt;if(xr(n)&&n!==3e3)return n},lo=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Va=class n{constructor(e){this.subscription=new ao;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(so)||(e.useBrowserEstimation?oo():void 0)||ec,i=n.load(no)??(e.useBrowserEstimation?uo():void 0)??0;if(this.throughput$=new Ca(t),this.rtt$=new Ca(i),this.rttAdjustedThroughput$=new Ca(lo(t,i,e.rttPenaltyRequestSize)),this.throughput=dt.getSmoothedValue(t,-1,e),this.rtt=dt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=oo();s&&this.throughput.next(s);let o=uo();xr(o)&&this.rtt.next(o)};Ci&&"onchange"in Ci&&this.subscription.add(Er(Ci,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Ba.set(so,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Ba.set(no,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Jl({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Xl(({throughput:r,rtt:a})=>lo(r,a,e.rttPenaltyRequestSize)),Zl(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=le(),r=new ao;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Er(e,"progress").pipe(Kl()).subscribe(a=>{t=a.loaded,i=le()}));break;case 1:case 0:r.add(Er(e,"loadstart").subscribe(()=>{t=0,i=le()}));break}r.add(Er(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=le(),d=s-t,u=o-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=le(),s=0,o=le(),d=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:l})=>{if(c)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=le();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=l.byteLength,a=le()}else s+=l.byteLength;o=le()}else r+=l.byteLength,s+=l.byteLength,s>=this.tuningConfig.streamMinSampleSize&&le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,le()-o,this.concurrentDownloads.size),s=0,o=le());await i?.read().then(u,d)}};this.concurrentDownloads.add(e),i?.read().then(u,d)}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=Ba.get(e);if(xr(t))return parseInt(t,10)??void 0}},co=Va;import{fillWithDefault as tc,VideoQuality as po}from"@vkontakte/videoplayer-shared";var ho={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:po.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:po.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!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,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!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},mo=n=>({...tc(n,ho),configName:[...n.configName??[],...ho.configName]});import{assertNonNullable as kr,combine as Ge,ErrorCategory as Ar,filter as K,filterChanged as B,fromEvent as _a,isNonNullable as uc,isNullable as dc,Logger as lc,map as M,mapTo as go,merge as We,now as Pr,once as Re,Subject as N,Subscription as vo,tap as yo,ValueSubject as E,isHigher as cc,isInvariantQuality as To,flattenObject as Ye,throttle as Na,getTraceSubscriptionMethod as Io,Tracer as pc}from"@vkontakte/videoplayer-shared";import{merge as ic,map as rc,filter as fo,isNonNullable as ac}from"@vkontakte/videoplayer-shared";var Oa=({seekState:n,position$:e})=>ic(n.stateChangeEnded$.pipe(rc(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),fo(ac)),e.pipe(fo(()=>n.getState().state==="none")));import{assertNonNullable as sc}from"@vkontakte/videoplayer-shared";var bo=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return sc(e,`Wrong container or containerId {${n.container}}`),e};import{filter as nc,once as oc}from"@vkontakte/videoplayer-shared";var So=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(nc(r=>r.length>0),oc()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var wr=class{constructor(e={configName:[]},t=pc.createRootTracer(!1)){this.subscription=new vo;this.logger=new lc;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,loadedMetadata$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:vs};if(this.initLogs(),this.tuning=mo(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Hi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new co(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let s=Reflect.get(i,r,a);return typeof s!="function"?s:(...o)=>{try{return s.apply(i,o)}catch(d){let u=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)}`,l=`Exception calling ${c} (${u.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Ar.WTF,message:l,thrown:d}),d}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",Ye(i)),this.domContainer=bo(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Di({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.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Qt()?(this.tracer.log("request play from hidden tab"),_a(document,"visibilitychange").pipe(Re()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;return e>=i&&!r&&(a=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){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.providerContainer.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),Re()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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",Ye(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),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",Ye(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return So(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}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(dc(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return uc(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(We(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(K(({from:e})=>e==="stopped"),Re()).subscribe(()=>{this.initedAt=Pr(),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",Ye(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Ar.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ye(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(M(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(M(s=>s.destination),B()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(M(s=>s.map(({quality:o})=>o).sort((o,d)=>To(o)?1:To(d)?-1:cc(d,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let d of s)d.fps&&(o[d.quality]=d.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(B()).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(B((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(B((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(B()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(B()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(B()).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(M(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(Ge({hasLiveOffsetByPaused:We(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(s=>s.to),B(),M(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(Ge({atLiveEdge:Ge({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Oa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(M(({isLive:s,position:o,isLowLatency:d})=>{let u=this.getActiveLiveDelay(d);return s&&Math.abs(o)<u/1e3}),B(),yo(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(M(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(Ge({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(M(({isLive:s,position:o,duration:d})=>s&&(Math.abs(d)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),B(),yo(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(M(s=>s.muted),B()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(M(s=>s.volume),B()).subscribe(this.info.volume$)).add(Oa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(We(e.providerOutput.endedEvent$.pipe(go(!0)),e.providerOutput.seekedEvent$.pipe(go(!1))).pipe(B()).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(M(s=>({id:s?`No${s}`:"NoProviders",category:Ar.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Re(),M(s=>s??Pr()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Re(),M(()=>Pr()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Re(),M(()=>Pr()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(K(({to:s})=>s==="playing"),Re()).subscribe(()=>i.next(!1)));let r=0,a=We(e.providerOutput.isBuffering$,t,i).pipe(M(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),B());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(We(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(We(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(),d=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),l;c==="CONNECTED"?l="second_screen":d?u?s?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(M(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new vo;this.subscription.add(t),this.subscription.add(e.current$.pipe(B((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(K(i=>i.length>0),Re()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Ue(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(We(this.desiredState.videoTrack.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(M(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),gs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ss(t)),this.providerContainer.current$.subscribe(({type:t})=>Ot("provider",t)),e.duration$.subscribe(t=>Ot("duration",t)),e.availableVideoTracks$.pipe(K(t=>!!t.length),Re()).subscribe(t=>Ot("tracks",t)),this.events.fatalError$.subscribe(new q("fatalError")),this.events.managedError$.subscribe(new q("managedError")),e.position$.subscribe(new q("position")),e.currentVideoTrack$.pipe(M(t=>t?.quality)).subscribe(new q("quality")),this.info.currentBuffer$.subscribe(new q("buffer")),e.isBuffering$.subscribe(new q("isBuffering"))].forEach(t=>this.subscription.add(t)),Ot("codecs",Gs())}initTracerSubscription(){let e=Io(this.tracer.log.bind(this.tracer)),t=Io(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(B()).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(Ge({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(K(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),B((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(K(i=>i>0),B()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(K(i=>i>0),B()).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(Ge({currentBuffer:this.info.currentBuffer$.pipe(K(i=>i.end>0),B((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(B())}).pipe(Na(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(B()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(B()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(B()).subscribe(e("canChangePlaybackSpeed"))).add(Ge({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(K(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Na(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(B(),K(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(B(),K(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(B()).subscribe(e("muted"))).add(this.info.volume$.pipe(B()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(B(),K(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ge({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(K(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Na(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(B(),K(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:Ar.DOM,message:String(r)})})};this.subscription.add(We(_a(document,"visibilitychange"),_a(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",Ye({quality:t,availableTracks:Ye(e),track:Ye(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 Px,Observable as wx,Subject as $x,ValueSubject as Lx,VideoQuality as Mx}from"@vkontakte/videoplayer-shared";var Rx=`@vkontakte/videoplayer-core@${Ua}`;export{Fi as ChromecastState,Vr as HttpConnectionType,wx as Observable,Z as PlaybackState,wr as Player,Rx as SDK_VERSION,$x as Subject,Px as Subscription,Or as Surface,Ua as VERSION,Lx as ValueSubject,Ve as VideoFormat,Mx as VideoQuality};
|
|
112
|
+
`;var xr=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 Ir(this.params.fov,this.params.orientation),this.cameraRotationManager=new Er(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(Cn,this.gl.VERTEX_SHADER),i=this.createShader(Bn,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,d=t-r,u=e+i,c=t+r,l=e-i,p=t+r;return[a,s,o,d,u,c,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var yt=class{constructor(e){this.subscription=new Hd;this.videoState=new $("stopped");this.elementSize$=new Qd(void 0);this.droppedFramesManager=new nr;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yt;this.audioTrackSwitchHistory=new Yt;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let s=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-s,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&y(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Bd(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new xr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ie(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 Tr({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=se(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:La.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,d)=>this.subscription.add(o.subscribe(d,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Vn(u=>!!u.length),Nn()).subscribe(u=>{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:u})})),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(Vn(_d),Nn()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(On(u=>u.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Me(this.video,t.isLooped,r)),this.subscription.add(ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,i.playbackRateState$,r)),a(Ud(this.video),this.elementSize$),a(be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map;let c=this.player.getStreams();if(Vd(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(va(h));let m=[];for(let f of h.representations){let g=Tn(f);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of c.video){l.push(ya(p));let h=[];for(let m of p.representations){let f=yn(m);f&&(h.push(f),this.videoTracksMap.set(f,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(l),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)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=u=>e.error$.next({id:"RepresentationSwitch",category:La.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(kr(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Nd(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,h]=l,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(s),h){let f=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,f).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ma()).subscribe(u=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{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(l),e.currentVideoStream$.next(ya(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ma()).subscribe(u=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===u);if(!c){e.currentAudioStream$.next(void 0);return}let[l,{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(va(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),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));let o=t.playbackState.stateChangeStarted$.pipe(On(({to:u})=>u==="ready"),Ma());this.subscription.add(kr(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(kr(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=kr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Fd(["init"])).pipe(Od(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:T})=>T===r),o=t.currentVideoTrack$.getValue(),d=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let u=[...this.videoStreamsMap.keys()].find(({id:T})=>T===d.id),c=u&&this.videoStreamsMap.get(u);if(!c)return;let l=_e(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),f=[...this.audioStreamsMap.keys()].find(({id:T})=>T===m?.id)??this.audioStreamsMap.keys().next().value,g=0;if(f){if(s&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let T=ir(s,c,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,T?.bitrate??-1/0)}else{let T=hr(s,c,this.audioStreamsMap.get(f)??[]);g=Math.max(g,T?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let T=ir(o,c,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,T?.bitrate??-1/0)}else{let T=hr(o,c,this.audioStreamsMap.get(f)??[]);g=Math.max(g,T?.bitrate??-1/0)}}let P=Je(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),R=i?P??s:s??P,S;this.params.tuning.useSeparateAudioVideoABR?S=f&&Bs(R,c,this.audioStreamsMap.get(f)??[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):S=f&&hr(R,c,this.audioStreamsMap.get(f)??[]);let b=this.videoTracksMap.get(R)?.representation,v=S&&this.audioTracksMap.get(S)?.representation;if(b&&v)return[b,v];if(b&&!v&&this.audioTracksMap.size===0)return[b,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){oe(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:La.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.player.destroy(),this.params.output.element$.next(void 0),re(this.video),this.tracer.end()}};var Mi=class extends yt{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 _n,interval as jd,map as Gd}from"@vkontakte/videoplayer-shared";var Ri=class extends yt{constructor(e){super(e),this.liveOffset=new Oe}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(_n({interval:jd(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()==="playing"){let a=e.position$.getValue()+(r-1);a<=0&&e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(_n({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Gd(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(r=>{if(r){let a=In(r);this.params.output.availableTextTracks$.next([a])}}))}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 Di,assertNonNullable as Fn,debounce as Wd,ErrorCategory as Ar,filter as Yd,isNonNullable as qd,isNullable as zd,map as Pr,merge as Kd,Observable as Jd,observableFrom as Xd,Subscription as Zd,videoSizeToQuality as el}from"@vkontakte/videoplayer-shared";var Ae={};var _t=(n,e)=>new Jd(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Ci=class{constructor(e){this.subscription=new Zd;this.videoState=new $("initializing");this.textTracksManager=new De;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:Di(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Di(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Di(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Di(e)}break;default:Di(t)}};this.video=ie(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),re(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ar.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||(Ae.Hls=r.default,Ae.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){Fn(Ae.Hls,"hls.js not loaded"),this.hls=new Ae.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Fn(Ae.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:Ar.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=se(this.video),a=(u,c)=>this.subscription.add(u.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(Me(this.video,e.isLooped,i)),this.subscription.add(ae(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(me(this.video,e.playbackRate,r.playbackRateState$,i)),a(be(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Pr(u=>u.to)),this.params.output.playbackState$),this.subscription.add(_t(this.hls,Ae.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:Ar.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(_t(this.hls,Ae.Events.MANIFEST_PARSED).pipe(Pr(({levels:u})=>u.reduce((c,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,f=Ke(l.attrs.QUALITY??"")??el({width:h,height:m});if(!f)return c;let g=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,P={id:p.toString(),quality:f,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:P,level:l}),c.push(P),c},[]))),t.availableVideoTracks$),a(_t(this.hls,Ae.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let l of u.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),a(_t(this.hls,Ae.Events.LEVEL_LOADING).pipe(Pr(({url:u})=>G(u))),t.hostname$),a(_t(this.hls,Ae.Events.FRAG_CHANGED),u=>{let{video:c,audio:l}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(Ye(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));let s=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=_t(this.hls,Ae.Events.LEVEL_SWITCHED).pipe(Pr(({level:u})=>s(this.hls.levels[u])));o.pipe(Yd(qd)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ye(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),u=>{if(zd(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let l=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let d=Kd(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Xd(["init"])).pipe(Wd(0));this.subscription.add(d.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 oe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ar.DOM,thrown:t}))||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0)}};var Un="X-Playback-Duration",Ra=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(Un)?parseInt(e.headers.get(Un),10):void 0};import{assertNever as nl,combine as ol,debounce as ul,ErrorCategory as $r,filter as dl,filterChanged as ll,isNonNullable as Qn,isNullable as Lr,map as jn,merge as cl,observableFrom as pl,Subscription as hl,ValueSubject as Ca,VideoQuality as ml}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as tl,getExponentialDelay as il}from"@vkontakte/videoplayer-shared";var rl=n=>{let e=null;if(n.QUALITY&&(e=Ke(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=tl({width:t,height:i})}return e??null},al=(n,e)=>{let t=n.split(`
|
|
113
|
+
`),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),d=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!d)){if(o){let u=Object.fromEntries(o[1].split(",").map(g=>g.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,l=rl(u),p;u.BANDWIDTH&&(p=parseInt(u.BANDWIDTH,10)/1e3||void 0),!p&&u["AVERAGE-BANDWIDTH"]&&(p=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[g,P]=u.RESOLUTION.split("x").map(R=>parseInt(R,10));g&&P&&(m={width:g,height:P})}let f=new URL(t[++a],e).toString();l&&i.push({id:c,quality:l,url:f,bandwidth:p,size:m,fps:h})}if(d){let u=Object.fromEntries(d[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),l=u.LANGUAGE,p=u.NAME;c&&l&&r.push({type:"internal",id:l,label:p,language:l,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},sl=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Da=0,Hn=async(n,e=n,t)=>{let r=await(await fetch(n)).text();Da+=1;try{let{qualityManifests:a,textTracks:s}=al(r,e);return{qualityManifests:a,textTracks:s}}catch{if(Da<=t.manifestRetryMaxCount)return await sl(il(Da-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Hn(n,e,t)}return{qualityManifests:[],textTracks:[]}},wr=Hn;var Bi=class{constructor(e){this.subscription=new hl;this.videoState=new $("stopped");this.textTracksManager=new De;this.manifests$=new Ca([]);this.liveOffset=new Oe;this.manifestStartTime$=new Ca(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=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),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(y(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return nl(t)}};this.params=e,this.video=ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ml.INVARIANT,url:this.params.source.url},wr(q(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:$r.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:$r.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Ca(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(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:$r.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=se(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,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(ae(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(me(this.video,t.playbackRate,r.playbackRateState$,i)),a(be(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ll(),jn(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Qn(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from==="changing_manifest"&&this.videoState.setState(d.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(ol({startTime:this.manifestStartTime$.pipe(dl(Qn)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:d})=>this.params.output.liveTime$.next(o+d*1e3),i)),this.subscription.add(this.manifests$.pipe(jn(o=>o.map(({id:d,quality:u,size:c,bandwidth:l,fps:p})=>({id:d,quality:u,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let s=cl(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,pl(["init"])).pipe(ul(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),re(this.video)}prepare(){let e=this.selectManifest();if(Lr(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:d}=t?.to??i??{};for(let[u,c]of[[o,"mq"],[d,"lq"]]){let l=String(parseFloat(u||""));c&&u&&r.searchParams.set(c,l)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=q(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),Ra(s).then(o=>{if(!Lr(o))this.maxSeekBackTime$.next(o);else{let d=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(Lr(d)||!isFinite(d))try{fetch(s).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let l=new URL(c,s).toString();Ra(l).then(p=>{Lr(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$r.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as fl,debounce as bl,ErrorCategory as Ba,fromEvent as Va,isNonNullable as gl,isNullable as Sl,map as Gn,merge as Wn,observableFrom as Yn,Subscription as vl,ValueSubject as yl,VideoQuality as Tl,clientChecker as Il}from"@vkontakte/videoplayer-shared";var Vi=class{constructor(e){this.subscription=new vl;this.videoState=new $("stopped");this.textTracksManager=new De;this.manifests$=new yl([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=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:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return fl(t)}};this.params=e,this.video=ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Tl.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),wr(q(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:Ba.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(d=>d.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Ba.WTF,message:"HlsProvider internal logic error",thrown:o})},r=se(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d));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(Gn(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Me(this.video,t.isLooped,i)),this.subscription.add(ae(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(me(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&gl(u.to)){let l=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(h),f.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from==="changing_manifest"&&this.videoState.setState(d.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(Gn(o=>o.map(({id:d,quality:u,size:c,bandwidth:l,fps:p})=>({id:d,quality:u,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!Il.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Wn(Va(o,"addtrack"),Va(o,"removetrack"),Va(o,"change"),Yn(["init"])).subscribe(()=>{for(let d=0;d<o.length;d++)o[d].mode="hidden"},i))}let s=Wn(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Yn(["init"])).pipe(bl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),re(this.video)}prepare(){let e=this.selectManifest();if(Sl(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,d]of[[a,"mq"],[s,"lq"]]){let u=String(parseFloat(o||""));d&&o&&r.searchParams.set(d,u)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ba.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as El,assertNonNullable as qn,debounce as xl,ErrorCategory as zn,isHigher as kl,isHigherOrEqual as Al,isInvariantQuality as Kn,isLowerOrEqual as Pl,isNonNullable as wl,merge as $l,observableFrom as Ll,Subscription as Ml,map as Rl}from"@vkontakte/videoplayer-shared";var Oi=class{constructor(e){this.subscription=new Ml;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),s.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[s.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?y(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return El(e)}};this.params=e,this.video=ie(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:zn.WTF,message:"MpegProvider internal logic error",thrown:o})},r=se(this.video),a=(o,d)=>this.subscription.add(o.subscribe(d,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(Rl(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Me(this.video,t.isLooped,i)),this.subscription.add(ae(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(me(this.video,t.playbackRate,r.playbackRateState$,i)),a(be(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&wl(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(d!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(d),c.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=$l(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ll(["init"])).pipe(xl(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),re(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;qn(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];qn(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=xi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!Kn(o.track.quality)&&Pl(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&Al(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(u=>!Kn(u.track.quality)&&kl(u.track.quality,e)),d=o.length;d&&(t=o[d-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=Je(r,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as Xn,debounce as Vl,merge as Zn,observableFrom as Ol,Subscription as Nl,map as eo,ValueSubject as _l,ErrorCategory as Na,VideoQuality as Fl}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Dl}from"@vkontakte/videoplayer-shared";var Jn=["stun:videostun.mycdn.me:80"],Cl=1e3,Bl=3,Oa=()=>null,Mr=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=Oa;this.externalStopCallback=Oa;this.externalErrorCallback=Oa;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:Jn}]};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:Dl.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),Cl)}normalizeOptions(e={}){let t={stunServerList:Jn,maxRetryNumber:Bl,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ni=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new _l(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Xn(e)}};this.subscription=new Nl,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ie(e.container,e.tuning),this.liveStreamClient=new Mr(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),re(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:Na.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};Zn(this.videoState.stateChangeStarted$.pipe(eo(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(eo(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=se(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(be(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{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(ae(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 Xn(s.to)}},i)).add(Zn(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ol(["init"])).pipe(Vl(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:Fl.INVARIANT}),this.video.srcObject=e,y(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Na.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Na.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var _i=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 Hi,assertNonNullable as et,ErrorCategory as Dr,filter as Yl,isNonNullable as no,isNullable as ql,map as zl,merge as Kl,once as Jl,Subject as ce,Subscription as oo,ValueSubject as L,flattenObject as uo}from"@vkontakte/videoplayer-shared";import{Observable as Ul,map as to,Subscription as Hl,Subject as Ql}from"@vkontakte/videoplayer-shared";var io=n=>new Ul(e=>{let t=new Hl,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(to(({from:u,to:c})=>`${u}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(to(({type:u})=>u!==void 0)),s=new Ql,o=0,d="unknown";return t.add(i.subscribe(u=>{o&&window.clearTimeout(o),d=u,o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),d="unknown",o=0})),t.add(a.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as ro,Subscription as jl,combine as Gl,filter as ao,once as so}from"@vkontakte/videoplayer-shared";var Fi=null,Rr=null;function _a(){return Fi||(Fi=new(window.AudioContext||window.webkitAudioContext)),Rr||(Rr=new GainNode(Fi,{gain:1}),Rr.connect(Fi.destination)),{audioCtx:Fi,gainNode:Rr}}import{clientChecker as Wl}from"@vkontakte/videoplayer-shared";var Ui=class n{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new jl;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(ao(s=>!!s.type),so()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Wl.isSafari&&e!=="MPEG"||this.subscriptions.add(Gl({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(ao(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),so()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=_a(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${n.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(s){this.volumeMultiplierError$.next({id:n.errorId,category:ro.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:s})}}).catch(s=>{this.volumeMultiplierError$.next({id:n.errorId,category:ro.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=_a();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Xl={chunkDuration:5e3,maxParallelRequests:5},Qi=class{constructor(e){this.current$=new L({type:void 0});this.providerError$=new ce;this.noAvailableProvidersError$=new ce;this.volumeMultiplierError$=new ce;this.providerOutput={position$:new L(0),duration$:new L(1/0),volume$:new L({muted:!1,volume:1}),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableVideoTracks$:new L([]),currentVideoTrack$:new L(void 0),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0),isAudioAvailable$:new L(!0),autoVideoTrackLimitingAvailable$:new L(!1),autoVideoTrackLimits$:new L(void 0),currentBuffer$:new L(void 0),isBuffering$:new L(!0),error$:new ce,warning$:new ce,willSeekEvent$:new ce,seekedEvent$:new ce,loopedEvent$:new ce,endedEvent$:new ce,firstBytesEvent$:new ce,loadedMetadataEvent$:new ce,firstFrameEvent$:new ce,canplay$:new ce,isLive$:new L(void 0),isLowLatency$:new L(!1),canChangePlaybackSpeed$:new L(!0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),inPiP$:new L(!1),inFullscreen$:new L(!1),element$:new L(void 0),elementVisible$:new L(!0),availableSources$:new L(void 0),is3DVideo$:new L(!1),playbackState$:new L("")};this.subscription=new oo;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Xs([...en(this.params.tuning),...Zs(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>no(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",uo(a)),this.screenFormatsIterator=new _i(a);let s=[...la(!0),...la(!1)];this.chromecastFormatsIterator=new _i(s.filter(o=>no(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Ui(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(ql(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Dr.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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 Hi(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]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return et(o),new Mi({...s,source:o,sourceHls:d})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return et(o),new Ri({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return et(o),Lt||!this.params.tuning.useHlsJs?new Vi({...s,source:o}):new Ci({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return et(o),new Bi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return et(o),new Oi({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return et(o),new Ws({...s,source:o,config:{...Xl,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return et(o),new Ni({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 Hi(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 et(o),new Qt({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 Hi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Hi(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 Hi(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 oo,t=!1,i=0;return e.add(Kl(this.providerOutput.error$,io({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(zl(r=>({id:`ProviderHangup:${r}`,category:Dr.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Yl(({to:a})=>a==="playing"),Jl()).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===Dr.NETWORK,d=r.category===Dr.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!d,l=u&&!d&&(o&&t||!c);s={...s,isNetworkError:o,isFatalError:d,haveFailoverHost:u,tryFailover:l,canReinitProvider:c},l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}this.tracer.error("providerError",uo(s))})),e}};import{fromEvent as Cr,once as Zl,combine as ec,Subscription as lo,ValueSubject as Fa,map as tc,filter as ic,isNonNullable as Br,now as pe,safeStorage as Ua}from"@vkontakte/videoplayer-shared";var rc=5e3,co="one_video_throughput",po="one_video_rtt",ji=window.navigator.connection,ho=()=>{let n=ji?.downlink;if(Br(n)&&n!==10)return n*1e3},mo=()=>{let n=ji?.rtt;if(Br(n)&&n!==3e3)return n},fo=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Ha=class n{constructor(e){this.subscription=new lo;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(co)||(e.useBrowserEstimation?ho():void 0)||rc,i=n.load(po)??(e.useBrowserEstimation?mo():void 0)??0;if(this.throughput$=new Fa(t),this.rtt$=new Fa(i),this.rttAdjustedThroughput$=new Fa(fo(t,i,e.rttPenaltyRequestSize)),this.throughput=St.getSmoothedValue(t,-1,e),this.rtt=St.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=ho();s&&this.throughput.next(s);let o=mo();Br(o)&&this.rtt.next(o)};ji&&"onchange"in ji&&this.subscription.add(Cr(ji,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Ua.set(co,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Ua.set(po,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(ec({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(tc(({throughput:r,rtt:a})=>fo(r,a,e.rttPenaltyRequestSize)),ic(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=pe(),r=new lo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Cr(e,"progress").pipe(Zl()).subscribe(a=>{t=a.loaded,i=pe()}));break;case 1:case 0:r.add(Cr(e,"loadstart").subscribe(()=>{t=0,i=pe()}));break}r.add(Cr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=pe(),d=s-t,u=o-i;this.addRawSpeed(d,u,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=pe(),s=0,o=pe(),d=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:l})=>{if(c)!t&&this.addRawSpeed(r,pe()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=pe();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=l.byteLength,a=pe()}else s+=l.byteLength;o=pe()}else r+=l.byteLength,s+=l.byteLength,s>=this.tuningConfig.streamMinSampleSize&&pe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,pe()-o,this.concurrentDownloads.size),s=0,o=pe());await i?.read().then(u,d)}};this.concurrentDownloads.add(e),i?.read().then(u,d)}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=Ua.get(e);if(Br(t))return parseInt(t,10)??void 0}},bo=Ha;import{fillWithDefault as ac,VideoQuality as go}from"@vkontakte/videoplayer-shared";var So={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:go.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:go.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,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!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,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!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},vo=n=>({...ac(n,So),configName:[...n.configName??[],...So.configName]});import{assertNonNullable as Vr,combine as tt,ErrorCategory as Or,filter as X,filterChanged as B,fromEvent as ja,isNonNullable as cc,isNullable as pc,Logger as hc,map as M,mapTo as Eo,merge as it,now as Nr,once as He,Subject as _,Subscription as xo,tap as ko,ValueSubject as E,isHigher as mc,isInvariantQuality as Ao,flattenObject as rt,throttle as Ga,getTraceSubscriptionMethod as Po,Tracer as fc}from"@vkontakte/videoplayer-shared";import{merge as sc,map as nc,filter as yo,isNonNullable as oc}from"@vkontakte/videoplayer-shared";var Qa=({seekState:n,position$:e})=>sc(n.stateChangeEnded$.pipe(nc(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),yo(oc)),e.pipe(yo(()=>n.getState().state==="none")));import{assertNonNullable as uc}from"@vkontakte/videoplayer-shared";var To=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return uc(e,`Wrong container or containerId {${n.container}}`),e};import{filter as dc,once as lc}from"@vkontakte/videoplayer-shared";var Io=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(dc(r=>r.length>0),lc()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var _r=class{constructor(e={configName:[]},t=fc.createRootTracer(!1)){this.subscription=new xo;this.logger=new hc;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new _,ready$:new _,started$:new _,playing$:new _,paused$:new _,stopped$:new _,willStart$:new _,willResume$:new _,willPause$:new _,willStop$:new _,willDestruct$:new _,watchCoverageRecord$:new _,watchCoverageLive$:new _,managedError$:new _,fatalError$:new _,ended$:new _,looped$:new _,seeked$:new _,willSeek$:new _,firstBytes$:new _,loadedMetadata$:new _,firstFrame$:new _,canplay$:new _,log$:new _};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:ks};if(this.initLogs(),this.tuning=vo(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Zi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new bo(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let s=Reflect.get(i,r,a);return typeof s!="function"?s:(...o)=>{try{return s.apply(i,o)}catch(d){let u=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)}`,l=`Exception calling ${c} (${u.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Or.WTF,message:l,thrown:d}),d}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",rt(i)),this.domContainer=To(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Qi({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.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xt()?(this.tracer.log("request play from hidden tab"),ja(document,"visibilitychange").pipe(He()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;return e>=i&&!r&&(a=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Vr(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.providerContainer.providerOutput.availableVideoTracks$.pipe(X(i=>i.length>0),He()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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",rt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){Vr(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",rt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Io(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}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(pc(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return cc(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(it(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(X(({from:e})=>e==="stopped"),He()).subscribe(()=>{this.initedAt=Nr(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",rt(s)),s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Or.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",rt(s)),s.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(M(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(M(s=>s.destination),B()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(M(s=>s.map(({quality:o})=>o).sort((o,d)=>Ao(o)?1:Ao(d)?-1:mc(d,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let d of s)d.fps&&(o[d.quality]=d.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(B()).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(B((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(B((s,o)=>Math.round(s)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(B()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(B()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(B()).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(M(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(tt({hasLiveOffsetByPaused:it(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(s=>s.to),B(),M(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(tt({atLiveEdge:tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Qa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(M(({isLive:s,position:o,isLowLatency:d})=>{let u=this.getActiveLiveDelay(d);return s&&Math.abs(o)<u/1e3}),B(),ko(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(M(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(M(({isLive:s,position:o,duration:d})=>s&&(Math.abs(d)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),B(),ko(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(M(s=>s.muted),B()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(M(s=>s.volume),B()).subscribe(this.info.volume$)).add(Qa({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(it(e.providerOutput.endedEvent$.pipe(Eo(!0)),e.providerOutput.seekedEvent$.pipe(Eo(!1))).pipe(B()).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(M(s=>({id:s?`No${s}`:"NoProviders",category:Or.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(He(),M(s=>s??Nr()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(He(),M(()=>Nr()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(He(),M(()=>Nr()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(X(({to:s})=>s==="playing"),He()).subscribe(()=>i.next(!1)));let r=0,a=it(e.providerOutput.isBuffering$,t,i).pipe(M(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),B());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(it(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(it(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(),d=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),l;c==="CONNECTED"?l="second_screen":d?u?s?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(M(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new xo;this.subscription.add(t),this.subscription.add(e.current$.pipe(B((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(X(i=>i.length>0),He()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Je(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(it(this.desiredState.videoTrack.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(M(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;Vr(this.providerContainer),Vr(e),xs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Es(t)),this.providerContainer.current$.subscribe(({type:t})=>Wt("provider",t)),e.duration$.subscribe(t=>Wt("duration",t)),e.availableVideoTracks$.pipe(X(t=>!!t.length),He()).subscribe(t=>Wt("tracks",t)),this.events.fatalError$.subscribe(new J("fatalError")),this.events.managedError$.subscribe(new J("managedError")),e.position$.subscribe(new J("position")),e.currentVideoTrack$.pipe(M(t=>t?.quality)).subscribe(new J("quality")),this.info.currentBuffer$.subscribe(new J("buffer")),e.isBuffering$.subscribe(new J("isBuffering"))].forEach(t=>this.subscription.add(t)),Wt("codecs",Js())}initTracerSubscription(){let e=Po(this.tracer.log.bind(this.tracer)),t=Po(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(B()).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(tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(X(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),B((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(X(i=>i>0),B()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(X(i=>i>0),B()).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(tt({currentBuffer:this.info.currentBuffer$.pipe(X(i=>i.end>0),B((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(B())}).pipe(Ga(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(B()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(B()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(B()).subscribe(e("canChangePlaybackSpeed"))).add(tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(X(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Ga(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(B(),X(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(B(),X(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(B()).subscribe(e("muted"))).add(this.info.volume$.pipe(B()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(B(),X(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(X(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Ga(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(B(),X(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Or.DOM,message:String(r)})})};this.subscription.add(it(ja(document,"visibilitychange"),ja(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",rt({quality:t,availableTracks:rt(e),track:rt(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 Gx,Observable as Wx,Subject as Yx,ValueSubject as qx,VideoQuality as zx}from"@vkontakte/videoplayer-shared";var Kx=`@vkontakte/videoplayer-core@${Ya}`;export{Ji as ChromecastState,Ur as HttpConnectionType,Wx as Observable,te as PlaybackState,_r as Player,Kx as SDK_VERSION,Yx as Subject,Gx as Subscription,Hr as Surface,Ya as VERSION,qx as ValueSubject,We as VideoFormat,zx as VideoQuality};
|