@vkontakte/videoplayer-core 2.0.106-dev.8484fdea.0 → 2.0.106-dev.915f79b2.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 +8 -8
- package/es2015.esm.js +10 -10
- package/es2018.cjs.js +8 -8
- package/es2018.esm.js +9 -9
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +5 -5
- package/package.json +2 -2
package/es2018.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.106-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.106-dev.915f79b2.0
|
|
3
|
+
* Mon, 19 Aug 2024 06:35:24 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-106/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Is="2.0.106-dev.8484fdea.0";var te=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(te||{}),Ne=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(Ne||{});var Wi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Wi||{}),Jr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Jr||{});var Xr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Xr||{});import{assertNever as ws,assertNonNullable as Du,isNonNullable as Qi,ValueSubject as Zr,Subject as Cu,Subscription as Vu,merge as Bu,observableFrom as Ou,fromEvent as xs,map as As,tap as Ps,filterChanged as _u,isNullable as ea,ErrorCategory as ks}from"@vkontakte/videoplayer-shared";var Es=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var ji=class{constructor(e){this.connection$=new Zr(void 0);this.castState$=new Zr("NOT_AVAILABLE");this.errorEvent$=new Cu;this.realCastState$=new Zr("NOT_AVAILABLE");this.subscription=new Vu;var a;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=Qi((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},r||Es("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ks.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Qi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ea(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ea(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(xs(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,s;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(s=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:s.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 ws(r.sessionState)}})).add(Bu(xs(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ps(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),As(r=>r.castState)),Ou([i.getCastState()])).pipe(_u(),As(Nu),Ps(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;let a=r==="CONNECTED",s=Qi(this.connection$.getValue());if(a&&!s){let u=i.getCurrentSession();Du(u);let d=u.getCastDevice(),l=(n=u.getMediaSession())==null?void 0:n.media.contentId;(ea(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Qi(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:ks.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Nu=o=>{switch(o){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 ws(o)}};import{assertNever as $s}from"@vkontakte/videoplayer-shared";var K=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:$s(t)}return o},ta=(o,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(o);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(o);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:$s(e)}};var v=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as Fu,Subject as Yi,merge as Ls}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Yi;this.transitionEnded$=new Yi;this.transitionUpdated$=new Yi;this.forceChanged$=new Yi;this.stateChangeStarted$=Ls(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ls(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||Fu(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 Uu}from"@vkontakte/videoplayer-shared";var Ms=o=>{switch(o){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 Uu(o)}};import{assertNever as It,assertNonNullable as rt,debounce as Rs,ErrorCategory as Ds,fromEvent as at,isNonNullable as Cs,map as Vs,merge as Bs,observableFrom as Hu,Subject as Gu,Subscription as ia,timeout as Wu,getHighestQuality as Qu}from"@vkontakte/videoplayer-shared";var ju=5,Yu=5,qu=500,Os=7e3,Ft=class{constructor(e){this.subscription=new ia;this.loadMediaTimeoutSubscription=new ia;this.videoState=new L("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==null?void 0: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:It(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:It(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:It(e)}break}default:It(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ms(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 ia;this.subscription.add(e),this.subscription.add(Bs(this.videoState.stateChangeStarted$.pipe(Vs(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Vs(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 Gu;e.add(r.pipe(Rs(qu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(at(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let n=s.value;this.params.output.position$.next(n),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(n-a)>ju)&&r.next(n),a=n})),e.add(at(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(at(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(at(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(at(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,n=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(n!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Yu&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),v(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:It(s)}}),t(at(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(at(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Bs(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Hu(["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"),v(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&v(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a: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){var d;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];rt(l);let c=Qu(Object.keys(l));rt(c);let p=l[c];rt(p),i=p,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];rt(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];rt(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];rt(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];rt(l),i=K(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ds.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return It(e)}let s=new chrome.cast.media.MediaInfo((d=this.params.meta.videoId)!=null?d:i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:n,subtitle:u}=this.params.meta;return Cs(n)&&(s.metadata.title=n),Cs(u)&&(s.metadata.subtitle=u),s}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Wu(Os).subscribe(()=>a(`timeout(${Os})`)))});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:Ds.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Ns}from"@vkontakte/videoplayer-shared";import{clearVideoElement as zu}from"@vkontakte/videoplayer-shared";var _s=o=>{try{o.pause(),o.playbackRate=0,zu(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as Ku,Subscription as Ju}from"@vkontakte/videoplayer-shared";var ra=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)}},aa=window.WeakMap?new WeakMap:new ra,sa=window.WeakMap?new WeakMap:new Map,Xu=(o,e=20)=>{let t=0;return Ku(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},ie=(o,{audioVideoSyncRate:e})=>{let t=o.querySelector("video"),i=!!t;t?Ns(t):(t=document.createElement("video"),o.appendChild(t)),aa.set(t,i);let r=new Ju;return r.add(Xu(t,e)),sa.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},re=o=>{let e=sa.get(o);e==null||e.unsubscribe(),sa.delete(o);let t=aa.get(o);aa.delete(o),t?Ns(o):_s(o)};import{assertNonNullable as Ut,isNonNullable as Pe,isNullable as td,fromEvent as Et,merge as Fs,observableFrom as Us,filterChanged as Hs,map as Ht,Subject as Gs,Subscription as id,ValueSubject as rd,ErrorCategory as ad}from"@vkontakte/videoplayer-shared";import{isNonNullable as na,isNullable as Zu,Subscription as ed}from"@vkontakte/videoplayer-shared";var qi=(o,e,t,{equal:i=(s,n)=>s===n,changed$:r,onError:a}={})=>{let s=o.getState(),n=e(),u=Zu(r),d=new ed;return r&&d.add(r.subscribe(l=>{let c=o.getState();i(l,c)&&o.setState(l)},a)),i(n,s)||(t(s),u&&o.setState(s)),d.add(o.stateChangeStarted$.subscribe(l=>{t(l.to),u&&o.setState(l.to)},a)),d},Ae=(o,e,t)=>qi(e,()=>o.loop,i=>{na(i)&&(o.loop=i)},{onError:t}),ae=(o,e,t,i)=>qi(e,()=>({muted:o.muted,volume:o.volume}),r=>{na(r)&&(o.muted=r.muted,o.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),pe=(o,e,t,i)=>qi(e,()=>o.playbackRate,r=>{na(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Fe=qi;var sd=o=>["__",o.language,o.label].join("|"),nd=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},oa=class o{constructor(){this.available$=new Gs;this.current$=new rd(void 0);this.error$=new Gs;this.subscription=new id;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:ad.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(Fe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Pe(a)&&this.setInternal(a)},{equal:(a,s)=>Pe(a)&&Pe(s)&&a.length===s.length&&a.every(({id:n},u)=>n===s[u].id),changed$:this.available$.pipe(Ht(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Fe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Pe(a)&&this.setExternal(a)},{equal:(a,s)=>Pe(a)&&Pe(s)&&a.length===s.length&&a.every(({id:n},u)=>n===s[u].id),changed$:this.available$.pipe(Ht(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Fe(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(Fe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Ut(this.video);let{textTracks:e}=this.video;this.subscription.add(Et(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Fs(Et(e,"addtrack"),Et(e,"removetrack"),Us(["init"])).pipe(Ht(()=>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(Fs(Et(e,"change"),Us(["init"])).pipe(Ht(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ht(i=>i&&this.htmlTextTrackToITextTrack(i).id),Hs()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Et(e,"addtrack").subscribe(i=>{var a,s;(a=i.track)==null||a.addEventListener("cuechange",t);let r=n=>{var d,l,c,p,h;let u=(l=(d=n.target)==null?void 0:d.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(c=n.target)==null?void 0:c.cues)!=null?p:null),(h=n.target)==null||h.removeEventListener("cuechange",r))};(s=i.track)==null||s.addEventListener("cuechange",r)})),this.subscription.add(Et(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.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;Pe(t.align)&&(r.align=t.align),Pe(t.position)&&(r.position=t.position),Pe(t.size)&&(r.size=t.size),Pe(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ut(this.video);let t=[...this.video.textTracks];return e?t:t.filter(o.isHealthyTrack)}htmlTextTrackToITextTrack(e){var n,u;let{language:t,label:i}=e,r=e.id?e.id:sd(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:(n=this.externalTracks.get(r))==null?void 0:n.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:(u=this.internalTracks.get(r))==null?void 0:u.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){Ut(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(td(e)||!nd(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){Ut(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){Ut(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)}},he=oa;var $e=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Ws=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ua=o=>{let e=Ws(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},Qs=o=>{let e=Ws(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as me,map as Ue,merge as Ys,filterChanged as ud,isNonNullable as qs,Subject as dd,filter as zs,mapTo as Ks,combine as ld,once as cd,ErrorCategory as pd,ValueSubject as Js,getCurrentBrowser as hd,CurrentClientBrowser as md}from"@vkontakte/videoplayer-shared";var od=3,js=(o,e,t=od)=>{let i=0,r=0;for(let a=0;a<o.length;a++){let s=o.start(a),n=o.end(a);if(s<=e&&e<=n){if(i=s,r=n,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)o.end(u)+t>=i&&(i=o.start(u));for(let u=a+1;u<o.length;u++)o.start(u)-t<=r&&(r=o.end(u))}}return{from:i,to:r}};var se=o=>{let e=g=>me(o,g).pipe(Ks(void 0)),i=Ys(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>me(o,g))).pipe(Ue(g=>g.type==="ended"?o.readyState<2:o.readyState<3),ud()),r=Ys(me(o,"progress"),me(o,"timeupdate")).pipe(Ue(()=>js(o.buffered,o.currentTime))),s=hd().browser===md.Safari?ld({play:e("play").pipe(cd()),playing:e("playing")}).pipe(Ks(void 0)):e("playing"),n=me(o,"volumechange").pipe(Ue(()=>({muted:o.muted,volume:o.volume}))),u=me(o,"ratechange").pipe(Ue(()=>o.playbackRate)),d=me(o,"error").pipe(zs(()=>!!(o.error||o.played.length)),Ue(()=>{var S;let g=o.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:pd.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:(S=o.error)!=null?S:void 0}})),l=me(o,"timeupdate").pipe(Ue(()=>o.currentTime)),c=new dd,p=.3,h;l.subscribe(g=>{o.loop&&qs(h)&&qs(g)&&h>=o.duration-p&&g<=p&&c.next(h),h=g});let m=e("pause").pipe(zs(()=>!o.error&&h!==o.duration)),f=me(o,"enterpictureinpicture"),b=me(o,"leavepictureinpicture"),E=new Js(Qs(o));f.subscribe(()=>E.next(!0)),b.subscribe(()=>E.next(!1));let x=new Js(ua(o));return me(o,"fullscreenchange").pipe(Ue(()=>ua(o))).subscribe(x),{playing$:s,pause$:m,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$:l,durationChange$:me(o,"durationchange").pipe(Ue(()=>o.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:E,inFullscreen$:x}};import{VideoQuality as He}from"@vkontakte/videoplayer-shared";var Ge=o=>{switch(o){case"mobile":return He.Q_144P;case"lowest":return He.Q_240P;case"low":return He.Q_360P;case"sd":case"medium":return He.Q_480P;case"hd":case"high":return He.Q_720P;case"fullhd":case"full":return He.Q_1080P;case"quadhd":case"quad":return He.Q_1440P;case"ultrahd":case"ultra":return He.Q_2160P}};import{isNonNullable as We,isNullable as la,now as an,isHigher as ca,isHigherOrEqual as tn,isInvariantQuality as rn,isLower as pa,isLowerOrEqual as fd,videoSizeToQuality as bd,assertNotEmptyArray as gd}from"@vkontakte/videoplayer-shared";var da=!1,Le={},Xs=o=>{da=o},Zs=()=>{Le={}},en=o=>{o(Le)},Gt=(o,e)=>{var t;da&&(Le.meta=(t=Le.meta)!=null?t:{},Le.meta[o]=e)},J=class{constructor(e){this.name=e}next(e){var i,r;if(!da)return;Le.series=(i=Le.series)!=null?i:{};let t=(r=Le.series[this.name])!=null?r:[];t.push([Date.now(),e]),Le.series[this.name]=t}};var Sd=new J("best_bitrate"),vd=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t,zi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=an()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},yd='Assertion "ABR Tracks is empty array" failed',Td=(o,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:n,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var w,$,A,F,j;gd(o,yd);let p=i.usePixelRatio&&(w=window.devicePixelRatio)!=null?w:1,h=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},m=h&&bd(h),f=i.considerPlaybackRate&&We(n)?n:1,b=o.filter(k=>!rn(k.quality)).sort((k,y)=>ca(k.quality,y.quality)?-1:1),E=($=b.at(-1))==null?void 0:$.quality,x=(A=b.at(0))==null?void 0:A.quality,T=la(r)||We(r.min)&&We(r.max)&&pa(r.max,r.min)||We(r.min)&&x&&ca(r.min,x)||We(r.max)&&E&&pa(r.max,E),g=f*vd(s!=null?s:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),S={},D=b.filter(k=>(m?pa(k.quality,m):!0)?(We(t)&&isFinite(t)&&We(k.bitrate)?t-a>=k.bitrate*g:!0)?i.lazyQualitySwitch&&We(i.minBufferToSwitchUp)&&u&&!rn(u.quality)&&(s!=null?s:0)<i.minBufferToSwitchUp&&ca(k.quality,u.quality)?(S[k.quality]="Buffer",!1):!!l&&tn(k.quality,l)?(S[k.quality]="DroppedFramesLimit",!1):T||(la(r.max)||fd(k.quality,r.max))&&(la(r.min)||tn(k.quality,r.min))?!0:(S[k.quality]="FitsQualityLimits",!1):(S[k.quality]="FitsThroughput",!1):(S[k.quality]="FitsContainer",!1))[0];D&&D.bitrate&&Sd.next(D.bitrate);let P=(F=D!=null?D:b[Math.ceil((b.length-1)/2)])!=null?F:o[0];P.quality!==((j=d==null?void 0:d.last)==null?void 0:j.quality)&&c({message:`
|
|
6
|
+
var Is="2.0.106-dev.915f79b2.0";var ie=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ie||{}),Ne=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(Ne||{});var Wi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Wi||{}),Jr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Jr||{});var Xr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Xr||{});import{assertNever as ws,assertNonNullable as Du,isNonNullable as Qi,ValueSubject as Zr,Subject as Cu,Subscription as Vu,merge as Bu,observableFrom as Ou,fromEvent as xs,map as As,tap as Ps,filterChanged as _u,isNullable as ea,ErrorCategory as ks}from"@vkontakte/videoplayer-shared";var Es=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var ji=class{constructor(e){this.connection$=new Zr(void 0);this.castState$=new Zr("NOT_AVAILABLE");this.errorEvent$=new Cu;this.realCastState$=new Zr("NOT_AVAILABLE");this.subscription=new Vu;var a;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=Qi((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},r||Es("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ks.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Qi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ea(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ea(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(xs(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,s;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(s=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:s.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 ws(r.sessionState)}})).add(Bu(xs(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ps(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),As(r=>r.castState)),Ou([i.getCastState()])).pipe(_u(),As(Nu),Ps(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;let a=r==="CONNECTED",s=Qi(this.connection$.getValue());if(a&&!s){let u=i.getCurrentSession();Du(u);let d=u.getCastDevice(),l=(n=u.getMediaSession())==null?void 0:n.media.contentId;(ea(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Qi(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:ks.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},Nu=o=>{switch(o){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 ws(o)}};import{assertNever as $s}from"@vkontakte/videoplayer-shared";var J=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:$s(t)}return o},ta=(o,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(o);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(o);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:$s(e)}};var v=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as Fu,Subject as Yi,merge as Ls}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Yi;this.transitionEnded$=new Yi;this.transitionUpdated$=new Yi;this.forceChanged$=new Yi;this.stateChangeStarted$=Ls(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ls(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||Fu(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 Uu}from"@vkontakte/videoplayer-shared";var Ms=o=>{switch(o){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 Uu(o)}};import{assertNever as It,assertNonNullable as it,debounce as Rs,ErrorCategory as Ds,fromEvent as rt,isNonNullable as Cs,map as Vs,merge as Bs,observableFrom as Hu,Subject as Gu,Subscription as ia,timeout as Wu,getHighestQuality as Qu}from"@vkontakte/videoplayer-shared";var ju=5,Yu=5,qu=500,Os=7e3,Ft=class{constructor(e){this.subscription=new ia;this.loadMediaTimeoutSubscription=new ia;this.videoState=new L("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==null?void 0: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:It(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:It(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:It(e)}break}default:It(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ms(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 ia;this.subscription.add(e),this.subscription.add(Bs(this.videoState.stateChangeStarted$.pipe(Vs(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Vs(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 Gu;e.add(r.pipe(Rs(qu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let n=s.value;this.params.output.position$.next(n),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(n-a)>ju)&&r.next(n),a=n})),e.add(rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,n=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(n!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Yu&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),v(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:It(s)}}),t(rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(rt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Bs(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Hu(["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"),v(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),v(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&v(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a: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){var d;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];it(l);let c=Qu(Object.keys(l));it(c);let p=l[c];it(p),i=p,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];it(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];it(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];it(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];it(l),i=J(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ds.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return It(e)}let s=new chrome.cast.media.MediaInfo((d=this.params.meta.videoId)!=null?d:i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:n,subtitle:u}=this.params.meta;return Cs(n)&&(s.metadata.title=n),Cs(u)&&(s.metadata.subtitle=u),s}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Wu(Os).subscribe(()=>a(`timeout(${Os})`)))});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:Ds.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Ns}from"@vkontakte/videoplayer-shared";import{clearVideoElement as zu}from"@vkontakte/videoplayer-shared";var _s=o=>{try{o.pause(),o.playbackRate=0,zu(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as Ku,Subscription as Ju}from"@vkontakte/videoplayer-shared";var ra=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)}},aa=window.WeakMap?new WeakMap:new ra,sa=window.WeakMap?new WeakMap:new Map,Xu=(o,e=20)=>{let t=0;return Ku(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},re=(o,{audioVideoSyncRate:e})=>{let t=o.querySelector("video"),i=!!t;t?Ns(t):(t=document.createElement("video"),o.appendChild(t)),aa.set(t,i);let r=new Ju;return r.add(Xu(t,e)),sa.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ae=o=>{let e=sa.get(o);e==null||e.unsubscribe(),sa.delete(o);let t=aa.get(o);aa.delete(o),t?Ns(o):_s(o)};import{assertNonNullable as Ut,isNonNullable as Pe,isNullable as td,fromEvent as Et,merge as Fs,observableFrom as Us,filterChanged as Hs,map as Ht,Subject as Gs,Subscription as id,ValueSubject as rd,ErrorCategory as ad}from"@vkontakte/videoplayer-shared";import{isNonNullable as na,isNullable as Zu,Subscription as ed}from"@vkontakte/videoplayer-shared";var qi=(o,e,t,{equal:i=(s,n)=>s===n,changed$:r,onError:a}={})=>{let s=o.getState(),n=e(),u=Zu(r),d=new ed;return r&&d.add(r.subscribe(l=>{let c=o.getState();i(l,c)&&o.setState(l)},a)),i(n,s)||(t(s),u&&o.setState(s)),d.add(o.stateChangeStarted$.subscribe(l=>{t(l.to),u&&o.setState(l.to)},a)),d},Ae=(o,e,t)=>qi(e,()=>o.loop,i=>{na(i)&&(o.loop=i)},{onError:t}),se=(o,e,t,i)=>qi(e,()=>({muted:o.muted,volume:o.volume}),r=>{na(r)&&(o.muted=r.muted,o.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),he=(o,e,t,i)=>qi(e,()=>o.playbackRate,r=>{na(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Fe=qi;var sd=o=>["__",o.language,o.label].join("|"),nd=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},oa=class o{constructor(){this.available$=new Gs;this.current$=new rd(void 0);this.error$=new Gs;this.subscription=new id;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:ad.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(Fe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Pe(a)&&this.setInternal(a)},{equal:(a,s)=>Pe(a)&&Pe(s)&&a.length===s.length&&a.every(({id:n},u)=>n===s[u].id),changed$:this.available$.pipe(Ht(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Fe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Pe(a)&&this.setExternal(a)},{equal:(a,s)=>Pe(a)&&Pe(s)&&a.length===s.length&&a.every(({id:n},u)=>n===s[u].id),changed$:this.available$.pipe(Ht(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Fe(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(Fe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Ut(this.video);let{textTracks:e}=this.video;this.subscription.add(Et(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Fs(Et(e,"addtrack"),Et(e,"removetrack"),Us(["init"])).pipe(Ht(()=>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(Fs(Et(e,"change"),Us(["init"])).pipe(Ht(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ht(i=>i&&this.htmlTextTrackToITextTrack(i).id),Hs()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Et(e,"addtrack").subscribe(i=>{var a,s;(a=i.track)==null||a.addEventListener("cuechange",t);let r=n=>{var d,l,c,p,h;let u=(l=(d=n.target)==null?void 0:d.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(c=n.target)==null?void 0:c.cues)!=null?p:null),(h=n.target)==null||h.removeEventListener("cuechange",r))};(s=i.track)==null||s.addEventListener("cuechange",r)})),this.subscription.add(Et(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.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;Pe(t.align)&&(r.align=t.align),Pe(t.position)&&(r.position=t.position),Pe(t.size)&&(r.size=t.size),Pe(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ut(this.video);let t=[...this.video.textTracks];return e?t:t.filter(o.isHealthyTrack)}htmlTextTrackToITextTrack(e){var n,u;let{language:t,label:i}=e,r=e.id?e.id:sd(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:(n=this.externalTracks.get(r))==null?void 0:n.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:(u=this.internalTracks.get(r))==null?void 0:u.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){Ut(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(td(e)||!nd(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){Ut(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){Ut(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)}},me=oa;var $e=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Ws=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ua=o=>{let e=Ws(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},Qs=o=>{let e=Ws(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as fe,map as Ue,merge as Ys,filterChanged as ud,isNonNullable as qs,Subject as dd,filter as zs,mapTo as Ks,combine as ld,once as cd,ErrorCategory as pd,ValueSubject as Js,getCurrentBrowser as hd,CurrentClientBrowser as md}from"@vkontakte/videoplayer-shared";var od=3,js=(o,e,t=od)=>{let i=0,r=0;for(let a=0;a<o.length;a++){let s=o.start(a),n=o.end(a);if(s<=e&&e<=n){if(i=s,r=n,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)o.end(u)+t>=i&&(i=o.start(u));for(let u=a+1;u<o.length;u++)o.start(u)-t<=r&&(r=o.end(u))}}return{from:i,to:r}};var ne=o=>{let e=S=>fe(o,S).pipe(Ks(void 0)),i=Ys(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>fe(o,S))).pipe(Ue(S=>S.type==="ended"?o.readyState<2:o.readyState<3),ud()),r=Ys(fe(o,"progress"),fe(o,"timeupdate")).pipe(Ue(()=>js(o.buffered,o.currentTime))),s=hd().browser===md.Safari?ld({play:e("play").pipe(cd()),playing:e("playing")}).pipe(Ks(void 0)):e("playing"),n=fe(o,"volumechange").pipe(Ue(()=>({muted:o.muted,volume:o.volume}))),u=fe(o,"ratechange").pipe(Ue(()=>o.playbackRate)),d=fe(o,"error").pipe(zs(()=>!!(o.error||o.played.length)),Ue(()=>{var g;let S=o.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:pd.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(g=o.error)!=null?g:void 0}})),l=fe(o,"timeupdate").pipe(Ue(()=>o.currentTime)),c=new dd,p=.3,h;l.subscribe(S=>{o.loop&&qs(h)&&qs(S)&&h>=o.duration-p&&S<=p&&c.next(h),h=S});let m=e("pause").pipe(zs(()=>!o.error&&h!==o.duration)),f=fe(o,"enterpictureinpicture"),b=fe(o,"leavepictureinpicture"),E=new Js(Qs(o));f.subscribe(()=>E.next(!0)),b.subscribe(()=>E.next(!1));let x=new Js(ua(o));return fe(o,"fullscreenchange").pipe(Ue(()=>ua(o))).subscribe(x),{playing$:s,pause$:m,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$:l,durationChange$:fe(o,"durationchange").pipe(Ue(()=>o.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:E,inFullscreen$:x}};import{VideoQuality as He}from"@vkontakte/videoplayer-shared";var Ge=o=>{switch(o){case"mobile":return He.Q_144P;case"lowest":return He.Q_240P;case"low":return He.Q_360P;case"sd":case"medium":return He.Q_480P;case"hd":case"high":return He.Q_720P;case"fullhd":case"full":return He.Q_1080P;case"quadhd":case"quad":return He.Q_1440P;case"ultrahd":case"ultra":return He.Q_2160P}};import{isNonNullable as We,isNullable as la,now as an,isHigher as ca,isHigherOrEqual as tn,isInvariantQuality as rn,isLower as pa,isLowerOrEqual as fd,videoSizeToQuality as bd,assertNotEmptyArray as Sd}from"@vkontakte/videoplayer-shared";var da=!1,Le={},Xs=o=>{da=o},Zs=()=>{Le={}},en=o=>{o(Le)},Gt=(o,e)=>{var t;da&&(Le.meta=(t=Le.meta)!=null?t:{},Le.meta[o]=e)},X=class{constructor(e){this.name=e}next(e){var i,r;if(!da)return;Le.series=(i=Le.series)!=null?i:{};let t=(r=Le.series[this.name])!=null?r:[];t.push([Date.now(),e]),Le.series[this.name]=t}};var gd=new X("best_bitrate"),vd=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t,zi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=an()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},yd='Assertion "ABR Tracks is empty array" failed',Td=(o,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:n,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var w,$,A,F,Y;Sd(o,yd);let p=i.usePixelRatio&&(w=window.devicePixelRatio)!=null?w:1,h=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},m=h&&bd(h),f=i.considerPlaybackRate&&We(n)?n:1,b=o.filter(k=>!rn(k.quality)).sort((k,y)=>ca(k.quality,y.quality)?-1:1),E=($=b.at(-1))==null?void 0:$.quality,x=(A=b.at(0))==null?void 0:A.quality,T=la(r)||We(r.min)&&We(r.max)&&pa(r.max,r.min)||We(r.min)&&x&&ca(r.min,x)||We(r.max)&&E&&pa(r.max,E),S=f*vd(s!=null?s:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),g={},R=b.filter(k=>(m?pa(k.quality,m):!0)?(We(t)&&isFinite(t)&&We(k.bitrate)?t-a>=k.bitrate*S:!0)?i.lazyQualitySwitch&&We(i.minBufferToSwitchUp)&&u&&!rn(u.quality)&&(s!=null?s:0)<i.minBufferToSwitchUp&&ca(k.quality,u.quality)?(g[k.quality]="Buffer",!1):!!l&&tn(k.quality,l)?(g[k.quality]="DroppedFramesLimit",!1):T||(la(r.max)||fd(k.quality,r.max))&&(la(r.min)||tn(k.quality,r.min))?!0:(g[k.quality]="FitsQualityLimits",!1):(g[k.quality]="FitsThroughput",!1):(g[k.quality]="FitsContainer",!1))[0];R&&R.bitrate&&gd.next(R.bitrate);let P=(F=R!=null?R:b[Math.ceil((b.length-1)/2)])!=null?F:o[0];P.quality!==((Y=d==null?void 0:d.last)==null?void 0:Y.quality)&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${o.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -19,7 +19,7 @@ var Is="2.0.106-dev.8484fdea.0";var te=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
19
19
|
playbackRate: ${n},
|
|
20
20
|
playbackRateFactor: ${f},
|
|
21
21
|
forwardBufferHealth: ${s},
|
|
22
|
-
bitrateFactor: ${
|
|
22
|
+
bitrateFactor: ${S},
|
|
23
23
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
24
24
|
droppedVideoMaxQualityLimit: ${l},
|
|
25
25
|
limitsAreInvalid: ${T},
|
|
@@ -27,14 +27,14 @@ var Is="2.0.106-dev.8484fdea.0";var te=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
27
27
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
30
|
+
${Object.entries(g).map(([k,y])=>`${k}: ${y}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
|
-
[best track] ${
|
|
33
|
+
[best track] ${R==null?void 0:R.quality}
|
|
34
34
|
[selected track] ${P==null?void 0:P.quality}
|
|
35
35
|
`});let N=P&&d&&d.history[P.id]&&an()-d.history[P.id]<=i.trackCooldown&&(!d.last||P.id!==d.last.id);if(P!=null&&P.id&&d&&!N&&d.recordSelection(P),N&&(d!=null&&d.last)){let k=d.last;return d==null||d.recordSwitch(k),c({message:`
|
|
36
36
|
[last selected] ${k==null?void 0:k.quality}
|
|
37
|
-
`}),k}return d==null||d.recordSwitch(P),P},Qe=Td;var q=o=>new URL(o).hostname;import{assertNever as ln,assertNonNullable as cn,combine as Ud,debounce as Hd,ErrorCategory as pn,filter as hn,filterChanged as Gd,isNonNullable as ga,map as er,merge as mn,observableFrom as Wd,once as Qd,Subscription as jd,ValueSubject as Sa,videoQualityToHeight as Yd,videoSizeToQuality as qd}from"@vkontakte/videoplayer-shared";var sn=o=>{if(o instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(o.message))throw o;return!(o instanceof DOMException&&(o.code===20||o.name==="AbortError"))},ne=async o=>{let e=o.muted;try{await o.play()}catch(t){if(!sn(t))return!1;if(e)return console.warn(t),!1;o.muted=!0;try{await o.play()}catch(i){return sn(i)&&(o.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Ji,isNullable as xd,assertNonNullable as jt}from"@vkontakte/videoplayer-shared";import{isNonNullable as nn,assertNonNullable as Ki,now as Id}from"@vkontakte/videoplayer-shared";function z(){return Id()}function ha(o){return z()-o}function ma(o){let e=o.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,n,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),n&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function on(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function xt(o,e,t,i){let r=window.XMLHttpRequest,a,s,n,u=!1,d=0,l,c,p=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;Ki(l);let A=ha(l),F;if(A<f){F=f-A,setTimeout(b,F);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,C()},E=A=>(a=A,$),x=A=>(c=A,$),T=()=>(h="json",$),g=()=>{if(!u){if(--d>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},S=A=>(p=A,$),C=()=>{l=z(),s=new r,s.open("get",o);let A=0,F,j=0,k=()=>(Ki(l),Math.max(l,Math.max(F||0,j||0)));if(a&&s.addEventListener("progress",y=>{let B=z();a.updateChunk&&y.loaded>A&&(a.updateChunk(k(),y.loaded-A),A=y.loaded,F=B)}),n&&(s.timeout=n,s.addEventListener("timeout",()=>g())),s.addEventListener("load",()=>{if(u)return;Ki(s);let y=s.status;if(y>=200&&y<300){if(s.response.byteLength&&a){let B=s.response.byteLength-A;B&&a.updateChunk&&a.updateChunk(k(),B)}s.responseType==="json"&&!Object.values(s.response).length?g():(c&&c(),e(s.response))}else g()}),s.addEventListener("error",()=>{g()}),p){let y=()=>{Ki(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(j=z(),s.removeEventListener("readystatechange",y))};s.addEventListener("readystatechange",y)}return s.responseType=h,s.send(),$},$={withBitrateReporting:E,withParallel:S,withJSONResponse:T,withRetryCount:A=>(d=A,$),withRetryInterval:(A,F)=>(nn(A)&&(f=A),nn(F)&&(m=F),$),withTimeout:A=>(n=A,$),withFinally:x,send:C,abort:()=>{s&&(s.abort(),s=void 0),u=!0,c&&c()}};return $}var Wt=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,n=a.end-a.start;i+=s;let u=a.bytes*s/n;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Qt=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=z(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=z()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=xt(t,a,()=>r("error"),n),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=z();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-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 Xi=1e4,fa=3;var Ad=6e4,Pd=10,kd=1,wd=500,Yt=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 Wt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ma(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=ma(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",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.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 n=0;n<this.manifest.length;++n)a=this.manifest[n],!(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||Ji(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{on(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Qt(fa,Xi,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,n=null,u=null,d=null,l=!1,c=()=>{let g=a&&(!l||l===this.rep);return g||t("Not running!"),g},p=(g,S,C)=>{u&&u.abort(),u=xt(this.urlResolver.resolve(g,!1),S,C,()=>this._retryCallback()).withTimeout(Xi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(fa).withFinally(()=>{u=null}).send()},h=(g,S,C)=>{jt(this.filesFetcher),n==null||n.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),S,C,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},m=g=>{let S=i.playbackRate;i.playbackRate!==g&&(t(`Playback rate switch: ${S}=>${g}`),i.playbackRate=g)},f=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let C=z()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let w=this.bufferStates[N];g=Math.min(g,w.buf),w.ts<C&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${g} drop=${D} jitter=${this.sourceJitter}`);let P=g-kd;this.sourceJitter>=0?P-=this.sourceJitter/2:this.sourceJitter-=1,P>3?m(1.15):P>1?m(1.1):P>.3?m(1.05):m(1)}},E=g=>{let S,C=()=>S&&S.start?S.start.length:0,D=y=>S.start[y]/1e3,P=y=>S.dur[y]/1e3,N=y=>S.fragIndex+y,w=(y,B)=>({chunkIdx:N(y),startTS:D(y),dur:P(y),discontinuity:B}),$=()=>{let y=0;if(S&&S.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=B;this.sourceJitter>1&&(G+=this.sourceJitter-1);let M=S.dur.length-1;for(;M>=0&&(G-=S.dur[M],!(G<=0));--M);y=Math.min(M,S.dur.length-1-U),y=Math.max(y,0)}return w(y,!0)},A=y=>{let B=C();if(!(B<=0)){if(Ji(y)){for(let U=0;U<B;U++)if(D(U)>y)return w(U)}return $()}},F=y=>{let B=C(),U=y?y.chunkIdx+1:0,G=U-S.fragIndex;if(!(B<=0)){if(!y||G<0||G-B>Pd)return t(`Resync: offset=${G} bChunks=${B} chunk=`+JSON.stringify(y)),$();if(!(G>=B))return w(U-S.fragIndex,!1)}},j=(y,B,U)=>{d&&d.abort(),d=xt(this.urlResolver.resolve(y,!0,this.lowLatency),B,U,()=>this._retryCallback()).withTimeout(Xi).withRetryCount(fa).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(y,B)=>{j(g,U=>{if(!c())return;S=U;let G=!!S.lowLatency;G!==this.lowLatency&&f(G);let M=0;for(let ve=0;ve<S.dur.length;++ve)M+=S.dur[ve];M>0&&(jt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(M/S.dur.length)),r({name:"index",zeroTime:S.zeroTime,shiftDuration:S.shiftDuration}),this.sourceJitter=S.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,S.jitter/1e3)):1,y(A(B))},()=>this._handleNetworkError())},nextChunk:F}},x=()=>{a=!1,n&&n.abort(),u&&u.abort(),d&&d.abort(),jt(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:g=>{let{videoElement:S,logger:C}=this.params,D=E(e.jidxUrl),P,N,w,$,A=0,F,j,k,y=()=>{F&&(clearTimeout(F),F=void 0);let O=Math.max(wd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Z=A+O,de=z(),ce=Math.min(1e4,Z-de);A=de;let Be=()=>{d||c()&&D.seek(()=>{c()&&(A=z(),B(),y())})};ce>0?F=window.setTimeout(()=>{this.paused?y():Be()},ce):Be()},B=()=>{let O;for(;O=D.nextChunk($);)$=O,Ke(O);let Z=D.nextChunk(w);if(Z){if(w&&Z.discontinuity){C("Detected discontinuity; restarting playback"),this.paused?y():(x(),this._initPlayerWith(e));return}ve(Z)}else y()},U=(O,Z)=>{if(!c()||!this.sourceBuffer)return;let de,ce,Be,gt=Oe=>{window.setTimeout(()=>{c()&&U(O,Z)},Oe)};if(this.sourceBuffer.updating)C("Source buffer is updating; delaying appendBuffer"),gt(100);else{let Oe=z(),Je=S.currentTime;!this.paused&&S.buffered.length>1&&j===Je&&Oe-k>500&&(C("Stall suspected; trying to fix"),this._fixupStall()),j!==Je&&(j=Je,k=Oe);let St=this._getBufferSizeSec();if(St>30)C(`Buffered ${St} seconds; delaying appendBuffer`),gt(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:Oe,buf:St}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Z&&Z()}catch(Vt){if(Vt.name==="QuotaExceededError")C("QuotaExceededError; delaying appendBuffer"),Be=this.sourceBuffer.buffered.length,Be!==0&&(de=this.sourceBuffer.buffered.start(0),ce=Je,ce-de>4&&this.sourceBuffer.remove(de,ce-3)),gt(1e3);else throw Vt}}},G=()=>{N&&P&&(C([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(w)]),U(N,function(){N=null,B()}))},M=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),ve=O=>{c()&&h(M(O),(Z,de)=>{if(c()){if(de/=1e3,N=Z,w=O,s=O.startTS,de){let ce=Math.min(10,O.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}G()}},()=>this._handleNetworkError())},Ke=O=>{c()&&(jt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(M(O),!1)))},Ve=O=>{c()&&(e.cachedHeader=O,U(O,()=>{P=!0,G()}))};a=!0,D.seek(O=>{if(c()){if(A=z(),!O){y();return}$=O,!xd(g)||O.startTS>g?ve(O):(w=O,B())}},g),e.cachedHeader?Ve(e.cachedHeader):p(e.headerUrl,Ve,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>s},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Ji(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,jt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ji(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(p,h)=>{let m=z();if(this.chunkRateEstimator.addInterval(p,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:b}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),s=-1/0,n,u=!0,d=()=>{let c=a.get();if(c&&n&&this.autoQuality){if(u&&c>n&&ha(s)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=a.updateChunk(c,p);return h&&d(),h},notifySwitch:c=>{let p=z();c<n&&(s=p),n=c}}}_fetchManifest(e,t,i){this.manifestRequest=xt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Xi).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;ne(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 n=[];return s!=null&&s.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,n.push(u))}),n.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),n):(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))},Ad))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as $d,filter as un,fromEvent as Ld,interval as Md,isHigher as Rd,isInvariantQuality as Dd,isLower as Cd,merge as Vd,Subject as dn,Subscription as Bd}from"@vkontakte/videoplayer-shared";var ba=class{constructor(){this.onDroopedVideoFramesLimit$=new dn;this.subscription=new Bd;this.playing=!1;this.tracks=[];this.forceChecker$=new dn;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Dd(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var s;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&&Rd(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((s=this.limitCounts[this.currentQuality])!=null?s: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(Ld(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Md(this.droppedFramesChecker.checkTime).pipe(un(()=>this.playing),un(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe($d(this.droppedFramesChecker.checkTime)),i=Vd(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){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[s])=>Cd(a,s)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?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=ba;import{map as Od,Observable as _d}from"@vkontakte/videoplayer-shared";import{fromEvent as Nd}from"@vkontakte/videoplayer-shared";var qt=()=>{var o;return!!((o=window.documentPictureInPicture)!=null&&o.window)||!!document.pictureInPictureElement};var Fd=(o,e)=>new _d(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,n)=>{s.forEach(u=>t.next(u.isIntersecting||qt()))},{...i,...e});r.observe(o);let a=Nd(document,"visibilitychange").pipe(Od(s=>!document.hidden||qt())).subscribe(s=>t.next(s));return()=>{r.unobserve(o),a.unsubscribe}}),fe=Fd;var zd=["paused","playing","ready"],Kd=["paused","playing","ready"],zt=class{constructor(e){this.subscription=new jd;this.videoState=new L("stopped");this.representations$=new Sa([]);this.textTracksManager=new he;this.droppedFramesManager=new Zi;this.maxSeekBackTime$=new Sa(1/0);this.zeroTime$=new Sa(void 0);this.liveOffset=new $e;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let s=e.isBuffering;this.params.output.isBuffering$.next(s);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:pn.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let s=e.manifest,n=[];for(let u of s){let d=(t=u.name)!=null?t:u.index.toString(10),l=(i=Ge(u.name))!=null?i:qd(u.video),c=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:d,quality:l,bitrate:c,size:p};n.push({track:h,representation:u})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let s=e.quality,n=(a=this.representations$.getValue().find(({representation:u})=>u===s))==null?void 0:a.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),ga(n)&&this.params.output.currentVideoTrack$.next(n);break}case"bandwidth":{let{size:s,duration:n}=e;this.params.dependencies.throughputEstimator.addRawSpeed(s,n);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(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Kd.includes(e)&&(s||n)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&zd.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(K(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(K(this.params.source.url,u))}return;default:return ln(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:pn.WTF,message:"DashLiveProvider internal logic error",thrown:r})};mn(this.videoState.stateChangeStarted$.pipe(er(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(er(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(q(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=se(this.video);this.subscription.add(this.representations$.pipe(er(r=>r.map(({track:a})=>a)),hn(r=>!!r.length),Qd()).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(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.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(Gd(),er(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ud({zeroTime:this.zeroTime$.pipe(hn(ga)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ae(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(pe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).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(fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Yd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;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":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.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 ln(r.to)}},t)).add(mn(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Wd(["init"])).pipe(Hd(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 Yt({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(){var d,l,c,p,h,m;let e=this.representations$.getValue(),t=(l=(d=this.params.desiredState.videoTrack.getTransition())==null?void 0:d.to)!=null?l:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&ga(t)?t:Qe(e.map(({track:f})=>f),{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==null?void 0:r.id,s=this.params.desiredState.videoTrack.getTransition(),n=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==n)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==n){let f=(m=e.find(({track:b})=>b.id===a))==null?void 0:m.representation;cn(f,"Representations missing"),this.dash.startPlay(f,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;cn(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(K(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var fn=zt;var Me=(o,e)=>{let t=0;for(let i=0;i<o.length;i++){let r=o.start(i)*1e3,a=o.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Hl,assertNonNullable as Gl,debounce as Wl,ErrorCategory as Oa,filter as Io,filterChanged as _a,fromEvent as Ql,isLowerOrEqual as Eo,isNonNullable as jl,isInvariantQuality as Yl,map as xo,merge as Ir,observableFrom as ql,observeElementSize as zl,once as Ao,Subscription as Kl,ValueSubject as Jl}from"@vkontakte/videoplayer-shared";var Re=()=>window.ManagedMediaSource||window.MediaSource,tr=()=>{var o,e;return!!(window.ManagedMediaSource&&((e=(o=window.ManagedSourceBuffer)==null?void 0:o.prototype)!=null&&e.appendBuffer))},bn=()=>{var o,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(o=window.SourceBuffer)==null?void 0:o.prototype)!=null&&e.appendBuffer))},gn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as dr,CurrentClientBrowser as Zd,CurrentClientDevice as el,getCurrentBrowser as Sn,isAndroid as tl}from"@vkontakte/videoplayer-shared";var $n=tl(),be=document.createElement("video"),il='video/mp4; codecs="avc1.42000a,mp4a.40.2"',rl='video/mp4; codecs="hev1.1.6.L93.B0"',Ln='video/webm; codecs="vp09.00.10.08"',Mn='video/webm; codecs="av01.0.00M.08"',al='audio/mp4; codecs="mp4a.40.2"',sl='audio/webm; codecs="opus"',vn,yn,st={mms:tr(),mse:bn(),hls:!!((vn=be.canPlayType)!=null&&vn.call(be,"application/x-mpegurl")||(yn=be.canPlayType)!=null&&yn.call(be,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Tn,In,oe={mp4:!!((Tn=be.canPlayType)!=null&&Tn.call(be,"video/mp4")),webm:!!((In=be.canPlayType)!=null&&In.call(be,"video/webm")),cmaf:!0},rr,En,ar,xn,sr,An,nr,Pn,or,kn,ur,wn,ue={h264:!!((En=(rr=Re())==null?void 0:rr.isTypeSupported)!=null&&En.call(rr,il)),h265:!!((xn=(ar=Re())==null?void 0:ar.isTypeSupported)!=null&&xn.call(ar,rl)),vp9:!!((An=(sr=Re())==null?void 0:sr.isTypeSupported)!=null&&An.call(sr,Ln)),av1:!!((Pn=(nr=Re())==null?void 0:nr.isTypeSupported)!=null&&Pn.call(nr,Mn)),aac:!!((kn=(or=Re())==null?void 0:or.isTypeSupported)!=null&&kn.call(or,al)),opus:!!((wn=(ur=Re())==null?void 0:ur.isTypeSupported)!=null&&wn.call(ur,sl))},At=(ue.h264||ue.h265)&&ue.aac,nt,nl=async()=>{if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:Mn}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:Ln}})]);nt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{nl()}catch(o){console.error(o)}var Pt=st.hls&&oe.mp4,Rn=()=>Object.keys(ue).filter(o=>ue[o]),Dn=(o,e=!1,t=!1)=>{let i=st.mse||st.mms&&t;return o.filter(r=>{switch(r){case"DASH_SEP":return i&&oe.mp4&&At;case"DASH_WEBM":return i&&oe.webm&&ue.vp9&&ue.opus;case"DASH_WEBM_AV1":return i&&oe.webm&&ue.av1&&ue.opus;case"DASH_STREAMS":return i&&(oe.mp4&&At||oe.webm&&(ue.vp9||ue.av1)&&(ue.opus||ue.aac));case"DASH_LIVE":return st.mse&&oe.mp4&&At;case"DASH_LIVE_CMAF":return i&&oe.mp4&&At&&oe.cmaf;case"DASH_ONDEMAND":return i&&oe.mp4&&At;case"HLS":case"HLS_ONDEMAND":return Pt||e&&st.mse&&oe.mp4&&At;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Pt;case"MPEG":return oe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return st.webrtc&&st.ws&&ue.h264&&(oe.mp4||oe.webm);default:return dr(r)}})},ir=o=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(o){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return nt?nt[t].smooth?[t,e]:nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return nt?nt[t].powerEfficient?[t,e]:nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:dr(o)}return[e,t]},Cn=({webmCodec:o,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ir(o),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if($n)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",...ir(o),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ir(o),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ir(o),...r,"HLS","HLS_ONDEMAND"];default:dr(e)}return Pt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Vn=({androidPreferredFormat:o,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],n,u=Sn().device===el.Mac&&Sn().browser===Zd.Safari;if($n)switch(o){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=a;break}case"hls":case"mpeg":{n=s;break}default:dr(o)}else Pt&&!u?n=s:u?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=a;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},va=o=>o?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Bn=o=>{if(o.size!==0){if(o.size===1)return o.values().next().value.split(".").at(0);for(let e of o){let t=e.split(".").at(0);if(t==="opus"||t==="vp09"||t==="av01")return t}return o.values().next().value.split(".").at(0)}};import{ErrorCategory as Kt}from"@vkontakte/videoplayer-shared";var On=o=>{if(!o)return{id:"EmptyResponse",category:Kt.PARSER,message:"Empty response"};if(o.length<=2&&o.match(/^\d+$/))return{id:`UVError#${o}`,category:Kt.NETWORK,message:`UV Error ${o}`};let e=o.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Kt.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(o,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Kt.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Kt.PARSER,message:"Response is valid XML, but parser failed"}};var Jt=(o,e)=>{for(let t=0;t<o.length;t++)if(o.start(t)*1e3<=e&&o.end(t)*1e3>e)return!0;return!1};var _n=()=>window.matchMedia("(dynamic-range: high)").matches,ya=o=>{let e=o.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(),n=a+s;return["6E","7A","F4"].includes(n)}}return!1};import{abortable as Ca,assertNonNullable as ft,combine as br,ErrorCategory as Ye,filter as gr,filterChanged as fo,fromEvent as Mt,interval as Va,isNonNullable as bo,map as Ba,merge as Rt,Subject as go,Subscription as So,tap as Bl,throttle as Ol,ValueSubject as X}from"@vkontakte/videoplayer-shared";import{assertNever as ol,CurrentClientBrowser as ul,ErrorCategory as Nn,getCurrentBrowser as dl,Subject as Fn}from"@vkontakte/videoplayer-shared";var ll=16,Gn=!1,Un,Hn;try{Gn=dl().browser===ul.Safari&&parseInt((Hn=(Un=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Un[1])!=null?Hn:"",10)<=ll}catch(o){console.error(o)}var Ta=class{constructor(e){this.bufferFull$=new Fn;this.error$=new Fn;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Nn.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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;Gn&&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(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Nn.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:ol(t)}}},Wn=Ta;var Ia=o=>{let e=0;for(let t=0;t<o.length;t++)e+=o.end(t)-o.start(t);return e*1e3};import{abortable as Lt,assertNonNullable as ke,ErrorCategory as pt,fromEvent as wa,getExponentialDelay as $a,isNonNullable as oo,isNullable as Ie,once as wl,Subject as $l,Subscription as Ll,ValueSubject as vi}from"@vkontakte/videoplayer-shared";var _=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 kt=class extends _{};var Xt=class extends _{};var Zt=class extends _{constructor(t,i){super(t,i);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var ei=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ti=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ii=class extends _{constructor(t,i){super(t,i);this.data=this.content}};var W=class extends _{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ot=class extends W{constructor(t,i){super(t,i);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 r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,u=this.readUint32();a=this.readUint32();let d=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:d,SAPDeltaTime:l})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var ri=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends W{constructor(t,i){super(t,i);switch(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 ni=class extends W{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var oi=class extends W{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ui=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends W{constructor(t,i){super(t,i);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 li=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends W{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var hi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends W{constructor(t,i){super(t,i);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 fi=class extends W{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 bi=class extends W{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 pl={ftyp:Zt,moov:ei,moof:ti,mdat:ii,sidx:ot,trak:ri,mdia:ui,mfhd:pi,tkhd:di,traf:hi,tfhd:mi,tfdt:fi,trun:bi,minf:li,sv3d:ai,st3d:si,prhd:ni,proj:ci,equi:oi,uuid:Xt,unknown:kt},ut=class o{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(r){break}return t}createBox(e,t){let i=pl[e];return i?new i(t,new o):new kt(t,new o)}};var wt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 ml=new TextDecoder("ascii"),fl=o=>ml.decode(new DataView(o.buffer,o.byteOffset+4,4))==="ftyp",bl=o=>{let e=new ot(o,new ut),t=e.earliestPresentationTime/e.timescale*1e3,i=o.byteOffset+o.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,n={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,n})},gl=(o,e)=>{let i=new ut().parse(o),r=new wt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let n=a[0],u=s[s.length-1],d=n.source.byteOffset,c=u.source.byteOffset-n.source.byteOffset+u.size;return new DataView(o.buffer,d,c)},Sl=(o,e)=>{let i=new ut().parse(o),a=new wt(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),n=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,p)=>c+p,0):d=s.defaultSampleDuration*u.sampleCount,(Number(n.baseMediaDecodeTime)+d)/e*1e3},vl=o=>{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 ut().parse(o),r=new wt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Qn={validateData:fl,parseInit:vl,getIndexRange:()=>{},parseSegments:bl,parseFeedableSegmentChunk:gl,getSegmentEndTime:Sl};import{assertNonNullable as xa,isNonNullable as zn,isNullable as Tl}from"@vkontakte/videoplayer-shared";import{assertNever as yl}from"@vkontakte/videoplayer-shared";var jn={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"}},Yn=o=>{let e=o.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=gi(o,t),r=i in jn,a=r?jn[i].type:"binary",s=o.getUint8(t),n=0;s&128?n=1:s&64?n=2:s&32?n=3:s&16?n=4:s&8?n=5:s&4?n=6:s&2?n=7:s&1&&(n=8);let u=new DataView(o.buffer,o.byteOffset+t+1,n-1),d=s&255>>n,l=gi(u),c=d*2**((n-1)*8)+l,p=t+n,h;return p+c>o.byteLength?h=new DataView(o.buffer,o.byteOffset+p):h=new DataView(o.buffer,o.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},gi=(o,e=o.byteLength)=>{switch(e){case 1:return o.getUint8(0);case 2:return o.getUint16(0);case 3:return o.getUint8(0)*2**16+o.getUint16(1);case 4:return o.getUint32(0);case 5:return o.getUint8(0)*2**32+o.getUint32(1);case 6:return o.getUint16(0)*2**32+o.getUint32(2);case 7:{let t=o.getUint8(0)*281474976710656+o.getUint16(1)*4294967296+o.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Te=(o,e)=>{switch(e){case"int":return o.getInt8(0);case"uint":return gi(o);case"float":return o.byteLength===4?o.getFloat32(0):o.getFloat64(0);case"string":return new TextDecoder("ascii").decode(o);case"utf8":return new TextDecoder("utf-8").decode(o);case"date":return new Date(Date.UTC(2001,0)+o.getInt8(0)).getTime();case"master":return o;case"binary":return o;default:yl(e)}},dt=(o,e)=>{let t=0;for(;t<o.byteLength;){let i=new DataView(o.buffer,o.byteOffset+t),r=Yn(i);if(!e(r))return;r.type==="master"&&dt(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},qn=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=Yn(o);return dt(r.value,({tag:a,type:s,value:n})=>(a===17143?e=Te(n,s):a===17026?t=Te(n,s):a===17029&&(i=Te(n,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Kn=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Il=[231,22612,22743,167,171,163,160,175],El=o=>{let e,t,i,r,a=!1,s=!1,n=!1,u,d,l=!1,c=0;return dt(o,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let b=Te(m,h);d=gi(b)}else p!==21420&&(d=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=Te(m,h):p===17545?r=Te(m,h):p===21420&&d===475249515?u=Te(m,h):p===374648427?dt(m,({tag:b,type:E,value:x})=>b===30321?(l=Te(x,E)===1,!1):!0):a&&s&&Kn.includes(p)&&(n=!0),!n}),xa(e,"Failed to parse webm Segment start"),xa(t,"Failed to parse webm Segment end"),xa(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},xl=o=>{if(Tl(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Al=(o,e)=>{let t=!1,i=!1,r=n=>zn(n.time)&&zn(n.position),a=[],s;return dt(o,({tag:n,type:u,value:d})=>{switch(n){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Te(d,u));break;case 183:break;case 241:s&&(s.position=Te(d,u));break;default:t&&Kn.includes(n)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((n,u)=>{let{time:d,position:l}=n,c=a[u+1];return{status:"none",time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Pl=o=>{let e=0,t=!1;try{dt(o,i=>i.tag===524531317?i.tagSize<=o.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Il.includes(i.tag)?(e+i.tagSize<=o.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=o.byteLength&&t?new DataView(o.buffer,o.byteOffset,e):null},Jn={validateData:qn,parseInit:El,getIndexRange:xl,parseSegments:Al,parseFeedableSegmentChunk:Pl};var $t=o=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(o);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Jn;case"mp4":return Qn}}throw new ReferenceError(`Unsupported mime type ${o}`)};import{isNonNullable as Zn,isNullable as eo}from"@vkontakte/videoplayer-shared";var Xn=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var to=o=>{if(!o.startsWith("P"))return;let e=(s,n)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*n},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(o),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},lt=(o,e)=>{let t=o;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,(n,u)=>eo(a)?n:eo(u)?a:a.padStart(parseInt(u,10),"0"))}return t},ro=(o,e)=>{var g,S,C,D,P,N,w,$,A,F,j,k,y,B,U,G,M,ve,Ke,Ve,O,Z,de,ce,Be,gt,Oe,Je,St,Vt,Xa,Za,es,ts,is,rs,as,ss,ns,os,us,ds,ls,cs,ps,hs,ms,fs,bs,gs;let i=new DOMParser().parseFromString(o,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],n=(C=(S=(g=a.querySelector("BaseURL"))==null?void 0:g.textContent)==null?void 0:S.trim())!=null?C:"",u=s.children,d=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),f=a.getElementsByTagName("vk:Attrs")[0],b=f==null?void 0:f.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=to(h);else if(m){let ee=to(m);Zn(ee)&&(p=ee)}else b&&(p=parseInt(b,10));let E=0,x=(P=(D=a.getAttribute("profiles"))==null?void 0:D.split(","))!=null?P:[];for(let ee of u){let pu=(N=ee.getAttribute("id"))!=null?N:"id"+(E++).toString(10),Bt=(w=ee.getAttribute("mimeType"))!=null?w:"",_r=($=ee.getAttribute("codecs"))!=null?$:"",Nr=(A=ee.getAttribute("contentType"))!=null?A:Bt==null?void 0:Bt.split("/")[0],hu=(j=(F=ee.getAttribute("profiles"))==null?void 0:F.split(","))!=null?j:[],mu=(k=ee.getAttribute("lang"))!=null?k:void 0,fu=(U=(B=(y=ee.querySelector("Label"))==null?void 0:y.textContent)==null?void 0:B.trim())!=null?U:void 0,bu=ee.querySelectorAll("Representation"),gu=ee.querySelector("SegmentTemplate"),Su=(M=(G=ee.querySelector("Role"))==null?void 0:G.getAttribute("value"))!=null?M:void 0,Ot=Nr,Y={id:pu,language:mu,isDefault:Su==="main",label:fu,codecs:_r,hdr:Ot==="video"&&ya(_r),mime:Bt,representations:[]};for(let Q of bu){let vu=(ve=Q.getAttribute("lang"))!=null?ve:void 0,yu=(Ke=Q.getAttribute("label"))!=null?Ke:void 0,Tu=(Z=(O=(Ve=Q.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:O.trim())!=null?Z:"",Fr=new URL(Tu||n,e).toString(),vt=(de=Q.getAttribute("mimeType"))!=null?de:Bt,Ni=(Be=(ce=Q.getAttribute("codecs"))!=null?ce:_r)!=null?Be:"",Ur;if(Nr==="text"){let Xe=Q.getAttribute("id")||"",Hr=Xe.includes("_auto");Ur={id:Xe,isAuto:Hr,kind:"text",url:Fr}}else{let Xe=(Oe=(gt=Q.getAttribute("contentType"))!=null?gt:vt==null?void 0:vt.split("/")[0])!=null?Oe:Nr,Hr=(St=(Je=ee.getAttribute("profiles"))==null?void 0:Je.split(","))!=null?St:[],Iu=parseInt((Vt=Q.getAttribute("width"))!=null?Vt:"",10),Ss=parseInt((Xa=Q.getAttribute("height"))!=null?Xa:"",10),vs=parseInt((Za=Q.getAttribute("bandwidth"))!=null?Za:"",10)/1e3,ys=(es=Q.getAttribute("frameRate"))!=null?es:"",Eu=(ts=Q.getAttribute("quality"))!=null?ts:void 0,xu=ys?Xn(ys):void 0,Au=(is=Q.getAttribute("id"))!=null?is:"id"+(E++).toString(10),Pu=Xe==="video"?`${Ss}p`:Xe==="audio"?`${vs}Kbps`:Ni,ku=`${Au}@${Pu}`,wu=[...x,...hu,...Hr],Gr,$u=Q.querySelector("SegmentBase"),Ze=(rs=Q.querySelector("SegmentTemplate"))!=null?rs:gu;if($u){let et=(ss=(as=Q.querySelector("SegmentBase Initialization"))==null?void 0:as.getAttribute("range"))!=null?ss:"",[tt,Qr]=et.split("-").map(yt=>parseInt(yt,10)),_e={from:tt,to:Qr},_t=(ns=Q.querySelector("SegmentBase"))==null?void 0:ns.getAttribute("indexRange"),[jr,Fi]=_t?_t.split("-").map(yt=>parseInt(yt,10)):[],Nt=_t?{from:jr,to:Fi}:void 0;Gr={type:"byteRange",url:Fr,initRange:_e,indexRange:Nt}}else if(Ze){let et={representationId:(os=Q.getAttribute("id"))!=null?os:void 0,bandwidth:(us=Q.getAttribute("bandwidth"))!=null?us:void 0},tt=parseInt((ds=Ze.getAttribute("timescale"))!=null?ds:"",10),Qr=(ls=Ze.getAttribute("initialization"))!=null?ls:"",_e=Ze.getAttribute("media"),_t=(ps=parseInt((cs=Ze.getAttribute("startNumber"))!=null?cs:"",10))!=null?ps:1,jr=lt(Qr,et);if(!_e)throw new ReferenceError("No media attribute in SegmentTemplate");let Fi=(hs=Ze.querySelectorAll("SegmentTimeline S"))!=null?hs:[],Nt=[],yt=0,Yr="",qr=0;if(Fi.length){let Ui=_t,ye=0;for(let Tt of Fi){let xe=parseInt((ms=Tt.getAttribute("d"))!=null?ms:"",10),it=parseInt((fs=Tt.getAttribute("r"))!=null?fs:"",10)||0,Hi=parseInt((bs=Tt.getAttribute("t"))!=null?bs:"",10);ye=Number.isFinite(Hi)?Hi:ye;let zr=xe/tt*1e3,Kr=ye/tt*1e3;for(let Gi=0;Gi<it+1;Gi++){let Mu=lt(_e,{...et,segmentNumber:Ui.toString(10),segmentTime:(ye+Gi*xe).toString(10)}),Ts=(Kr!=null?Kr:0)+Gi*zr,Ru=Ts+zr;Ui++,Nt.push({time:{from:Ts,to:Ru},url:Mu})}ye+=(it+1)*xe,yt+=(it+1)*zr}qr=ye/tt*1e3,Yr=lt(_e,{...et,segmentNumber:Ui.toString(10),segmentTime:ye.toString(10)})}else if(Zn(p)){let ye=parseInt((gs=Ze.getAttribute("duration"))!=null?gs:"",10)/tt*1e3,Tt=Math.ceil(p/ye),xe=0;for(let it=1;it<Tt;it++){let Hi=lt(_e,{...et,segmentNumber:it.toString(10),segmentTime:xe.toString(10)});Nt.push({time:{from:xe,to:xe+ye},url:Hi}),xe+=ye}qr=xe,Yr=lt(_e,{...et,segmentNumber:Tt.toString(10),segmentTime:xe.toString(10)})}let Lu={time:{from:qr,to:1/0},url:Yr};Gr={type:"template",baseUrl:Fr,segmentTemplateUrl:_e,initUrl:jr,totalSegmentsDurationMs:yt,segments:Nt,nextSegmentBeyondManifest:Lu,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Xe||!vt)continue;let Wr={video:"video",audio:"audio",text:"text"}[Xe];if(!Wr)continue;Ot||(Ot=Wr),Ur={id:ku,kind:Wr,segmentReference:Gr,profiles:wu,duration:p,bitrate:vs,mime:vt,codecs:Ni,width:Iu,height:Ss,fps:xu,quality:Eu}}Y.language||(Y.language=vu),Y.label||(Y.label=yu),Y.mime||(Y.mime=vt),Y.codecs||(Y.codecs=Ni),Y.hdr||(Y.hdr=Ot==="video"&&ya(Ni)),Y.representations.push(Ur)}Ot&&r[Ot].push(Y)}return{dynamic:d,liveAvailabilityStartTime:c,duration:p,streams:r}};import{videoSizeToQuality as kl}from"@vkontakte/videoplayer-shared";var ao=({id:o,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;let s=(n=a?Ge(a):void 0)!=null?n:kl({width:e,height:t});return s&&{id:o,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},so=({id:o,bitrate:e})=>({id:o,bitrate:e}),lr=(o,e,t)=>{var r;let i=e.indexOf(o);return(r=t.at(Math.round(t.length*i/e.length)))!=null?r:t.at(-1)},no=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),Pa=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),ka=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),cr=o=>"url"in o,ct=o=>o.type==="template",Si=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var yi=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:n,compatibilityMode:u=!1,manifest:d}){this.currentSegmentLength$=new vi(0);this.onLastSegment$=new vi(!1);this.fullyBuffered$=new vi(!1);this.playingRepresentation$=new vi(void 0);this.playingRepresentationInit$=new vi(void 0);this.error$=new $l;this.gaps=[];this.subscription=new Ll;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=Lt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Wn(this.sourceBuffer),this.subscription.add(wa(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let n,u=this.mediaSource.readyState;u!=="open"&&(n={id:`SegmentEjection_source_${u}`,category:pt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),n!=null||(n={id:"SegmentEjection",category:pt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),this.error$.next(n)})),this.subscription.add(wa(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:pt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n)return;let u=Math.min(this.bufferLimit,Ia(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=Me(this.sourceBuffer.buffered,n),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(n,s*2,d<l)}else this.pruneBufferOld(n,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);ke(i,"No init buffer for starting representation"),ke(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=Lt(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);ke(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ie(a)||Ie(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ke(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();oo(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Lt(this.destroyAbortController.signal,async function*(e){var u,d;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let c=t.find(m=>m.id===l);c&&this.representations.set(l,c);let p=this.representations.get(l);if(!p||!ct(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(d=this.switchingToRepresentationId)!=null?d:this.downloadingRepresentationId,r=this.representations.get(i);ke(r);let a=this.segments.get(i);ke(a,"No segments for starting representation");let s=this.initData.get(i);if(ke(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=n,this.isLive=!!(d!=null&&d.dynamic),this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}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()){var d,l;if(Ie(e)||Ie(this.downloadingRepresentationId)||Ie(this.playingRepresentationId)||Ie(this.sourceBuffer)||!Ie(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ke(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((d=r==null?void 0:r.time.to)!=null?d:0)-((l=r==null?void 0:r.time.from)!=null?l:0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Me(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(a=h)}if(isFinite(this.bufferLimit)&&Ia(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Me(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,t.segmentReference.type,a),n.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(n.includes(r))c="high";else{let p=n.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(n,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!n.length&&Me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=i.at(-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}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;oo(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==null?void 0: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!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,s;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(n=>n.representations))!=null?i:[];for(let n of t){if(!n||!ct(n.segmentReference))return;let u=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),d=(r=this.segments.get(n.id))!=null?r:[],l=(s=(a=d.at(-1))==null?void 0:a.time.to)!=null?s:0,c=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=u.slice(c+1);this.segments.set(n.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ke(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!ct(r))return;let a=(t=this.segments.get(i.id))!=null?t:[],s=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),d=lt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}}findSegmentStartTime(e){var a,s,n;let t=(s=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?s:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(n=r==null?void 0:r.time.from)!=null?n:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.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(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}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:c,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,b=p>i||f||m===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&p<=i+E||h<=i+E;return(c==="none"||c==="partially_ejected"&&b&&x&&this.sourceBuffer&&!Jt(this.sourceBuffer.buffered,i))&&b&&x});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,n=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=d||n<=l);c++){let p=a[c];if(s+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){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:n,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Lt(n,async function*(){let l=$a(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(s,{range:a,signal:n,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;let c=new DataView(l);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=$t(t.mime);r.segment.time.to=h.getSegmentEndTime(c,p)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,n),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Si(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await Lt(s,async function*(){let u=$a(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),wa(window,"online").pipe(wl()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:n,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Si(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(ct(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:(n,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:n,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:pt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ct(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!a.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:pt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let s=this.representations.get(t);if(s)for(let n of this.activeSegments){let{segment:u}=n;if(n.representationId===t){if(a.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),l=$t(s.mime).parseFeedableSegmentChunk(d,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",n.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),n.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let n={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(n):this.onSomeByteRangesDataLoadedOld(n)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(!n)return;let u=n.segmentReference.type,d=e.byteLength;for(let l of this.activeSegments){let{segment:c}=l,p=u==="byteRange",h=p?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!p||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let f=p?c.byte.from-i:0,b=p?c.byte.to-i:e.byteLength,E=f<r,x=b<=r;if(c.status==="downloading"&&E&&x){c.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+f,h);this.sourceBufferTaskQueue.append(T,a).then(g=>g&&!a.aborted?this.onSegmentFullyAppended(l,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&(l.loadedBytes=Math.min(h,r-f),l.loadedBytes>l.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+f+l.feedingBytes,l.loadedBytes-l.feedingBytes),g=l.loadedBytes===h?T:$t(n.mime).parseFeedableSegmentChunk(T);g!=null&&g.byteLength&&(c.status="partially_fed",l.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,a).then(S=>{if(a.aborted)s();else if(S)l.fedBytes+=g.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;s()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let l=d.byte.from-i,c=d.byte.to-i,p=c-l+1,h=l<r,m=c<=r;if(h){if(d.status==="downloading"&&m){d.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(f,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===p?f:$t(n.mime).parseFeedableSegmentChunk(f);b!=null&&b.byteLength&&(d.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):s())}}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",cr(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);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||(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?Lt(this.destroyAbortController.signal,async function*(){let n=$a(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,$t(e.mime),r)).then(async n=>{if(!n)return;let{init:u,dataView:d,segments:l}=n,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let p=l;this.isLive&&ct(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:pt.WTF,message:"loadInit threw",thrown:n})});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||Ie(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((l,c)=>l.from-c.from);let d=[u[0]];for(let l=1;l<u.length;l++){let{from:c,to:p}=u[l],h=d[d.length-1];h.to>=c?h.to=Math.max(h.to,p):d.push(u[l])}return d},n=u=>{var l;if(a>=t)return r;r.push(u.time),r=s(r);let d=cr(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&d.status==="fed"&&n(d)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:d,to:l},url:"",status:"none"};n(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||l,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ie(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,n=!1,u=d=>{var c;a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let l=cr(d)?(c=d.size)!=null?c:0:d.byte.to-d.byte.from;r+=l};for(let d of this.segments.values())for(let l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&u(l)}if(n=isFinite(a)&&isFinite(s),!n){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&u(l)}}if(n=isFinite(a)&&isFinite(s),!n)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)){a=l,s=c;break}}if(n=isFinite(a)&&isFinite(s),!n&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>e+d&&c.status==="fed"&&u(c)}return n=isFinite(a)&&isFinite(s),n?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,n=this.sourceBuffer.buffered.end(a)*1e3;if(!(n<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&n>=i.time.to){r=void 0;break}n>i.time.from&&n<i.time.to&&(r.from=n),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){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:pt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ie(this.sourceBuffer)||Ie(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=1;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),n=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=s&&l.to+t>=n),d=e.filter(l=>s>=l.from-t&&s<=l.to+t||n>=l.from-t&&n<=l.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var Ti=o=>{let e=new URL(o);return e.searchParams.set("quic","1"),e.toString()};var uo=o=>{var a;let e=o.get("X-Delivery-Type"),t=o.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as Ii,assertNever as lo,fromEvent as co,merge as Ml,now as La,Subscription as Rl,ValueSubject as Ma}from"@vkontakte/videoplayer-shared";var pr=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new Ma(void 0);this.lastConnectionReused$=new Ma(void 0);this.lastRequestFirstBytes$=new Ma(void 0);this.abortAllController=new AbortController;this.subscription=new Rl;this.fetchManifest=Ii(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ti(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(Ei);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=Ii(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:n=!0,isLowLatency:u=!1}={}){var P,N;let d=e,l=new Headers;if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let w=new URL(d,location.href);w.searchParams.append("bytes",`${i.from}-${i.to}`),d=w.toString();break}default:lo(t)}this.requestQuic&&(d=Ti(d));let c=this.abortAllController.signal,p;if(s){let w=new AbortController;if(p=Ml(co(this.abortAllController.signal,"abort"),co(s,"abort")).subscribe(()=>{try{w.abort()}catch($){Ei($)}}),this.abortAllController.signal.aborted||s.aborted)try{w.abort()}catch($){Ei($)}c=w.signal}let h=La(),m=yield fetch(d,{priority:a,headers:l,signal:c}).catch(Ei),f=La();if(!m)return p==null||p.unsubscribe(),null;if((P=this.throughputEstimator)==null||P.addRawRtt(f-h),!m.ok||!m.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!r&&!n)return p==null||p.unsubscribe(),m.arrayBuffer();let[b,E]=m.body.tee(),x=b.getReader();n&&((N=this.throughputEstimator)==null||N.trackStream(E,u));let T=0,g=new Uint8Array(0),S=!1,C=w=>{p==null||p.unsubscribe(),S=!0,Ei(w)},D=Ii(c,async function*({done:w,value:$}){if(T===0&&this.lastRequestFirstBytes$.next(La()-h),c.aborted){p==null||p.unsubscribe();return}if(!w&&$){let A=new Uint8Array(g.length+$.length);A.set(g),A.set($,g.length),g=A,T+=$.byteLength,r==null||r(new DataView(g.buffer),T),yield x==null?void 0:x.read().then(D,C)}}.bind(this));return yield x==null?void 0:x.read().then(D,C),p==null||p.unsubscribe(),S?null:g.buffer}.bind(this));this.fetchByteRangeRepresentation=Ii(this.abortAllController.signal,async function*(e,t,i){var E;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,n=a,u=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),n=Math.max(l,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:n},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(E=e.indexRange)!=null?E:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-s,m.to-m.from+1);else{let x=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!x)return null;f=new DataView(x)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=Ii(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=i}onHeadersReceived(e){let{type:t,reused:i}=uo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,s;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(s=await this.fetchTemplateRepresentation(e,i))!=null?s:null;default:lo(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ei=o=>{if(!Si(o))throw o};var ht=(o,e,t)=>t*e+(1-t)*o,Ra=(o,e)=>o.reduce((t,i)=>t+i,0)/e,po=(o,e,t,i)=>{let r=0,a=t,s=Ra(o,e),n=e<i?e:i;for(let u=0;u<n;u++)o[a]>s?r++:r--,a=(o.length+a-1)%o.length;return Math.abs(r)===n};import{isNullable as Dl,ValueSubject as ho}from"@vkontakte/videoplayer-shared";var je=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ho(e.initial),this.debounced$=new ho(e.initial);let t=(i=e.label)!=null?i:"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 n=0;n<this.pastMeasures.length;n++)this.pastMeasures[n]!==void 0&&(t+=(this.pastMeasures[n]-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)&&(Dl(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 hr=class extends je{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=ht(this.slow,t,this.params.emaAlphaSlow),this.fast=ht(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var mr=class extends je{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=Ra(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ht(this.emaSmoothed,t,this.params.emaAlpha);let r=po(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var fr=class extends je{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?ht(this.smoothed,t,this.params.emaAlpha):t}};var mt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new hr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new mr({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 fr({initial:e,label:"liveEdgeDelay",...t})}};var Da=(o,e)=>{o&&o.playbackRate!==e&&(o.playbackRate=e)};var vo=["timeupdate","progress","play","seeked","stalled","waiting"];var Sr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new So;this.representationSubscription=new So;this.state$=new L("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new go;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.isLive$=new X(!1);this.liveDuration$=new X(0);this.liveAvailabilityStartTime$=new X(void 0);this.bufferLength$=new X(0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.timeInWaiting=0;this.isActiveLowLatency$=new X(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new go;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Ca(this.destroyController.signal,async function*(e,t,i){var r;this.element=e,this.manifestUrlString=K(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ye.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ca(this.destroyController.signal,async function*(){var a,s;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ye.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=ro(e!=null?e:"",this.manifestUrlString)}catch(n){let u=(a=On(e))!=null?a:{id:"ManifestParsing",category:Ye.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(u)}if(!t)return null;let i=(n,u,d)=>{var l,c,p,h;return!!((c=(l=this.element)==null?void 0:l.canPlayType)!=null&&c.call(l,u)&&((h=(p=Re())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${d}"`))||n==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((s=t.duration)!=null?s:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let d=t.streams[n].filter(({mime:p,codecs:h})=>i(n,p,h)),l=new Set(d.map(({codecs:p})=>p)),c=Bn(l);if(c&&(r[n]=d.filter(({codecs:p})=>p.startsWith(c))),n==="video"){let p=_n(),h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);p&&h&&m?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}return{...t,streams:r}}.bind(this));this.initRepresentations=Ca(this.destroyController.signal,async function*(e,t,i){var c;ft(this.manifest),ft(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Mt(p,"error").pipe(gr(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ye.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?gn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&tr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.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},n=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new yi("video",this.source,n,s),this.bufferManagers=[this.videoBufferManager],bo(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new yi("audio",this.source,p,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(Va(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=ta(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(Rt(...vo.filter(p=>p!=="waiting").map(p=>Mt(this.element,p))).pipe(Ba(p=>this.element?Me(this.element.buffered,this.element.currentTime*1e3):0),fo(),gr(p=>!!p),Bl(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(fo()).subscribe(h=>Da(this.element,1))),this.representationSubscription.add(br({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(gr(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(br({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-f,T=1;Math.abs(x)>b&&(T=1+Math.sign(x)*E),Da(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var f,b;let m=0;if(h){let E=((b=(f=this.element)==null?void 0:f.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var g,S;return(S=(g=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:g.to)!=null?S:E}))-E}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(br({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Ol(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(ft(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=ta(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,S=isFinite(h)?h:m,C=this.isActiveLowLatency$.getValue(),D=E<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(C&&D);let P="none";if(C?P="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&D?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(N=>N.proceedLowLatencyLive()),P="active_low_latency"):b!==0&&S<x?P="live_forward_buffering":S<x+g&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let N=p-(x+T),w=this.normolizeLiveOffset(Math.trunc(b+N/f)),$=Math.abs(w-b),A;!h||$<=this.tuning.dashCmafLive.offsetCalculationError?A=b:w>0&&$>this.tuning.dashCmafLive.offsetCalculationError?A=w:A=0,this.manifestUrlString=K(this.manifestUrlString,A,2)}P!=="none"&&P!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Rt(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ba(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Rt(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ba(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Rt(this.forceEnded$,br({allBuffersFull:u,someBufferEnded:d}).pipe(gr(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Ye.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Rt(...this.bufferManagers.map(p=>p.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(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(c=this.manifest.duration)!=null?c:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&bo(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Va(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),r=>{this.error$.next({id:"GapWatchdog",category:Ye.WTF,message:"Error handling gaps",thrown:r})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new pr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=mt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var i,r,a,s;ft(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=K(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive((i=this.manifest)==null?void 0:i.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive((a=this.manifest)==null?void 0:a.streams.audio)))}initBuffer(){ft(this.element),this.state$.setState("running"),this.subscription.add(Rt(...vo.map(e=>Mt(this.element,e)),Mt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ye.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var i,r;if(this.element){if(this.timeInWaiting+=1e3,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);else{let a=this.element.currentTime*1e3;(i=this.videoBufferManager)==null||i.maintain(a),(r=this.audioBufferManager)==null||r.maintain(a)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Va(1e3).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ye.FATAL,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}seek(e,t){var r,a,s,n,u;ft(this.element),ft(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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(s=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?s:e),Jt(this.element.buffered,i)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)==null||n.abort()),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3}stop(){var e,t,i;(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,i=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let a of this.bufferManagers)for(let s of a.gaps)a.playingRepresentation$.getValue()===s.representation&&s.from-r<=t&&s.to+r>t&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?i.push(1/0):i.push(s.to));if(i.length){let a=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,a===1/0?this.forceEnded$.next():this.element.currentTime=a/1e3}}};var vr=class{constructor(e,t){this.fov=e,this.orientation=t}};var yr=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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?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 yo=`attribute vec2 a_vertex;
|
|
37
|
+
`}),k}return d==null||d.recordSwitch(P),P},Qe=Td;var z=o=>new URL(o).hostname;import{assertNever as ln,assertNonNullable as cn,combine as Ud,debounce as Hd,ErrorCategory as pn,filter as hn,filterChanged as Gd,isNonNullable as Sa,map as er,merge as mn,observableFrom as Wd,once as Qd,Subscription as jd,ValueSubject as ga,videoQualityToHeight as Yd,videoSizeToQuality as qd}from"@vkontakte/videoplayer-shared";var sn=o=>{if(o instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(o.message))throw o;return!(o instanceof DOMException&&(o.code===20||o.name==="AbortError"))},oe=async o=>{let e=o.muted;try{await o.play()}catch(t){if(!sn(t))return!1;if(e)return console.warn(t),!1;o.muted=!0;try{await o.play()}catch(i){return sn(i)&&(o.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Ji,isNullable as xd,assertNonNullable as jt}from"@vkontakte/videoplayer-shared";import{isNonNullable as nn,assertNonNullable as Ki,now as Id}from"@vkontakte/videoplayer-shared";function K(){return Id()}function ha(o){return K()-o}function ma(o){let e=o.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,n,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),n&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function on(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function xt(o,e,t,i){let r=window.XMLHttpRequest,a,s,n,u=!1,d=0,l,c,p=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;Ki(l);let A=ha(l),F;if(A<f){F=f-A,setTimeout(b,F);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,D()},E=A=>(a=A,$),x=A=>(c=A,$),T=()=>(h="json",$),S=()=>{if(!u){if(--d>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},g=A=>(p=A,$),D=()=>{l=K(),s=new r,s.open("get",o);let A=0,F,Y=0,k=()=>(Ki(l),Math.max(l,Math.max(F||0,Y||0)));if(a&&s.addEventListener("progress",y=>{let B=K();a.updateChunk&&y.loaded>A&&(a.updateChunk(k(),y.loaded-A),A=y.loaded,F=B)}),n&&(s.timeout=n,s.addEventListener("timeout",()=>S())),s.addEventListener("load",()=>{if(u)return;Ki(s);let y=s.status;if(y>=200&&y<300){if(s.response.byteLength&&a){let B=s.response.byteLength-A;B&&a.updateChunk&&a.updateChunk(k(),B)}s.responseType==="json"&&!Object.values(s.response).length?S():(c&&c(),e(s.response))}else S()}),s.addEventListener("error",()=>{S()}),p){let y=()=>{Ki(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=K(),s.removeEventListener("readystatechange",y))};s.addEventListener("readystatechange",y)}return s.responseType=h,s.send(),$},$={withBitrateReporting:E,withParallel:g,withJSONResponse:T,withRetryCount:A=>(d=A,$),withRetryInterval:(A,F)=>(nn(A)&&(f=A),nn(F)&&(m=F),$),withTimeout:A=>(n=A,$),withFinally:x,send:D,abort:()=>{s&&(s.abort(),s=void 0),u=!0,c&&c()}};return $}var Wt=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,n=a.end-a.start;i+=s;let u=a.bytes*s/n;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Qt=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=K(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=K()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=xt(t,a,()=>r("error"),n),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=K()}_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=K();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 n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-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 Xi=1e4,fa=3;var Ad=6e4,Pd=10,kd=1,wd=500,Yt=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 Wt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ma(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=ma(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",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.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 n=0;n<this.manifest.length;++n)a=this.manifest[n],!(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||Ji(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{on(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Qt(fa,Xi,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,n=null,u=null,d=null,l=!1,c=()=>{let S=a&&(!l||l===this.rep);return S||t("Not running!"),S},p=(S,g,D)=>{u&&u.abort(),u=xt(this.urlResolver.resolve(S,!1),g,D,()=>this._retryCallback()).withTimeout(Xi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(fa).withFinally(()=>{u=null}).send()},h=(S,g,D)=>{jt(this.filesFetcher),n==null||n.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),g,D,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},m=S=>{let g=i.playbackRate;i.playbackRate!==S&&(t(`Playback rate switch: ${g}=>${S}`),i.playbackRate=S)},f=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let D=K()-1e4,R=0;for(let N=0;N<this.bufferStates.length;N++){let w=this.bufferStates[N];S=Math.min(S,w.buf),w.ts<D&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${S} drop=${R} jitter=${this.sourceJitter}`);let P=S-kd;this.sourceJitter>=0?P-=this.sourceJitter/2:this.sourceJitter-=1,P>3?m(1.15):P>1?m(1.1):P>.3?m(1.05):m(1)}},E=S=>{let g,D=()=>g&&g.start?g.start.length:0,R=y=>g.start[y]/1e3,P=y=>g.dur[y]/1e3,N=y=>g.fragIndex+y,w=(y,B)=>({chunkIdx:N(y),startTS:R(y),dur:P(y),discontinuity:B}),$=()=>{let y=0;if(g&&g.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=B;this.sourceJitter>1&&(G+=this.sourceJitter-1);let j=g.dur.length-1;for(;j>=0&&(G-=g.dur[j],!(G<=0));--j);y=Math.min(j,g.dur.length-1-U),y=Math.max(y,0)}return w(y,!0)},A=y=>{let B=D();if(!(B<=0)){if(Ji(y)){for(let U=0;U<B;U++)if(R(U)>y)return w(U)}return $()}},F=y=>{let B=D(),U=y?y.chunkIdx+1:0,G=U-g.fragIndex;if(!(B<=0)){if(!y||G<0||G-B>Pd)return t(`Resync: offset=${G} bChunks=${B} chunk=`+JSON.stringify(y)),$();if(!(G>=B))return w(U-g.fragIndex,!1)}},Y=(y,B,U)=>{d&&d.abort(),d=xt(this.urlResolver.resolve(y,!0,this.lowLatency),B,U,()=>this._retryCallback()).withTimeout(Xi).withRetryCount(fa).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(y,B)=>{Y(S,U=>{if(!c())return;g=U;let G=!!g.lowLatency;G!==this.lowLatency&&f(G);let j=0;for(let O=0;O<g.dur.length;++O)j+=g.dur[O];j>0&&(jt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(j/g.dur.length)),r({name:"index",zeroTime:g.zeroTime,shiftDuration:g.shiftDuration}),this.sourceJitter=g.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,g.jitter/1e3)):1,y(A(B))},()=>this._handleNetworkError())},nextChunk:F}},x=()=>{a=!1,n&&n.abort(),u&&u.abort(),d&&d.abort(),jt(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:S=>{let{videoElement:g,logger:D}=this.params,R=E(e.jidxUrl),P,N,w,$,A=0,F,Y,k,y=()=>{F&&(clearTimeout(F),F=void 0);let C=Math.max(wd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ee=A+C,le=K(),pe=Math.min(1e4,ee-le);A=le;let Be=()=>{d||c()&&R.seek(()=>{c()&&(A=K(),B(),y())})};pe>0?F=window.setTimeout(()=>{this.paused?y():Be()},pe):Be()},B=()=>{let C;for(;C=R.nextChunk($);)$=C,bt(C);let ee=R.nextChunk(w);if(ee){if(w&&ee.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?y():(x(),this._initPlayerWith(e));return}O(ee)}else y()},U=(C,ee)=>{if(!c()||!this.sourceBuffer)return;let le,pe,Be,St=Oe=>{window.setTimeout(()=>{c()&&U(C,ee)},Oe)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),St(100);else{let Oe=K(),Ke=g.currentTime;!this.paused&&g.buffered.length>1&&Y===Ke&&Oe-k>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),Y!==Ke&&(Y=Ke,k=Oe);let gt=this._getBufferSizeSec();if(gt>30)D(`Buffered ${gt} seconds; delaying appendBuffer`),St(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:Oe,buf:gt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ee&&ee()}catch(Vt){if(Vt.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),Be=this.sourceBuffer.buffered.length,Be!==0&&(le=this.sourceBuffer.buffered.start(0),pe=Ke,pe-le>4&&this.sourceBuffer.remove(le,pe-3)),St(1e3);else throw Vt}}},G=()=>{N&&P&&(D([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(w)]),U(N,function(){N=null,B()}))},j=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),O=C=>{c()&&h(j(C),(ee,le)=>{if(c()){if(le/=1e3,N=ee,w=C,s=C.startTS,le){let pe=Math.min(10,C.dur/le);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*pe:pe}G()}},()=>this._handleNetworkError())},bt=C=>{c()&&(jt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(j(C),!1)))},Ve=C=>{c()&&(e.cachedHeader=C,U(C,()=>{P=!0,G()}))};a=!0,R.seek(C=>{if(c()){if(A=K(),!C){y();return}$=C,!xd(S)||C.startTS>S?O(C):(w=C,B())}},S),e.cachedHeader?Ve(e.cachedHeader):p(e.headerUrl,Ve,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>s},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Ji(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,jt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ji(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(p,h)=>{let m=K();if(this.chunkRateEstimator.addInterval(p,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:b}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),s=-1/0,n,u=!0,d=()=>{let c=a.get();if(c&&n&&this.autoQuality){if(u&&c>n&&ha(s)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=a.updateChunk(c,p);return h&&d(),h},notifySwitch:c=>{let p=K();c<n&&(s=p),n=c}}}_fetchManifest(e,t,i){this.manifestRequest=xt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Xi).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 n=[];return s!=null&&s.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,n.push(u))}),n.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),n):(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))},Ad))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as $d,filter as un,fromEvent as Ld,interval as Md,isHigher as Rd,isInvariantQuality as Dd,isLower as Cd,merge as Vd,Subject as dn,Subscription as Bd}from"@vkontakte/videoplayer-shared";var ba=class{constructor(){this.onDroopedVideoFramesLimit$=new dn;this.subscription=new Bd;this.playing=!1;this.tracks=[];this.forceChecker$=new dn;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Dd(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var s;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&&Rd(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((s=this.limitCounts[this.currentQuality])!=null?s: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(Ld(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Md(this.droppedFramesChecker.checkTime).pipe(un(()=>this.playing),un(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe($d(this.droppedFramesChecker.checkTime)),i=Vd(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){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[s])=>Cd(a,s)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?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=ba;import{map as Od,Observable as _d}from"@vkontakte/videoplayer-shared";import{fromEvent as Nd}from"@vkontakte/videoplayer-shared";var qt=()=>{var o;return!!((o=window.documentPictureInPicture)!=null&&o.window)||!!document.pictureInPictureElement};var Fd=(o,e)=>new _d(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,n)=>{s.forEach(u=>t.next(u.isIntersecting||qt()))},{...i,...e});r.observe(o);let a=Nd(document,"visibilitychange").pipe(Od(s=>!document.hidden||qt())).subscribe(s=>t.next(s));return()=>{r.unobserve(o),a.unsubscribe}}),be=Fd;var zd=["paused","playing","ready"],Kd=["paused","playing","ready"],zt=class{constructor(e){this.subscription=new jd;this.videoState=new L("stopped");this.representations$=new ga([]);this.textTracksManager=new me;this.droppedFramesManager=new Zi;this.maxSeekBackTime$=new ga(1/0);this.zeroTime$=new ga(void 0);this.liveOffset=new $e;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let s=e.isBuffering;this.params.output.isBuffering$.next(s);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:pn.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let s=e.manifest,n=[];for(let u of s){let d=(t=u.name)!=null?t:u.index.toString(10),l=(i=Ge(u.name))!=null?i:qd(u.video),c=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:d,quality:l,bitrate:c,size:p};n.push({track:h,representation:u})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let s=e.quality,n=(a=this.representations$.getValue().find(({representation:u})=>u===s))==null?void 0:a.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),Sa(n)&&this.params.output.currentVideoTrack$.next(n);break}case"bandwidth":{let{size:s,duration:n}=e;this.params.dependencies.throughputEstimator.addRawSpeed(s,n);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(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Kd.includes(e)&&(s||n)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&zd.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(J(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(J(this.params.source.url,u))}return;default:return ln(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:pn.WTF,message:"DashLiveProvider internal logic error",thrown:r})};mn(this.videoState.stateChangeStarted$.pipe(er(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(er(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=re(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(z(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=ne(this.video);this.subscription.add(this.representations$.pipe(er(r=>r.map(({track:a})=>a)),hn(r=>!!r.length),Qd()).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(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.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(Gd(),er(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ud({zeroTime:this.zeroTime$.pipe(hn(Sa)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ae(this.video,this.params.desiredState.isLooped,t)).add(se(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(he(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).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&&Yd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;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":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.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 ln(r.to)}},t)).add(mn(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Wd(["init"])).pipe(Hd(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),ae(this.video)}createLiveDashPlayer(){let e=new Yt({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(){var d,l,c,p,h,m;let e=this.representations$.getValue(),t=(l=(d=this.params.desiredState.videoTrack.getTransition())==null?void 0:d.to)!=null?l:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Sa(t)?t:Qe(e.map(({track:f})=>f),{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==null?void 0:r.id,s=this.params.desiredState.videoTrack.getTransition(),n=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==n)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==n){let f=(m=e.find(({track:b})=>b.id===a))==null?void 0:m.representation;cn(f,"Representations missing"),this.dash.startPlay(f,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;cn(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(J(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var fn=zt;var Me=(o,e)=>{let t=0;for(let i=0;i<o.length;i++){let r=o.start(i)*1e3,a=o.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Hl,assertNonNullable as Gl,debounce as Wl,ErrorCategory as Oa,filter as Io,filterChanged as _a,fromEvent as Ql,isLowerOrEqual as Eo,isNonNullable as jl,isInvariantQuality as Yl,map as xo,merge as Ir,observableFrom as ql,observeElementSize as zl,once as Ao,Subscription as Kl,ValueSubject as Jl}from"@vkontakte/videoplayer-shared";var Re=()=>window.ManagedMediaSource||window.MediaSource,tr=()=>{var o,e;return!!(window.ManagedMediaSource&&((e=(o=window.ManagedSourceBuffer)==null?void 0:o.prototype)!=null&&e.appendBuffer))},bn=()=>{var o,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(o=window.SourceBuffer)==null?void 0:o.prototype)!=null&&e.appendBuffer))},Sn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as dr,CurrentClientBrowser as Zd,CurrentClientDevice as el,getCurrentBrowser as gn,isAndroid as tl}from"@vkontakte/videoplayer-shared";var $n=tl(),Se=document.createElement("video"),il='video/mp4; codecs="avc1.42000a,mp4a.40.2"',rl='video/mp4; codecs="hev1.1.6.L93.B0"',Ln='video/webm; codecs="vp09.00.10.08"',Mn='video/webm; codecs="av01.0.00M.08"',al='audio/mp4; codecs="mp4a.40.2"',sl='audio/webm; codecs="opus"',vn,yn,at={mms:tr(),mse:bn(),hls:!!((vn=Se.canPlayType)!=null&&vn.call(Se,"application/x-mpegurl")||(yn=Se.canPlayType)!=null&&yn.call(Se,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Tn,In,ue={mp4:!!((Tn=Se.canPlayType)!=null&&Tn.call(Se,"video/mp4")),webm:!!((In=Se.canPlayType)!=null&&In.call(Se,"video/webm")),cmaf:!0},rr,En,ar,xn,sr,An,nr,Pn,or,kn,ur,wn,de={h264:!!((En=(rr=Re())==null?void 0:rr.isTypeSupported)!=null&&En.call(rr,il)),h265:!!((xn=(ar=Re())==null?void 0:ar.isTypeSupported)!=null&&xn.call(ar,rl)),vp9:!!((An=(sr=Re())==null?void 0:sr.isTypeSupported)!=null&&An.call(sr,Ln)),av1:!!((Pn=(nr=Re())==null?void 0:nr.isTypeSupported)!=null&&Pn.call(nr,Mn)),aac:!!((kn=(or=Re())==null?void 0:or.isTypeSupported)!=null&&kn.call(or,al)),opus:!!((wn=(ur=Re())==null?void 0:ur.isTypeSupported)!=null&&wn.call(ur,sl))},At=(de.h264||de.h265)&&de.aac,st,nl=async()=>{if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:Mn}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:Ln}})]);st={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{nl()}catch(o){console.error(o)}var Pt=at.hls&&ue.mp4,Rn=()=>Object.keys(de).filter(o=>de[o]),Dn=(o,e=!1,t=!1)=>{let i=at.mse||at.mms&&t;return o.filter(r=>{switch(r){case"DASH_SEP":return i&&ue.mp4&&At;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&&At||ue.webm&&(de.vp9||de.av1)&&(de.opus||de.aac));case"DASH_LIVE":return at.mse&&ue.mp4&&At;case"DASH_LIVE_CMAF":return i&&ue.mp4&&At&&ue.cmaf;case"DASH_ONDEMAND":return i&&ue.mp4&&At;case"HLS":case"HLS_ONDEMAND":return Pt||e&&at.mse&&ue.mp4&&At;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Pt;case"MPEG":return ue.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return at.webrtc&&at.ws&&de.h264&&(ue.mp4||ue.webm);default:return dr(r)}})},ir=o=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(o){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return st?st[t].smooth?[t,e]:st[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return st?st[t].powerEfficient?[t,e]:st[e].powerEfficient?[e,t]:[t,e]:[e,t];default:dr(o)}return[e,t]},Cn=({webmCodec:o,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ir(o),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if($n)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",...ir(o),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ir(o),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ir(o),...r,"HLS","HLS_ONDEMAND"];default:dr(e)}return Pt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Vn=({androidPreferredFormat:o,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],n,u=gn().device===el.Mac&&gn().browser===Zd.Safari;if($n)switch(o){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=a;break}case"hls":case"mpeg":{n=s;break}default:dr(o)}else Pt&&!u?n=s:u?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=a;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},va=o=>o?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Bn=o=>{if(o.size!==0){if(o.size===1)return o.values().next().value.split(".").at(0);for(let e of o){let t=e.split(".").at(0);if(t==="opus"||t==="vp09"||t==="av01")return t}return o.values().next().value.split(".").at(0)}};import{ErrorCategory as Kt}from"@vkontakte/videoplayer-shared";var On=o=>{if(!o)return{id:"EmptyResponse",category:Kt.PARSER,message:"Empty response"};if(o.length<=2&&o.match(/^\d+$/))return{id:`UVError#${o}`,category:Kt.NETWORK,message:`UV Error ${o}`};let e=o.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Kt.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(o,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Kt.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Kt.PARSER,message:"Response is valid XML, but parser failed"}};var Jt=(o,e)=>{for(let t=0;t<o.length;t++)if(o.start(t)*1e3<=e&&o.end(t)*1e3>e)return!0;return!1};var _n=()=>window.matchMedia("(dynamic-range: high)").matches,ya=o=>{let e=o.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(),n=a+s;return["6E","7A","F4"].includes(n)}}return!1};import{abortable as Ca,assertNonNullable as mt,combine as br,ErrorCategory as Ye,filter as Sr,filterChanged as fo,fromEvent as Mt,interval as Va,isNonNullable as bo,map as Ba,merge as Rt,Subject as So,Subscription as go,tap as Bl,throttle as Ol,ValueSubject as Z}from"@vkontakte/videoplayer-shared";import{assertNever as ol,CurrentClientBrowser as ul,ErrorCategory as Nn,getCurrentBrowser as dl,Subject as Fn}from"@vkontakte/videoplayer-shared";var ll=16,Gn=!1,Un,Hn;try{Gn=dl().browser===ul.Safari&&parseInt((Hn=(Un=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Un[1])!=null?Hn:"",10)<=ll}catch(o){console.error(o)}var Ta=class{constructor(e){this.bufferFull$=new Fn;this.error$=new Fn;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Nn.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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;Gn&&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(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Nn.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:ol(t)}}},Wn=Ta;var Ia=o=>{let e=0;for(let t=0;t<o.length;t++)e+=o.end(t)-o.start(t);return e*1e3};import{abortable as Lt,assertNonNullable as ke,ErrorCategory as ct,fromEvent as wa,getExponentialDelay as $a,isNonNullable as oo,isNullable as Ie,once as wl,Subject as $l,Subscription as Ll,ValueSubject as vi}from"@vkontakte/videoplayer-shared";var _=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 kt=class extends _{};var Xt=class extends _{};var Zt=class extends _{constructor(t,i){super(t,i);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var ei=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ti=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ii=class extends _{constructor(t,i){super(t,i);this.data=this.content}};var W=class extends _{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var nt=class extends W{constructor(t,i){super(t,i);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 r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,u=this.readUint32();a=this.readUint32();let d=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:d,SAPDeltaTime:l})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var ri=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends W{constructor(t,i){super(t,i);switch(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 ni=class extends W{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var oi=class extends W{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ui=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends W{constructor(t,i){super(t,i);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 li=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends W{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var hi=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends W{constructor(t,i){super(t,i);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 fi=class extends W{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 bi=class extends W{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 pl={ftyp:Zt,moov:ei,moof:ti,mdat:ii,sidx:nt,trak:ri,mdia:ui,mfhd:pi,tkhd:di,traf:hi,tfhd:mi,tfdt:fi,trun:bi,minf:li,sv3d:ai,st3d:si,prhd:ni,proj:ci,equi:oi,uuid:Xt,unknown:kt},ot=class o{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(r){break}return t}createBox(e,t){let i=pl[e];return i?new i(t,new o):new kt(t,new o)}};var wt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 ml=new TextDecoder("ascii"),fl=o=>ml.decode(new DataView(o.buffer,o.byteOffset+4,4))==="ftyp",bl=o=>{let e=new nt(o,new ot),t=e.earliestPresentationTime/e.timescale*1e3,i=o.byteOffset+o.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,n={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,n})},Sl=(o,e)=>{let i=new ot().parse(o),r=new wt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let n=a[0],u=s[s.length-1],d=n.source.byteOffset,c=u.source.byteOffset-n.source.byteOffset+u.size;return new DataView(o.buffer,d,c)},gl=(o,e)=>{let i=new ot().parse(o),a=new wt(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),n=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,p)=>c+p,0):d=s.defaultSampleDuration*u.sampleCount,(Number(n.baseMediaDecodeTime)+d)/e*1e3},vl=o=>{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 ot().parse(o),r=new wt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Qn={validateData:fl,parseInit:vl,getIndexRange:()=>{},parseSegments:bl,parseFeedableSegmentChunk:Sl,getSegmentEndTime:gl};import{assertNonNullable as xa,isNonNullable as zn,isNullable as Tl}from"@vkontakte/videoplayer-shared";import{assertNever as yl}from"@vkontakte/videoplayer-shared";var jn={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"}},Yn=o=>{let e=o.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Si(o,t),r=i in jn,a=r?jn[i].type:"binary",s=o.getUint8(t),n=0;s&128?n=1:s&64?n=2:s&32?n=3:s&16?n=4:s&8?n=5:s&4?n=6:s&2?n=7:s&1&&(n=8);let u=new DataView(o.buffer,o.byteOffset+t+1,n-1),d=s&255>>n,l=Si(u),c=d*2**((n-1)*8)+l,p=t+n,h;return p+c>o.byteLength?h=new DataView(o.buffer,o.byteOffset+p):h=new DataView(o.buffer,o.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Si=(o,e=o.byteLength)=>{switch(e){case 1:return o.getUint8(0);case 2:return o.getUint16(0);case 3:return o.getUint8(0)*2**16+o.getUint16(1);case 4:return o.getUint32(0);case 5:return o.getUint8(0)*2**32+o.getUint32(1);case 6:return o.getUint16(0)*2**32+o.getUint32(2);case 7:{let t=o.getUint8(0)*281474976710656+o.getUint16(1)*4294967296+o.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Te=(o,e)=>{switch(e){case"int":return o.getInt8(0);case"uint":return Si(o);case"float":return o.byteLength===4?o.getFloat32(0):o.getFloat64(0);case"string":return new TextDecoder("ascii").decode(o);case"utf8":return new TextDecoder("utf-8").decode(o);case"date":return new Date(Date.UTC(2001,0)+o.getInt8(0)).getTime();case"master":return o;case"binary":return o;default:yl(e)}},ut=(o,e)=>{let t=0;for(;t<o.byteLength;){let i=new DataView(o.buffer,o.byteOffset+t),r=Yn(i);if(!e(r))return;r.type==="master"&&ut(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},qn=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=Yn(o);return ut(r.value,({tag:a,type:s,value:n})=>(a===17143?e=Te(n,s):a===17026?t=Te(n,s):a===17029&&(i=Te(n,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Kn=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Il=[231,22612,22743,167,171,163,160,175],El=o=>{let e,t,i,r,a=!1,s=!1,n=!1,u,d,l=!1,c=0;return ut(o,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let b=Te(m,h);d=Si(b)}else p!==21420&&(d=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=Te(m,h):p===17545?r=Te(m,h):p===21420&&d===475249515?u=Te(m,h):p===374648427?ut(m,({tag:b,type:E,value:x})=>b===30321?(l=Te(x,E)===1,!1):!0):a&&s&&Kn.includes(p)&&(n=!0),!n}),xa(e,"Failed to parse webm Segment start"),xa(t,"Failed to parse webm Segment end"),xa(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},xl=o=>{if(Tl(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Al=(o,e)=>{let t=!1,i=!1,r=n=>zn(n.time)&&zn(n.position),a=[],s;return ut(o,({tag:n,type:u,value:d})=>{switch(n){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Te(d,u));break;case 183:break;case 241:s&&(s.position=Te(d,u));break;default:t&&Kn.includes(n)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((n,u)=>{let{time:d,position:l}=n,c=a[u+1];return{status:"none",time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Pl=o=>{let e=0,t=!1;try{ut(o,i=>i.tag===524531317?i.tagSize<=o.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Il.includes(i.tag)?(e+i.tagSize<=o.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=o.byteLength&&t?new DataView(o.buffer,o.byteOffset,e):null},Jn={validateData:qn,parseInit:El,getIndexRange:xl,parseSegments:Al,parseFeedableSegmentChunk:Pl};var $t=o=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(o);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Jn;case"mp4":return Qn}}throw new ReferenceError(`Unsupported mime type ${o}`)};import{isNonNullable as Zn,isNullable as eo}from"@vkontakte/videoplayer-shared";var Xn=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var to=o=>{if(!o.startsWith("P"))return;let e=(s,n)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*n},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(o),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},dt=(o,e)=>{let t=o;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,(n,u)=>eo(a)?n:eo(u)?a:a.padStart(parseInt(u,10),"0"))}return t},ro=(o,e)=>{var S,g,D,R,P,N,w,$,A,F,Y,k,y,B,U,G,j,O,bt,Ve,C,ee,le,pe,Be,St,Oe,Ke,gt,Vt,Xa,Za,es,ts,is,rs,as,ss,ns,os,us,ds,ls,cs,ps,hs,ms,fs,bs,Ss;let i=new DOMParser().parseFromString(o,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],n=(D=(g=(S=a.querySelector("BaseURL"))==null?void 0:S.textContent)==null?void 0:g.trim())!=null?D:"",u=s.children,d=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),f=a.getElementsByTagName("vk:Attrs")[0],b=f==null?void 0:f.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=to(h);else if(m){let te=to(m);Zn(te)&&(p=te)}else b&&(p=parseInt(b,10));let E=0,x=(P=(R=a.getAttribute("profiles"))==null?void 0:R.split(","))!=null?P:[];for(let te of u){let pu=(N=te.getAttribute("id"))!=null?N:"id"+(E++).toString(10),Bt=(w=te.getAttribute("mimeType"))!=null?w:"",_r=($=te.getAttribute("codecs"))!=null?$:"",Nr=(A=te.getAttribute("contentType"))!=null?A:Bt==null?void 0:Bt.split("/")[0],hu=(Y=(F=te.getAttribute("profiles"))==null?void 0:F.split(","))!=null?Y:[],mu=(k=te.getAttribute("lang"))!=null?k:void 0,fu=(U=(B=(y=te.querySelector("Label"))==null?void 0:y.textContent)==null?void 0:B.trim())!=null?U:void 0,bu=te.querySelectorAll("Representation"),Su=te.querySelector("SegmentTemplate"),gu=(j=(G=te.querySelector("Role"))==null?void 0:G.getAttribute("value"))!=null?j:void 0,Ot=Nr,q={id:pu,language:mu,isDefault:gu==="main",label:fu,codecs:_r,hdr:Ot==="video"&&ya(_r),mime:Bt,representations:[]};for(let Q of bu){let vu=(O=Q.getAttribute("lang"))!=null?O:void 0,yu=(bt=Q.getAttribute("label"))!=null?bt:void 0,Tu=(ee=(C=(Ve=Q.querySelector("BaseURL"))==null?void 0:Ve.textContent)==null?void 0:C.trim())!=null?ee:"",Fr=new URL(Tu||n,e).toString(),vt=(le=Q.getAttribute("mimeType"))!=null?le:Bt,Ni=(Be=(pe=Q.getAttribute("codecs"))!=null?pe:_r)!=null?Be:"",Ur;if(Nr==="text"){let Je=Q.getAttribute("id")||"",Hr=Je.includes("_auto");Ur={id:Je,isAuto:Hr,kind:"text",url:Fr}}else{let Je=(Oe=(St=Q.getAttribute("contentType"))!=null?St:vt==null?void 0:vt.split("/")[0])!=null?Oe:Nr,Hr=(gt=(Ke=te.getAttribute("profiles"))==null?void 0:Ke.split(","))!=null?gt:[],Iu=parseInt((Vt=Q.getAttribute("width"))!=null?Vt:"",10),gs=parseInt((Xa=Q.getAttribute("height"))!=null?Xa:"",10),vs=parseInt((Za=Q.getAttribute("bandwidth"))!=null?Za:"",10)/1e3,ys=(es=Q.getAttribute("frameRate"))!=null?es:"",Eu=(ts=Q.getAttribute("quality"))!=null?ts:void 0,xu=ys?Xn(ys):void 0,Au=(is=Q.getAttribute("id"))!=null?is:"id"+(E++).toString(10),Pu=Je==="video"?`${gs}p`:Je==="audio"?`${vs}Kbps`:Ni,ku=`${Au}@${Pu}`,wu=[...x,...hu,...Hr],Gr,$u=Q.querySelector("SegmentBase"),Xe=(rs=Q.querySelector("SegmentTemplate"))!=null?rs:Su;if($u){let Ze=(ss=(as=Q.querySelector("SegmentBase Initialization"))==null?void 0:as.getAttribute("range"))!=null?ss:"",[et,Qr]=Ze.split("-").map(yt=>parseInt(yt,10)),_e={from:et,to:Qr},_t=(ns=Q.querySelector("SegmentBase"))==null?void 0:ns.getAttribute("indexRange"),[jr,Fi]=_t?_t.split("-").map(yt=>parseInt(yt,10)):[],Nt=_t?{from:jr,to:Fi}:void 0;Gr={type:"byteRange",url:Fr,initRange:_e,indexRange:Nt}}else if(Xe){let Ze={representationId:(os=Q.getAttribute("id"))!=null?os:void 0,bandwidth:(us=Q.getAttribute("bandwidth"))!=null?us:void 0},et=parseInt((ds=Xe.getAttribute("timescale"))!=null?ds:"",10),Qr=(ls=Xe.getAttribute("initialization"))!=null?ls:"",_e=Xe.getAttribute("media"),_t=(ps=parseInt((cs=Xe.getAttribute("startNumber"))!=null?cs:"",10))!=null?ps:1,jr=dt(Qr,Ze);if(!_e)throw new ReferenceError("No media attribute in SegmentTemplate");let Fi=(hs=Xe.querySelectorAll("SegmentTimeline S"))!=null?hs:[],Nt=[],yt=0,Yr="",qr=0;if(Fi.length){let Ui=_t,ye=0;for(let Tt of Fi){let xe=parseInt((ms=Tt.getAttribute("d"))!=null?ms:"",10),tt=parseInt((fs=Tt.getAttribute("r"))!=null?fs:"",10)||0,Hi=parseInt((bs=Tt.getAttribute("t"))!=null?bs:"",10);ye=Number.isFinite(Hi)?Hi:ye;let zr=xe/et*1e3,Kr=ye/et*1e3;for(let Gi=0;Gi<tt+1;Gi++){let Mu=dt(_e,{...Ze,segmentNumber:Ui.toString(10),segmentTime:(ye+Gi*xe).toString(10)}),Ts=(Kr!=null?Kr:0)+Gi*zr,Ru=Ts+zr;Ui++,Nt.push({time:{from:Ts,to:Ru},url:Mu})}ye+=(tt+1)*xe,yt+=(tt+1)*zr}qr=ye/et*1e3,Yr=dt(_e,{...Ze,segmentNumber:Ui.toString(10),segmentTime:ye.toString(10)})}else if(Zn(p)){let ye=parseInt((Ss=Xe.getAttribute("duration"))!=null?Ss:"",10)/et*1e3,Tt=Math.ceil(p/ye),xe=0;for(let tt=1;tt<Tt;tt++){let Hi=dt(_e,{...Ze,segmentNumber:tt.toString(10),segmentTime:xe.toString(10)});Nt.push({time:{from:xe,to:xe+ye},url:Hi}),xe+=ye}qr=xe,Yr=dt(_e,{...Ze,segmentNumber:Tt.toString(10),segmentTime:xe.toString(10)})}let Lu={time:{from:qr,to:1/0},url:Yr};Gr={type:"template",baseUrl:Fr,segmentTemplateUrl:_e,initUrl:jr,totalSegmentsDurationMs:yt,segments:Nt,nextSegmentBeyondManifest:Lu,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Je||!vt)continue;let Wr={video:"video",audio:"audio",text:"text"}[Je];if(!Wr)continue;Ot||(Ot=Wr),Ur={id:ku,kind:Wr,segmentReference:Gr,profiles:wu,duration:p,bitrate:vs,mime:vt,codecs:Ni,width:Iu,height:gs,fps:xu,quality:Eu}}q.language||(q.language=vu),q.label||(q.label=yu),q.mime||(q.mime=vt),q.codecs||(q.codecs=Ni),q.hdr||(q.hdr=Ot==="video"&&ya(Ni)),q.representations.push(Ur)}Ot&&r[Ot].push(q)}return{dynamic:d,liveAvailabilityStartTime:c,duration:p,streams:r}};import{videoSizeToQuality as kl}from"@vkontakte/videoplayer-shared";var ao=({id:o,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;let s=(n=a?Ge(a):void 0)!=null?n:kl({width:e,height:t});return s&&{id:o,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},so=({id:o,bitrate:e})=>({id:o,bitrate:e}),lr=(o,e,t)=>{var r;let i=e.indexOf(o);return(r=t.at(Math.round(t.length*i/e.length)))!=null?r:t.at(-1)},no=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),Pa=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),ka=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),cr=o=>"url"in o,lt=o=>o.type==="template",gi=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var yi=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:n,compatibilityMode:u=!1,manifest:d}){this.currentSegmentLength$=new vi(0);this.onLastSegment$=new vi(!1);this.fullyBuffered$=new vi(!1);this.playingRepresentation$=new vi(void 0);this.playingRepresentationInit$=new vi(void 0);this.error$=new $l;this.gaps=[];this.subscription=new Ll;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=Lt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Wn(this.sourceBuffer),this.subscription.add(wa(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let n,u=this.mediaSource.readyState;u!=="open"&&(n={id:`SegmentEjection_source_${u}`,category:ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),n!=null||(n={id:"SegmentEjection",category:ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),this.error$.next(n)})),this.subscription.add(wa(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ct.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n)return;let u=Math.min(this.bufferLimit,Ia(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=Me(this.sourceBuffer.buffered,n),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(n,s*2,d<l)}else this.pruneBufferOld(n,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);ke(i,"No init buffer for starting representation"),ke(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=Lt(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);ke(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ie(a)||Ie(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ke(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();oo(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(s,1/0,!0)),this.maintain(s)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Lt(this.destroyAbortController.signal,async function*(e){var u,d;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let c=t.find(m=>m.id===l);c&&this.representations.set(l,c);let p=this.representations.get(l);if(!p||!lt(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(d=this.switchingToRepresentationId)!=null?d:this.downloadingRepresentationId,r=this.representations.get(i);ke(r);let a=this.segments.get(i);ke(a,"No segments for starting representation");let s=this.initData.get(i);if(ke(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=n,this.isLive=!!(d!=null&&d.dynamic),this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}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()){var d,l;if(Ie(e)||Ie(this.downloadingRepresentationId)||Ie(this.playingRepresentationId)||Ie(this.sourceBuffer)||!Ie(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ke(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((d=r==null?void 0:r.time.to)!=null?d:0)-((l=r==null?void 0:r.time.from)!=null?l:0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Me(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(a=h)}if(isFinite(this.bufferLimit)&&Ia(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Me(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let n=[];if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,t.segmentReference.type,a),n.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(n.includes(r))c="high";else{let p=n.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(n,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!n.length&&Me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=i.at(-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}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;oo(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==null?void 0: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!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,s;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(n=>n.representations))!=null?i:[];for(let n of t){if(!n||!lt(n.segmentReference))return;let u=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),d=(r=this.segments.get(n.id))!=null?r:[],l=(s=(a=d.at(-1))==null?void 0:a.time.to)!=null?s:0,c=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=u.slice(c+1);this.segments.set(n.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ke(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!lt(r))return;let a=(t=this.segments.get(i.id))!=null?t:[],s=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),d=dt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}}findSegmentStartTime(e){var a,s,n;let t=(s=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?s:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(n=r==null?void 0:r.time.from)!=null?n:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.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(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}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:c,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,b=p>i||f||m===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&p<=i+E||h<=i+E;return(c==="none"||c==="partially_ejected"&&b&&x&&this.sourceBuffer&&!Jt(this.sourceBuffer.buffered,i))&&b&&x});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,n=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=d||n<=l);c++){let p=a[c];if(s+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){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:n,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Lt(n,async function*(){let l=$a(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(s,{range:a,signal:n,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;let c=new DataView(l);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=$t(t.mime);r.segment.time.to=h.getSegmentEndTime(c,p)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,n),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),gi(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await Lt(s,async function*(){let u=$a(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),wa(window,"online").pipe(wl()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:n,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),gi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(lt(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:(n,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:n,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!lt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!a.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let s=this.representations.get(t);if(s)for(let n of this.activeSegments){let{segment:u}=n;if(n.representationId===t){if(a.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),l=$t(s.mime).parseFeedableSegmentChunk(d,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",n.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),n.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let n={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(n):this.onSomeByteRangesDataLoadedOld(n)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(!n)return;let u=n.segmentReference.type,d=e.byteLength;for(let l of this.activeSegments){let{segment:c}=l,p=u==="byteRange",h=p?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!p||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let f=p?c.byte.from-i:0,b=p?c.byte.to-i:e.byteLength,E=f<r,x=b<=r;if(c.status==="downloading"&&E&&x){c.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+f,h);this.sourceBufferTaskQueue.append(T,a).then(S=>S&&!a.aborted?this.onSegmentFullyAppended(l,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&(l.loadedBytes=Math.min(h,r-f),l.loadedBytes>l.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+f+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?T:$t(n.mime).parseFeedableSegmentChunk(T);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,this.sourceBufferTaskQueue.append(S,a).then(g=>{if(a.aborted)s();else if(g)l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;s()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let l=d.byte.from-i,c=d.byte.to-i,p=c-l+1,h=l<r,m=c<=r;if(h){if(d.status==="downloading"&&m){d.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(f,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===p?f:$t(n.mime).parseFeedableSegmentChunk(f);b!=null&&b.byteLength&&(d.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,a)&&!a.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):s())}}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",cr(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);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||(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?Lt(this.destroyAbortController.signal,async function*(){let n=$a(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,$t(e.mime),r)).then(async n=>{if(!n)return;let{init:u,dataView:d,segments:l}=n,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let p=l;this.isLive&<(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:ct.WTF,message:"loadInit threw",thrown:n})});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||Ie(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((l,c)=>l.from-c.from);let d=[u[0]];for(let l=1;l<u.length;l++){let{from:c,to:p}=u[l],h=d[d.length-1];h.to>=c?h.to=Math.max(h.to,p):d.push(u[l])}return d},n=u=>{var l;if(a>=t)return r;r.push(u.time),r=s(r);let d=cr(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&d.status==="fed"&&n(d)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)h.status==="none"&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:d,to:l},url:"",status:"none"};n(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||l,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ie(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,n=!1,u=d=>{var c;a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let l=cr(d)?(c=d.size)!=null?c:0:d.byte.to-d.byte.from;r+=l};for(let d of this.segments.values())for(let l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&u(l)}if(n=isFinite(a)&&isFinite(s),!n){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&u(l)}}if(n=isFinite(a)&&isFinite(s),!n)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)){a=l,s=c;break}}if(n=isFinite(a)&&isFinite(s),!n&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>e+d&&c.status==="fed"&&u(c)}return n=isFinite(a)&&isFinite(s),n?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,n=this.sourceBuffer.buffered.end(a)*1e3;if(!(n<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&n>=i.time.to){r=void 0;break}n>i.time.from&&n<i.time.to&&(r.from=n),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){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ct.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ie(this.sourceBuffer)||Ie(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=1;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),n=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=s&&l.to+t>=n),d=e.filter(l=>s>=l.from-t&&s<=l.to+t||n>=l.from-t&&n<=l.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var Ti=o=>{let e=new URL(o);return e.searchParams.set("quic","1"),e.toString()};var uo=o=>{var a;let e=o.get("X-Delivery-Type"),t=o.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as Ii,assertNever as lo,fromEvent as co,merge as Ml,now as La,Subscription as Rl,ValueSubject as Ma}from"@vkontakte/videoplayer-shared";var pr=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new Ma(void 0);this.lastConnectionReused$=new Ma(void 0);this.lastRequestFirstBytes$=new Ma(void 0);this.abortAllController=new AbortController;this.subscription=new Rl;this.fetchManifest=Ii(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ti(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(Ei);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=Ii(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:n=!0,isLowLatency:u=!1}={}){var P,N;let d=e,l=new Headers;if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let w=new URL(d,location.href);w.searchParams.append("bytes",`${i.from}-${i.to}`),d=w.toString();break}default:lo(t)}this.requestQuic&&(d=Ti(d));let c=this.abortAllController.signal,p;if(s){let w=new AbortController;if(p=Ml(co(this.abortAllController.signal,"abort"),co(s,"abort")).subscribe(()=>{try{w.abort()}catch($){Ei($)}}),this.abortAllController.signal.aborted||s.aborted)try{w.abort()}catch($){Ei($)}c=w.signal}let h=La(),m=yield fetch(d,{priority:a,headers:l,signal:c}).catch(Ei),f=La();if(!m)return p==null||p.unsubscribe(),null;if((P=this.throughputEstimator)==null||P.addRawRtt(f-h),!m.ok||!m.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!r&&!n)return p==null||p.unsubscribe(),m.arrayBuffer();let[b,E]=m.body.tee(),x=b.getReader();n&&((N=this.throughputEstimator)==null||N.trackStream(E,u));let T=0,S=new Uint8Array(0),g=!1,D=w=>{p==null||p.unsubscribe(),g=!0,Ei(w)},R=Ii(c,async function*({done:w,value:$}){if(T===0&&this.lastRequestFirstBytes$.next(La()-h),c.aborted){p==null||p.unsubscribe();return}if(!w&&$){let A=new Uint8Array(S.length+$.length);A.set(S),A.set($,S.length),S=A,T+=$.byteLength,r==null||r(new DataView(S.buffer),T),yield x==null?void 0:x.read().then(R,D)}}.bind(this));return yield x==null?void 0:x.read().then(R,D),p==null||p.unsubscribe(),g?null:S.buffer}.bind(this));this.fetchByteRangeRepresentation=Ii(this.abortAllController.signal,async function*(e,t,i){var E;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,n=a,u=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),n=Math.max(l,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:n},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(E=e.indexRange)!=null?E:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-s,m.to-m.from+1);else{let x=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!x)return null;f=new DataView(x)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=Ii(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=i}onHeadersReceived(e){let{type:t,reused:i}=uo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,s;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(s=await this.fetchTemplateRepresentation(e,i))!=null?s:null;default:lo(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ei=o=>{if(!gi(o))throw o};var pt=(o,e,t)=>t*e+(1-t)*o,Ra=(o,e)=>o.reduce((t,i)=>t+i,0)/e,po=(o,e,t,i)=>{let r=0,a=t,s=Ra(o,e),n=e<i?e:i;for(let u=0;u<n;u++)o[a]>s?r++:r--,a=(o.length+a-1)%o.length;return Math.abs(r)===n};import{isNullable as Dl,ValueSubject as ho}from"@vkontakte/videoplayer-shared";var je=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ho(e.initial),this.debounced$=new ho(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new X(`raw_${t}`),this.smoothedSeries$=new X(`smoothed_${t}`),this.reportedSeries$=new X(`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 n=0;n<this.pastMeasures.length;n++)this.pastMeasures[n]!==void 0&&(t+=(this.pastMeasures[n]-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)&&(Dl(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 hr=class extends je{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=pt(this.slow,t,this.params.emaAlphaSlow),this.fast=pt(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var mr=class extends je{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=Ra(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pt(this.emaSmoothed,t,this.params.emaAlpha);let r=po(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var fr=class extends je{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?pt(this.smoothed,t,this.params.emaAlpha):t}};var ht=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new hr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new mr({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 fr({initial:e,label:"liveEdgeDelay",...t})}};var Da=(o,e)=>{o&&o.playbackRate!==e&&(o.playbackRate=e)};var vo=["timeupdate","progress","play","seeked","stalled","waiting"];var gr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new go;this.representationSubscription=new go;this.state$=new L("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 So;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 So;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Ca(this.destroyController.signal,async function*(e,t,i){var r;this.element=e,this.manifestUrlString=J(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ye.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ca(this.destroyController.signal,async function*(){var a,s;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ye.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=ro(e!=null?e:"",this.manifestUrlString)}catch(n){let u=(a=On(e))!=null?a:{id:"ManifestParsing",category:Ye.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(u)}if(!t)return null;let i=(n,u,d)=>{var l,c,p,h;return!!((c=(l=this.element)==null?void 0:l.canPlayType)!=null&&c.call(l,u)&&((h=(p=Re())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${d}"`))||n==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((s=t.duration)!=null?s:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let d=t.streams[n].filter(({mime:p,codecs:h})=>i(n,p,h)),l=new Set(d.map(({codecs:p})=>p)),c=Bn(l);if(c&&(r[n]=d.filter(({codecs:p})=>p.startsWith(c))),n==="video"){let p=_n(),h=this.tuning.preferHDR,m=r.video.some(b=>b.hdr),f=r.video.some(b=>!b.hdr);p&&h&&m?r.video=r.video.filter(b=>b.hdr):f&&(r.video=r.video.filter(b=>!b.hdr))}}return{...t,streams:r}}.bind(this));this.initRepresentations=Ca(this.destroyController.signal,async function*(e,t,i){var c;mt(this.manifest),mt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Mt(p,"error").pipe(Sr(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ye.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Sn():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&tr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.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},n=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new yi("video",this.source,n,s),this.bufferManagers=[this.videoBufferManager],bo(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new yi("audio",this.source,p,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(Va(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=ta(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(Rt(...vo.filter(p=>p!=="waiting").map(p=>Mt(this.element,p))).pipe(Ba(p=>this.element?Me(this.element.buffered,this.element.currentTime*1e3):0),fo(),Sr(p=>!!p),Bl(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(fo()).subscribe(h=>Da(this.element,1))),this.representationSubscription.add(br({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Sr(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(br({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-f,T=1;Math.abs(x)>b&&(T=1+Math.sign(x)*E),Da(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var f,b;let m=0;if(h){let E=((b=(f=this.element)==null?void 0:f.currentTime)!=null?b:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var S,g;return(g=(S=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:S.to)!=null?g:E}))-E}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(br({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Ol(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(mt(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=ta(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,g=isFinite(h)?h:m,D=this.isActiveLowLatency$.getValue(),R=E<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(D&&R);let P="none";if(D?P="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&R?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(N=>N.proceedLowLatencyLive()),P="active_low_latency"):b!==0&&g<x?P="live_forward_buffering":g<x+S&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let N=p-(x+T),w=this.normolizeLiveOffset(Math.trunc(b+N/f)),$=Math.abs(w-b),A;!h||$<=this.tuning.dashCmafLive.offsetCalculationError?A=b:w>0&&$>this.tuning.dashCmafLive.offsetCalculationError?A=w:A=0,this.manifestUrlString=J(this.manifestUrlString,A,2)}P!=="none"&&P!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Rt(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ba(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Rt(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ba(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Rt(this.forceEnded$,br({allBuffersFull:u,someBufferEnded:d}).pipe(Sr(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Ye.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Rt(...this.bufferManagers.map(p=>p.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(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(c=this.manifest.duration)!=null?c:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&bo(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Va(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),r=>{this.error$.next({id:"GapWatchdog",category:Ye.WTF,message:"Error handling gaps",thrown:r})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new pr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=ht.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var i,r,a,s;mt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=J(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive((i=this.manifest)==null?void 0:i.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive((a=this.manifest)==null?void 0:a.streams.audio)))}initBuffer(){mt(this.element),this.state$.setState("running"),this.subscription.add(Rt(...vo.map(e=>Mt(this.element,e)),Mt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ye.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var i,r;if(this.element){if(this.timeInWaiting+=1e3,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);else{let a=this.element.currentTime*1e3;(i=this.videoBufferManager)==null||i.maintain(a),(r=this.audioBufferManager)==null||r.maintain(a)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Va(1e3).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ye.FATAL,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}seek(e,t){var r,a,s,n,u;mt(this.element),mt(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((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(s=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?s:e),Jt(this.element.buffered,i)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)==null||n.abort()),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3}stop(){var e,t,i;(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,i=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let a of this.bufferManagers)for(let s of a.gaps)a.playingRepresentation$.getValue()===s.representation&&s.from-r<=t&&s.to+r>t&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?i.push(1/0):i.push(s.to));if(i.length){let a=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,a===1/0?this.forceEnded$.next():this.element.currentTime=a/1e3}}};var vr=class{constructor(e,t){this.fov=e,this.orientation=t}};var yr=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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?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 yo=`attribute vec2 a_vertex;
|
|
38
38
|
attribute vec2 a_texel;
|
|
39
39
|
|
|
40
40
|
varying vec2 v_texel;
|
|
@@ -88,5 +88,5 @@ void main(void) {
|
|
|
88
88
|
// sample using new coordinates
|
|
89
89
|
gl_FragColor = texture2D(u_texture, tc);
|
|
90
90
|
}
|
|
91
|
-
`;var Tr=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 vr(this.params.fov,this.params.orientation),this.cameraRotationManager=new yr(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(yo,this.gl.VERTEX_SHADER),i=this.createShader(To,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,n=e+i,u=t-r,d=e+i,l=t+r,c=e-i,p=t+r;return[a,s,n,u,d,l,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var bt=class{constructor(e){this.subscription=new Kl;this.videoState=new L("stopped");this.elementSize$=new Jl(void 0);this.textTracksManager=new he;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 zi;this.textTracks=[];this.syncPlayback=()=>{var s,n,u;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==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let d=(n=(s=this.liveOffset)==null?void 0:s.getTotalPausedTime())!=null?n:0;this.seek(r.position-d,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"),v(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&v(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(i==null?void 0:i.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return Hl(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Tr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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.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(q(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Sr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=se(this.video),r=this.constructor.name,a=n=>{e.error$.next({id:r,category:Oa.WTF,message:`${r} internal logic error`,thrown:n})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(n,u)=>this.subscription.add(n.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Io(d=>!!d.length),Ao()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})})),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(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(Io(jl),Ao()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(xo(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ae(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(pe(this.video,t.playbackRate,i.playbackRateState$,r)),a(zl(this.video),this.elementSize$),a(fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams();if(Gl(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(Pa(h));let m=[];for(let f of h.representations){let b=so(f);m.push(b),this.audioTracksMap.set(b,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of l.video){c.push(ka(p));let h=[];for(let m of p.representations){let f=ao(m);f&&(h.push(f),this.videoTracksMap.set(f,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(c);for(let p of l.text)for(let h of p.representations){let m=no(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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:Oa.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(Ir(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$,Ql(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(d)||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),d==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0: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:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(_a()).subscribe(d=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:p}]=l,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(ka(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(_a()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[c,{stream:p}]=l,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Pa(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.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 n=t.playbackState.stateChangeStarted$.pipe(xo(({to:d})=>d==="ready"),_a());this.subscription.add(Ir(n,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(Ir(n,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Ir(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ql(["init"])).pipe(Wl(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var D,P,N,w,$,A,F,j,k,y,B,U,G;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(D=e.videoTrack.getState())==null?void 0:D.id,s=[...this.videoTracksMap.keys()].find(({id:M})=>M===r),n=t.currentVideoTrack$.getValue(),u=((w=(N=e.videoStream.getState())!=null?N:s&&((P=this.videoTracksMap.get(s))==null?void 0:P.stream))!=null?w:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let d=[...this.videoStreamsMap.keys()].find(({id:M})=>M===u.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let c=Me(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=($=e.audioStream.getState())!=null?$:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,f=[...this.audioStreamsMap.keys()].find(({id:M})=>M===(m==null?void 0:m.id)),b=0;if(f){if(s&&!i){let M=lr(s,l,(A=this.audioStreamsMap.get(f))!=null?A:[]);b=Math.max(b,(F=M==null?void 0:M.bitrate)!=null?F:-1/0)}if(n){let M=lr(n,l,(j=this.audioStreamsMap.get(f))!=null?j:[]);b=Math.max(b,(k=M==null?void 0:M.bitrate)!=null?k:-1/0)}}let E=Qe(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:h,current:n,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:x}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&i&&(E=(y=l.filter(M=>!Yl(M.quality)).sort((M,ve)=>{var Ke,Ve;return((Ke=ve.bitrate)!=null?Ke:0)-((Ve=M.bitrate)!=null?Ve:0)}).filter(M=>Eo(M.quality,E.quality)&&Eo(M.quality,x))[0])!=null?y:E);let T=i?E!=null?E:s:s!=null?s:E,g=f&&lr(T,l,(B=this.audioStreamsMap.get(f))!=null?B:[]),S=(U=this.videoTracksMap.get(T))==null?void 0:U.representation,C=g&&((G=this.audioTracksMap.get(g))==null?void 0:G.representation);if(S&&C)return[S,C];if(S&&!C&&this.audioTracksMap.size===0)return[S,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ne(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Oa.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),re(this.video)}};var Ai=class extends bt{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 Po,interval as Xl,map as Zl}from"@vkontakte/videoplayer-shared";var Pi=class extends bt{constructor(e){super(e),this.liveOffset=new $e}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(Po({interval:Xl(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(r-1);s<=0&&e.position$.next(s),(a=this.liveOffset)==null||a.resetTo(-s*1e3)}})).add(Po({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Zl(({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(()=>{var n;this.params.output.position$.next(e/1e3),(n=this.liveOffset)==null||n.resetTo(s,r)})}};import{assertNever as ki,assertNonNullable as ko,debounce as ec,ErrorCategory as Er,filter as tc,isNonNullable as ic,isNullable as rc,map as xr,merge as ac,Observable as sc,observableFrom as nc,Subscription as oc,videoSizeToQuality as uc}from"@vkontakte/videoplayer-shared";var Ee={};var Dt=(o,e)=>new sc(t=>{let i=(r,a)=>t.next(a);return o.on(e,i),()=>o.off(e,i)}),wi=class{constructor(e){this.subscription=new oc;this.videoState=new L("initializing");this.textTracksManager=new he;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==null?void 0: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:ki(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ki(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ki(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ki(e)}break;default:ki(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(q(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.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:Er.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||(Ee.Hls=r.default,Ee.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){ko(Ee.Hls,"hls.js not loaded"),this.hls=new Ee.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){ko(Ee.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:Er.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=se(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.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(Ae(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(pe(this.video,e.playbackRate,r.playbackRateState$,i)),a(fe(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(xr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(Dt(this.hls,Ee.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:Er.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)==null?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())==null?void 0:d.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Dt(this.hls,Ee.Events.MANIFEST_PARSED).pipe(xr(({levels:d})=>d.reduce((l,c)=>{var x,T;let p=c.name||c.height.toString(10),{width:h,height:m}=c,f=(T=Ge((x=c.attrs.QUALITY)!=null?x:""))!=null?T:uc({width:h,height:m});if(!f)return l;let b=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,E={id:p.toString(),quality:f,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:b};return this.trackLevels.set(p,{track:E,level:c}),l.push(E),l},[]))),t.availableVideoTracks$),a(Dt(this.hls,Ee.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let l=[];for(let c of d.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang,f="internal";l.push({id:p,url:h,language:m,type:f})}e.internalTextTracks.startTransitionTo(l)}}),a(Dt(this.hls,Ee.Events.LEVEL_LOADING).pipe(xr(({url:d})=>q(d))),t.hostname$),a(Dt(this.hls,Ee.Events.FRAG_CHANGED),d=>{var p,h,m,f;let{video:l,audio:c}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=c==null?void 0:c.endPTS)!=null?m:0)-((f=c==null?void 0:c.startPTS)!=null?f:0))*1e3)}),this.subscription.add(Fe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))==null?void 0:l.track},n=Dt(this.hls,Ee.Events.LEVEL_SWITCHED).pipe(xr(({level:d})=>s(this.hls.levels[d])));n.pipe(tc(ic)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Fe(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{var m;if(rc(d))return;let l=(m=this.trackLevels.get(d.id))==null?void 0:m.level;if(!l)return;let c=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:n,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=ac(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nc(["init"])).pipe(ec(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ne(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Er.DOM,thrown:t}))||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0)}};var wo="X-Playback-Duration",Na=async o=>{var r;let e=await fetch(o),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(wo)?parseInt(e.headers.get(wo),10):void 0};import{assertNever as mc,combine as fc,debounce as bc,ErrorCategory as Pr,filter as gc,filterChanged as Sc,isNonNullable as Lo,isNullable as kr,map as Mo,merge as vc,observableFrom as yc,Subscription as Tc,ValueSubject as Ua,VideoQuality as Ic}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as dc,getExponentialDelay as lc}from"@vkontakte/videoplayer-shared";var cc=o=>{let e=null;if(o.QUALITY&&(e=Ge(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=dc({width:t,height:i})}return e!=null?e:null},pc=(o,e)=>{var a,s;let t=o.split(`
|
|
92
|
-
`),i=[],r=[];for(let n=0;n<t.length;n++){let u=t[n],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!l)){if(d){let c=Object.fromEntries(d[1].split(",").map(x=>x.split("="))),p=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,h=cc(c),m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let f=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,b;if(c.RESOLUTION){let[x,T]=c.RESOLUTION.split("x").map(g=>parseInt(g,10));x&&T&&(b={width:x,height:T})}let E=new URL(t[++n],e).toString();h&&i.push({id:p,quality:h,url:E,bandwidth:m,size:b,fps:f})}if(l){let c=Object.fromEntries(l[1].split(",").map(f=>f.split("=")).map(([f,b])=>[f,b.replace(/^"|"$/g,"")])),p=(s=c.URI)==null?void 0:s.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,m=c.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},hc=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),Fa=0,$o=async(o,e=o,t)=>{let r=await(await fetch(o)).text();Fa+=1;try{let{qualityManifests:a,textTracks:s}=pc(r,e);return{qualityManifests:a,textTracks:s}}catch(a){if(Fa<=t.manifestRetryMaxCount)return await hc(lc(Fa-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),$o(o,e,t)}return{qualityManifests:[],textTracks:[]}},Ar=$o;var $i=class{constructor(e){this.subscription=new Tc;this.videoState=new L("stopped");this.textTracksManager=new he;this.manifests$=new Ua([]);this.liveOffset=new $e;this.manifestStartTime$=new Ua(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(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||n){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(v(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return mc(t)}};var t;this.params=e,this.video=ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ic.INVARIANT,url:this.params.source.url},Ar(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Pr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Pr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(q(this.params.source.url)),this.maxSeekBackTime$=new Ua((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let n=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:Pr.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=se(this.video),a=(n,u)=>this.subscription.add(n.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.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(pe(this.video,t.playbackRate,r.playbackRateState$,i)),a(fe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(Sc(),Mo(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Lo(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(q(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,d,l;let n=(l=(d=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:d.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(fc({startTime:this.manifestStartTime$.pipe(gc(Lo)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:u})=>this.params.output.liveTime$.next(n+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Mo(n=>n.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=vc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,yc(["init"])).pipe(bc(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(){var n,u;let e=this.selectManifest();if(kr(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:d,min:l}=(u=(n=t==null?void 0:t.to)!=null?n:i)!=null?u:{};for(let[c,p]of[[d,"mq"],[l,"lq"]]){let h=String(parseFloat(c||""));p&&c&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=K(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),Na(s).then(d=>{var l;if(!kr(d))this.maxSeekBackTime$.next(d);else{let c=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(kr(c)||!isFinite(c))try{fetch(s).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let f=new URL(h,s).toString();Na(f).then(b=>{kr(b)||this.maxSeekBackTime$.next(b)})}})}catch(p){}}})}playIfAllowed(){ne(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pr.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 Ec,debounce as xc,ErrorCategory as Ha,fromEvent as Ga,isNonNullable as Ac,isNullable as Pc,map as Ro,merge as Do,observableFrom as Co,Subscription as kc,ValueSubject as wc,VideoQuality as $c,isIOS as Lc}from"@vkontakte/videoplayer-shared";var Li=class{constructor(e){this.subscription=new kc;this.videoState=new L("stopped");this.textTracksManager=new he;this.manifests$=new wc([]);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(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||n){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:c}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&v(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Ec(t)}};this.params=e,this.video=ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$c.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(q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ar(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ha.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let n=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:Ha.WTF,message:"HlsProvider internal logic error",thrown:n})},r=se(this.video),a=(n,u)=>this.subscription.add(n.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.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(Ro(n=>n.to)),this.params.output.playbackState$),this.subscription.add(Ae(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(pe(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var c;let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Ac(d.to)){let p=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(q(h.url));let m=this.params.desiredState.playbackRate.getState(),f=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(m!==f){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(m),b.playbackRate=m)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n.state==="requested"&&this.seek(n.position)},i))),this.subscription.add(this.manifests$.pipe(Ro(n=>n.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Lc()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(Do(Ga(n,"addtrack"),Ga(n,"removetrack"),Ga(n,"change"),Co(["init"])).subscribe(()=>{for(let u=0;u<n.length;u++)n[u].mode="hidden"},i))}let s=Do(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Co(["init"])).pipe(xc(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(){var a,s;let e=this.selectManifest();if(Pc(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:n,min:u}=(s=(a=t==null?void 0:t.to)!=null?a:i)!=null?s:{};for(let[d,l]of[[n,"mq"],[u,"lq"]]){let c=String(parseFloat(d||""));l&&d&&r.searchParams.set(l,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ne(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ha.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Mc,assertNonNullable as Vo,debounce as Rc,ErrorCategory as Bo,isHigher as Dc,isHigherOrEqual as Cc,isInvariantQuality as Oo,isLowerOrEqual as Vc,isNonNullable as Bc,merge as Oc,observableFrom as _c,Subscription as Nc,map as Fc}from"@vkontakte/videoplayer-shared";var Mi=class{constructor(e){this.subscription=new Nc;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new he;this.syncPlayback=()=>{var u,d,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=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:c}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),s.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(d=this.trackUrls[s.to.id])==null?void 0:d.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?v(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(i==null?void 0:i.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return Mc(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=n=>{e.error$.next({id:"MpegProvider",category:Bo.WTF,message:"MpegProvider internal logic error",thrown:n})},r=se(this.video),a=(n,u)=>this.subscription.add(n.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.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(Fc(n=>n.to)),this.params.output.playbackState$),this.subscription.add(Ae(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(pe(this.video,t.playbackRate,r.playbackRateState$,i)),a(fe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,d;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let n=this.params.desiredState.videoTrack.getTransition();if(n&&Bc(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let l=this.params.desiredState.playbackRate.getState(),c=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(l!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Oc(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,_c(["init"])).pipe(Rc(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(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Vo(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Vo(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ti(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(q(t))}playIfAllowed(){ne(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,a,s,n;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(a=Object.values(this.trackUrls).find(c=>!Oo(c.track.quality)&&Vc(c.track.quality,e)))==null?void 0:a.track,d=(s=this.params.desiredState.videoTrack.getState())==null?void 0:s.id,l=(n=this.trackUrls[d!=null?d:"0"])==null?void 0:n.track;if(u&&l&&Cc(l.quality,u.quality)&&(t=u),!t){let c=Object.values(this.trackUrls).filter(h=>!Oo(h.track.quality)&&Dc(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(d=>d.track);t=Qe(u,{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 No,debounce as Wc,merge as Fo,observableFrom as Qc,Subscription as jc,map as Uo,ValueSubject as Yc,ErrorCategory as Qa,VideoQuality as qc}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Uc}from"@vkontakte/videoplayer-shared";var _o=["stun:videostun.mycdn.me:80"],Hc=1e3,Gc=3,Wa=()=>null,wr=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Wa;this.externalStopCallback=Wa;this.externalErrorCallback=Wa;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:_o}]};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:Uc.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(t){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),Hc)}normalizeOptions(e={}){let t={stunServerList:_o,maxRetryNumber:Gc,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ri=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new Yc(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(i==null?void 0:i.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return No(e)}};this.subscription=new jc,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ie(e.container,e.tuning),this.liveStreamClient=new wr(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.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:Qa.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};Fo(this.videoState.stateChangeStarted$.pipe(Uo(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Uo(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})});let r=se(this.video),a=(s,n)=>this.subscription.add(s.subscribe(n,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(fe(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(()=>{var s;((s=this.videoState.getTransition())==null?void 0:s.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 No(s.to)}},i)).add(Fo(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Qc(["init"])).pipe(Wc(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(q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:qc.INVARIANT}),this.video.srcObject=e,v(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Qa.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ne(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qa.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Di=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 Bi,assertNonNullable as qe,ErrorCategory as Lr,filter as ip,isNonNullable as Yo,isNullable as rp,map as ap,merge as sp,once as np,Subject as ge,Subscription as qo,ValueSubject as R}from"@vkontakte/videoplayer-shared";import{Observable as zc,map as Ho,Subscription as Kc,Subject as Jc}from"@vkontakte/videoplayer-shared";var Go=o=>new zc(e=>{let t=new Kc,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Ho(({from:d,to:l})=>`${d}-${l}`)),r=o.desiredPlaybackState$.stateChangeEnded$,a=o.providerChanged$.pipe(Ho(({type:d})=>d!==void 0)),s=new Jc,n=0,u="unknown";return t.add(i.subscribe(d=>{n&&window.clearTimeout(n),u=d,n=window.setTimeout(()=>s.next(d),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(n),u="unknown",n=0})),t.add(a.subscribe(d=>{n&&(window.clearTimeout(n),n=0,d&&(n=window.setTimeout(()=>s.next(u),o.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as Wo,Subscription as Xc,combine as Zc,filter as Qo,once as jo}from"@vkontakte/videoplayer-shared";var Ci=null,$r=null;function ja(){return Ci||(Ci=new(window.AudioContext||window.webkitAudioContext)),$r||($r=new GainNode(Ci,{gain:1}),$r.connect(Ci.destination)),{audioCtx:Ci,gainNode:$r}}import{getCurrentBrowser as ep,CurrentClientBrowser as tp}from"@vkontakte/videoplayer-shared";var Ct=class Ct{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Xc;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(Qo(s=>!!s.type),jo()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){let{browser:t}=ep();t===tp.Safari&&e!=="MPEG"||this.subscriptions.add(Zc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Qo(({playbackState:i,video:r,volume:{muted:a,volume:s}})=>i==="playing"&&!!r&&!a&&!!s),jo()).subscribe(({video:i})=>this.initAudioContextOnce(i)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=ja(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{var s;if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Ct.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(n){this.volumeMultiplierError$.next({id:Ct.errorId,category:Wo.VIDEO_PIPELINE,message:(s=n==null?void 0:n.message)!=null?s:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(s=>{var n;this.volumeMultiplierError$.next({id:Ct.errorId,category:Wo.VIDEO_PIPELINE,message:(n=s==null?void 0:s.message)!=null?n:"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=ja();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Ct.errorId="VolumeMultiplierManager";var Vi=Ct;var op={chunkDuration:5e3,maxParallelRequests:5},Oi=class{constructor(e){this.current$=new R({type:void 0});this.providerError$=new ge;this.noAvailableProvidersError$=new ge;this.volumeMultiplierError$=new ge;this.providerOutput={position$:new R(0),duration$:new R(1/0),volume$:new R({muted:!1,volume:1}),availableVideoStreams$:new R([]),currentVideoStream$:new R(void 0),availableVideoTracks$:new R([]),currentVideoTrack$:new R(void 0),availableAudioStreams$:new R([]),currentAudioStream$:new R(void 0),availableAudioTracks$:new R([]),currentVideoSegmentLength$:new R(0),currentAudioSegmentLength$:new R(0),isAudioAvailable$:new R(!0),autoVideoTrackLimitingAvailable$:new R(!1),autoVideoTrackLimits$:new R(void 0),currentBuffer$:new R(void 0),isBuffering$:new R(!0),error$:new ge,warning$:new ge,willSeekEvent$:new ge,seekedEvent$:new ge,loopedEvent$:new ge,endedEvent$:new ge,firstBytesEvent$:new ge,firstFrameEvent$:new ge,canplay$:new ge,isLive$:new R(void 0),isLowLatency$:new R(!1),canChangePlaybackSpeed$:new R(!0),liveTime$:new R(void 0),liveBufferTime$:new R(void 0),availableTextTracks$:new R([]),currentTextTrack$:new R(void 0),hostname$:new R(void 0),httpConnectionType$:new R(void 0),httpConnectionReused$:new R(void 0),inPiP$:new R(!1),inFullscreen$:new R(!1),element$:new R(void 0),elementVisible$:new R(!0),availableSources$:new R(void 0),is3DVideo$:new R(!1),playbackState$:new R("")};this.subscription=new qo;var n;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Dn([...Vn(this.params.tuning),...Cn(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>Yo(e.sources[u])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(u=>!r.includes(u)),...t.filter(u=>r.includes(u))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Di(a);let s=[...va(!0),...va(!1)];this.chromecastFormatsIterator=new Di(s.filter(u=>Yo(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Vi(this.providerOutput,this.current$,this.volumeMultiplierError$,(n=this.params.volumeMultiplier)!=null?n: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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(rp(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Lr.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.destroyProvider(),this.initProvider()}switchToNextProvider(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"});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}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Bi(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 n=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qe(n),new Ai({...s,source:n,sourceHls:u})}case"DASH_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return qe(n),new Pi({...s,source:n})}case"HLS":case"HLS_ONDEMAND":{let n=this.applyFailoverHost(t[e]);return qe(n),Pt||!this.params.tuning.useHlsJs?new Li({...s,source:n}):new wi({...s,source:n})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return qe(n),new $i({...s,source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let n=this.applyFailoverHost(t[e]);return qe(n),new Mi({...s,source:n})}case"DASH_LIVE":{let n=this.applyFailoverHost(t[e]);return qe(n),new fn({...s,source:n,config:{...op,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let n=this.applyFailoverHost(t[e]);return qe(n),new Ri({container:i,source:n,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 Bi(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return qe(n),new Ft({connection:n,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 Bi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Bi(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 Bi(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 qo,t=!1,i=0;return e.add(sp(this.providerOutput.error$,Go({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(ap(r=>({id:`ProviderHangup:${r}`,category:Lr.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(ip(({to:a})=>a==="playing"),np()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let s=r.category===Lr.NETWORK,n=r.category===Lr.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!n;u&&!n&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:"SCREEN")}})),e}};import{fromEvent as Mr,once as up,combine as dp,Subscription as zo,ValueSubject as Ya,map as lp,filter as cp,isNonNullable as Rr,now as le,safeStorage as qa}from"@vkontakte/videoplayer-shared";var pp=5e3,Ko="one_video_throughput",Jo="one_video_rtt",De=window.navigator.connection,Xo=()=>{let o=De==null?void 0:De.downlink;if(Rr(o)&&o!==10)return o*1e3},Zo=()=>{let o=De==null?void 0:De.rtt;if(Rr(o)&&o!==3e3)return o},eu=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},za=class o{constructor(e){this.subscription=new zo;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=o.load(Ko)||(e.useBrowserEstimation?Xo():void 0)||pp,i=(a=(r=o.load(Jo))!=null?r:e.useBrowserEstimation?Zo():void 0)!=null?a:0;if(this.throughput$=new Ya(t),this.rtt$=new Ya(i),this.rttAdjustedThroughput$=new Ya(eu(t,i,e.rttPenaltyRequestSize)),this.throughput=mt.getSmoothedValue(t,-1,e),this.rtt=mt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let s=()=>{let u=Xo();u&&this.throughput.next(u);let d=Zo();Rr(d)&&this.rtt.next(d)};De&&"onchange"in De&&this.subscription.add(Mr(De,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{qa.set(Ko,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{qa.set(Jo,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dp({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(lp(({throughput:s,rtt:n})=>eu(s,n,e.rttPenaltyRequestSize)),cp(s=>{let n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=le(),r=new zo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Mr(e,"progress").pipe(up()).subscribe(a=>{t=a.loaded,i=le()}));break;case 1:case 0:r.add(Mr(e,"loadstart").subscribe(()=>{t=0,i=le()}));break}r.add(Mr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,n=le(),u=s-t,d=n-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=le(),s=0,n=le(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=le();if(p-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=n-a;m&&this.addRawSpeed(s,m,1,t),s=c.byteLength,a=le()}else s+=c.byteLength;n=le()}else r+=c.byteLength,s+=c.byteLength,s>=this.tuningConfig.streamMinSampleSize&&le()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,le()-n,this.concurrentDownloads.size),s=0,n=le());await(i==null?void 0:i.read().then(d,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(o.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){var i;let t=qa.get(e);if(Rr(t))return(i=parseInt(t,10))!=null?i:void 0}},tu=za;import{fillWithDefault as hp,VideoQuality as iu}from"@vkontakte/videoplayer-shared";var ru={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,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:iu.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:iu.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,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!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},au=o=>{var e;return{...hp(o,ru),configName:[...(e=o.configName)!=null?e:[],...ru.configName]}};import{assertNonNullable as Dr,combine as Cr,ErrorCategory as Vr,filter as _i,filterChanged as Se,fromEvent as Ja,isNonNullable as yp,isNullable as Tp,Logger as Ip,map as V,mapTo as uu,merge as ze,now as Br,once as Ce,Subject as H,Subscription as du,tap as lu,ValueSubject as I,isHigher as Ep,isInvariantQuality as cu}from"@vkontakte/videoplayer-shared";import{merge as mp,map as fp,filter as su,isNonNullable as bp}from"@vkontakte/videoplayer-shared";var Ka=({seekState:o,position$:e})=>mp(o.stateChangeEnded$.pipe(fp(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),su(bp)),e.pipe(su(()=>o.getState().state==="none")));import{assertNonNullable as gp}from"@vkontakte/videoplayer-shared";var nu=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return gp(e,`Wrong container or containerId {${o.container}}`),e};import{filter as Sp,once as vp}from"@vkontakte/videoplayer-shared";var ou=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(Sp(r=>r.length>0),vp()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(o)};var Or=class{constructor(e={configName:[]}){this.subscription=new du;this.logger=new Ip;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new I(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new I("stopped"),position$:new I(0),duration$:new I(1/0),muted$:new I(!1),volume$:new I(1),availableVideoStreams$:new I([]),currentVideoStream$:new I(void 0),availableQualities$:new I([]),availableQualitiesFps$:new I({}),currentQuality$:new I(void 0),isAutoQualityEnabled$:new I(!0),autoQualityLimitingAvailable$:new I(!1),autoQualityLimits$:new I({}),availableAudioStreams$:new I([]),currentAudioStream$:new I(void 0),availableAudioTracks$:new I([]),isAudioAvailable$:new I(!0),currentPlaybackRate$:new I(1),currentBuffer$:new I({start:0,end:0}),isBuffering$:new I(!0),isStalled$:new I(!1),isEnded$:new I(!1),isLooped$:new I(!1),isLive$:new I(void 0),canChangePlaybackSpeed$:new I(void 0),atLiveEdge$:new I(void 0),atLiveDurationEdge$:new I(void 0),liveTime$:new I(void 0),liveBufferTime$:new I(void 0),currentFormat$:new I(void 0),availableTextTracks$:new I([]),currentTextTrack$:new I(void 0),throughputEstimation$:new I(void 0),rttEstimation$:new I(void 0),videoBitrate$:new I(void 0),hostname$:new I(void 0),httpConnectionType$:new I(void 0),httpConnectionReused$:new I(void 0),surface$:new I("none"),chromecastState$:new I("NOT_AVAILABLE"),chromecastDeviceName$:new I(void 0),intrinsicVideoSize$:new I(void 0),availableSources$:new I(void 0),is3DVideo$:new I(!1),currentVideoSegmentLength$:new I(0),currentAudioSegmentLength$:new I(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,firstBytes$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new I(void 0),tuningConfigName$:new I([]),enableDebugTelemetry$:new I(!1),dumpTelemetry:en};if(this.initLogs(),this.tuning=au(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ji({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new tu(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...s)=>{try{return a.apply(t,s)}catch(n){let u=s.map(c=>JSON.stringify(c,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Vr.WTF,message:l,thrown:n}),n}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=nu(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Oi({sources:e.sources,meta:(i=e.meta)!=null?i:{},failoverHosts:(r=e.failoverHosts)!=null?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!qt()?Ja(document,"visibilitychange").pipe(Ce()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.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){Dr(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(_i(i=>i.length>0),Ce()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;Dr(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return ou(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(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(Tp(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return yp(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.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(ze(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(_i(({from:e})=>e==="stopped"),Ce()).subscribe(()=>{this.initedAt=Br(),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();s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Vr.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(s=>s.destination),Se()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(V(s=>s.map(({quality:n})=>n).sort((n,u)=>cu(n)?1:cu(u)?-1:Ep(u,n)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let n={};for(let u of s)u.fps&&(n[u.quality]=u.fps);this.info.availableQualitiesFps$.next(n)})).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$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s==null?void 0:s.quality),this.info.videoBitrate$.next(s==null?void 0:s.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Se()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Se()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Se()).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!=null?s:{})})).add(e.providerOutput.currentBuffer$.pipe(V(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Cr({hasLiveOffsetByPaused:ze(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(s=>s.to),Se(),V(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:n})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(n));return}this.hasLiveOffsetByPaused.next(!1)})).add(Cr({atLiveEdge:Cr({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ka({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:s,position:n,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(n)<d/1e3}),Se(),lu(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:s,hasPausedTimeoutCase:n})=>s&&!n)).subscribe(this.info.atLiveEdge$)).add(Cr({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:s,position:n,duration:u})=>s&&(Math.abs(u)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),Se(),lu(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(s=>s.muted),Se()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(s=>s.volume),Se()).subscribe(this.info.volume$)).add(Ka({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ze(e.providerOutput.endedEvent$.pipe(uu(!0)),e.providerOutput.seekedEvent$.pipe(uu(!1))).pipe(Se()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(V(s=>({id:s?`No${s}`:"NoProviders",category:Vr.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Ce(),V(s=>s!=null?s:Br()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ce(),V(()=>Br()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ce(),V(()=>Br()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new I(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new I(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(_i(({to:s})=>s==="playing"),Ce()).subscribe(()=>i.next(!1)));let r=0,a=ze(e.providerOutput.isBuffering$,t,i).pipe(V(()=>{let s=e.providerOutput.isBuffering$.getValue(),n=t.getValue()||i.getValue();return s&&!n}),Se());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(ze(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s==null?void 0:s.videoWidth,height:s==null?void 0:s.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{var u,d;let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=s==null?void 0:s.size)==null?void 0:u.width,height:(d=s==null?void 0:s.size)==null?void 0:d.height},{width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ze(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),c;l==="CONNECTED"?c="second_screen":u?d?s?c="pip":n?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(V(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new du;this.subscription.add(t),this.subscription.add(e.current$.pipe(Se((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(_i(i=>i.length>0),Ce()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Qe(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(ze(this.desiredState.videoTrack.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(V(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Dr(this.providerContainer),Dr(e),Zs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Xs(i)),this.providerContainer.current$.subscribe(({type:i})=>Gt("provider",i)),e.duration$.subscribe(i=>Gt("duration",i)),e.availableVideoTracks$.pipe(_i(i=>!!i.length),Ce()).subscribe(i=>Gt("tracks",i)),this.events.fatalError$.subscribe(new J("fatalError")),this.events.managedError$.subscribe(new J("managedError")),e.position$.subscribe(new J("position")),e.currentVideoTrack$.pipe(V(i=>i==null?void 0:i.quality)).subscribe(new J("quality")),this.info.currentBuffer$.subscribe(new J("buffer")),e.isBuffering$.subscribe(new J("isBuffering"))].forEach(i=>this.subscription.add(i)),Gt("codecs",Rn())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||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:Vr.DOM,message:String(r)})})};this.subscription.add(ze(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!=null&&e.released);r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);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 DA,Observable as CA,Subject as VA,ValueSubject as BA,VideoQuality as OA}from"@vkontakte/videoplayer-shared";var _A=`@vkontakte/videoplayer-core@${Is}`;export{Wi as ChromecastState,Jr as HttpConnectionType,CA as Observable,te as PlaybackState,Or as Player,_A as SDK_VERSION,VA as Subject,DA as Subscription,Xr as Surface,Is as VERSION,BA as ValueSubject,Ne as VideoFormat,OA as VideoQuality};
|
|
91
|
+
`;var Tr=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 vr(this.params.fov,this.params.orientation),this.cameraRotationManager=new yr(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(yo,this.gl.VERTEX_SHADER),i=this.createShader(To,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,n=e+i,u=t-r,d=e+i,l=t+r,c=e-i,p=t+r;return[a,s,n,u,d,l,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var ft=class{constructor(e){this.subscription=new Kl;this.videoState=new L("stopped");this.elementSize$=new Jl(void 0);this.textTracksManager=new me;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 zi;this.textTracks=[];this.syncPlayback=()=>{var s,n,u;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==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let d=(n=(s=this.liveOffset)==null?void 0:s.getTotalPausedTime())!=null?n:0;this.seek(r.position-d,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"),v(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&v(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),Math.floor(this.video.duration)===Math.floor(this.video.currentTime)?this.videoState.setState("paused"):this.video.pause(),this.video.pause()):(i==null?void 0:i.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return Hl(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Tr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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=re(e.container,e.tuning),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(z(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new gr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=ne(this.video),r=this.constructor.name,a=n=>{e.error$.next({id:r,category:Oa.WTF,message:`${r} internal logic error`,thrown:n})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(n,u)=>this.subscription.add(n.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Io(d=>!!d.length),Ao()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})})),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(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(Io(jl),Ao()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(xo(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ae(this.video,t.isLooped,r)),this.subscription.add(se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(he(this.video,t.playbackRate,i.playbackRateState$,r)),a(zl(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"),v(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams();if(Gl(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(Pa(h));let m=[];for(let f of h.representations){let b=so(f);m.push(b),this.audioTracksMap.set(b,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of l.video){c.push(ka(p));let h=[];for(let m of p.representations){let f=ao(m);f&&(h.push(f),this.videoTracksMap.set(f,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(c);for(let p of l.text)for(let h of p.representations){let m=no(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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:Oa.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(Ir(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$,Ql(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(d)||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,h]=c,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),d==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0: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:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(_a()).subscribe(d=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:p}]=l,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(ka(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(_a()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[c,{stream:p}]=l,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Pa(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.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 n=t.playbackState.stateChangeStarted$.pipe(xo(({to:d})=>d==="ready"),_a());this.subscription.add(Ir(n,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(Ir(n,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Ir(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ql(["init"])).pipe(Wl(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var R,P,N,w,$,A,F,Y,k,y,B,U,G,j;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(R=e.videoTrack.getState())==null?void 0:R.id,s=[...this.videoTracksMap.keys()].find(({id:O})=>O===r),n=t.currentVideoTrack$.getValue(),u=((w=(N=e.videoStream.getState())!=null?N:s&&((P=this.videoTracksMap.get(s))==null?void 0:P.stream))!=null?w:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let d=[...this.videoStreamsMap.keys()].find(({id:O})=>O===u.id),l=d&&this.videoStreamsMap.get(d);if(!l)return;let c=Me(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=($=e.audioStream.getState())!=null?$:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,f=(A=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(m==null?void 0:m.id)))!=null?A:this.audioStreamsMap.keys().next().value,b=0;if(f){if(s&&!i){let O=lr(s,l,(F=this.audioStreamsMap.get(f))!=null?F:[]);b=Math.max(b,(Y=O==null?void 0:O.bitrate)!=null?Y:-1/0)}if(n){let O=lr(n,l,(k=this.audioStreamsMap.get(f))!=null?k:[]);b=Math.max(b,(y=O==null?void 0:O.bitrate)!=null?y:-1/0)}}let E=Qe(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:h,current:n,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:x}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&i&&(E=(B=l.filter(O=>!Yl(O.quality)).sort((O,bt)=>{var Ve,C;return((Ve=bt.bitrate)!=null?Ve:0)-((C=O.bitrate)!=null?C:0)}).filter(O=>Eo(O.quality,E.quality)&&Eo(O.quality,x))[0])!=null?B:E);let T=i?E!=null?E:s:s!=null?s:E,S=f&&lr(T,l,(U=this.audioStreamsMap.get(f))!=null?U:[]),g=(G=this.videoTracksMap.get(T))==null?void 0:G.representation,D=S&&((j=this.audioTracksMap.get(S))==null?void 0:j.representation);if(g&&D)return[g,D];if(g&&!D&&this.audioTracksMap.size===0)return[g,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){oe(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Oa.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),ae(this.video)}};var Ai=class extends ft{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 Po,interval as Xl,map as Zl}from"@vkontakte/videoplayer-shared";var Pi=class extends ft{constructor(e){super(e),this.liveOffset=new $e}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(Po({interval:Xl(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(r-1);s<=0&&e.position$.next(s),(a=this.liveOffset)==null||a.resetTo(-s*1e3)}})).add(Po({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Zl(({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(()=>{var n;this.params.output.position$.next(e/1e3),(n=this.liveOffset)==null||n.resetTo(s,r)})}};import{assertNever as ki,assertNonNullable as ko,debounce as ec,ErrorCategory as Er,filter as tc,isNonNullable as ic,isNullable as rc,map as xr,merge as ac,Observable as sc,observableFrom as nc,Subscription as oc,videoSizeToQuality as uc}from"@vkontakte/videoplayer-shared";var Ee={};var Dt=(o,e)=>new sc(t=>{let i=(r,a)=>t.next(a);return o.on(e,i),()=>o.off(e,i)}),wi=class{constructor(e){this.subscription=new oc;this.videoState=new L("initializing");this.textTracksManager=new me;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==null?void 0: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:ki(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ki(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ki(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ki(e)}break;default:ki(t)}};this.video=re(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(z(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ae(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Er.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||(Ee.Hls=r.default,Ee.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){ko(Ee.Hls,"hls.js not loaded"),this.hls=new Ee.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){ko(Ee.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:Er.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ne(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.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(Ae(this.video,e.isLooped,i)),this.subscription.add(se(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(he(this.video,e.playbackRate,r.playbackRateState$,i)),a(be(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(xr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(Dt(this.hls,Ee.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:Er.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)==null?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())==null?void 0:d.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Dt(this.hls,Ee.Events.MANIFEST_PARSED).pipe(xr(({levels:d})=>d.reduce((l,c)=>{var x,T;let p=c.name||c.height.toString(10),{width:h,height:m}=c,f=(T=Ge((x=c.attrs.QUALITY)!=null?x:""))!=null?T:uc({width:h,height:m});if(!f)return l;let b=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,E={id:p.toString(),quality:f,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:b};return this.trackLevels.set(p,{track:E,level:c}),l.push(E),l},[]))),t.availableVideoTracks$),a(Dt(this.hls,Ee.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let l=[];for(let c of d.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang,f="internal";l.push({id:p,url:h,language:m,type:f})}e.internalTextTracks.startTransitionTo(l)}}),a(Dt(this.hls,Ee.Events.LEVEL_LOADING).pipe(xr(({url:d})=>z(d))),t.hostname$),a(Dt(this.hls,Ee.Events.FRAG_CHANGED),d=>{var p,h,m,f;let{video:l,audio:c}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=c==null?void 0:c.endPTS)!=null?m:0)-((f=c==null?void 0:c.startPTS)!=null?f:0))*1e3)}),this.subscription.add(Fe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))==null?void 0:l.track},n=Dt(this.hls,Ee.Events.LEVEL_SWITCHED).pipe(xr(({level:d})=>s(this.hls.levels[d])));n.pipe(tc(ic)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Fe(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{var m;if(rc(d))return;let l=(m=this.trackLevels.get(d.id))==null?void 0:m.level;if(!l)return;let c=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:n,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=ac(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nc(["init"])).pipe(ec(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await oe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Er.DOM,thrown:t}))||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),Math.floor(this.video.duration)===Math.floor(this.video.currentTime)?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0)}};var wo="X-Playback-Duration",Na=async o=>{var r;let e=await fetch(o),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(wo)?parseInt(e.headers.get(wo),10):void 0};import{assertNever as mc,combine as fc,debounce as bc,ErrorCategory as Pr,filter as Sc,filterChanged as gc,isNonNullable as Lo,isNullable as kr,map as Mo,merge as vc,observableFrom as yc,Subscription as Tc,ValueSubject as Ua,VideoQuality as Ic}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as dc,getExponentialDelay as lc}from"@vkontakte/videoplayer-shared";var cc=o=>{let e=null;if(o.QUALITY&&(e=Ge(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=dc({width:t,height:i})}return e!=null?e:null},pc=(o,e)=>{var a,s;let t=o.split(`
|
|
92
|
+
`),i=[],r=[];for(let n=0;n<t.length;n++){let u=t[n],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!l)){if(d){let c=Object.fromEntries(d[1].split(",").map(x=>x.split("="))),p=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,h=cc(c),m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let f=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,b;if(c.RESOLUTION){let[x,T]=c.RESOLUTION.split("x").map(S=>parseInt(S,10));x&&T&&(b={width:x,height:T})}let E=new URL(t[++n],e).toString();h&&i.push({id:p,quality:h,url:E,bandwidth:m,size:b,fps:f})}if(l){let c=Object.fromEntries(l[1].split(",").map(f=>f.split("=")).map(([f,b])=>[f,b.replace(/^"|"$/g,"")])),p=(s=c.URI)==null?void 0:s.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,m=c.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},hc=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),Fa=0,$o=async(o,e=o,t)=>{let r=await(await fetch(o)).text();Fa+=1;try{let{qualityManifests:a,textTracks:s}=pc(r,e);return{qualityManifests:a,textTracks:s}}catch(a){if(Fa<=t.manifestRetryMaxCount)return await hc(lc(Fa-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),$o(o,e,t)}return{qualityManifests:[],textTracks:[]}},Ar=$o;var $i=class{constructor(e){this.subscription=new Tc;this.videoState=new L("stopped");this.textTracksManager=new me;this.manifests$=new Ua([]);this.liveOffset=new $e;this.manifestStartTime$=new Ua(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(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||n){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),Math.floor(this.video.duration)===Math.floor(this.video.currentTime)?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(v(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return mc(t)}};var t;this.params=e,this.video=re(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ic.INVARIANT,url:this.params.source.url},Ar(J(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Pr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Pr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(z(this.params.source.url)),this.maxSeekBackTime$=new Ua((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let n=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:Pr.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=ne(this.video),a=(n,u)=>this.subscription.add(n.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.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(se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(he(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"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(gc(),Mo(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Lo(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(z(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,d,l;let n=(l=(d=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:d.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(fc({startTime:this.manifestStartTime$.pipe(Sc(Lo)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:u})=>this.params.output.liveTime$.next(n+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Mo(n=>n.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=vc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,yc(["init"])).pipe(bc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ae(this.video)}prepare(){var n,u;let e=this.selectManifest();if(kr(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:d,min:l}=(u=(n=t==null?void 0:t.to)!=null?n:i)!=null?u:{};for(let[c,p]of[[d,"mq"],[l,"lq"]]){let h=String(parseFloat(c||""));p&&c&&r.searchParams.set(p,h)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=J(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),Na(s).then(d=>{var l;if(!kr(d))this.maxSeekBackTime$.next(d);else{let c=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(kr(c)||!isFinite(c))try{fetch(s).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let f=new URL(h,s).toString();Na(f).then(b=>{kr(b)||this.maxSeekBackTime$.next(b)})}})}catch(p){}}})}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pr.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 Ec,debounce as xc,ErrorCategory as Ha,fromEvent as Ga,isNonNullable as Ac,isNullable as Pc,map as Ro,merge as Do,observableFrom as Co,Subscription as kc,ValueSubject as wc,VideoQuality as $c,isIOS as Lc}from"@vkontakte/videoplayer-shared";var Li=class{constructor(e){this.subscription=new kc;this.videoState=new L("stopped");this.textTracksManager=new me;this.manifests$=new wc([]);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(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||n){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:c}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?v(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),Math.floor(this.video.duration)===Math.floor(this.video.currentTime)?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&v(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Ec(t)}};this.params=e,this.video=re(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$c.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(z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ar(J(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ha.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let n=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:Ha.WTF,message:"HlsProvider internal logic error",thrown:n})},r=ne(this.video),a=(n,u)=>this.subscription.add(n.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.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(Ro(n=>n.to)),this.params.output.playbackState$),this.subscription.add(Ae(this.video,t.isLooped,i)),this.subscription.add(se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(he(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var c;let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Ac(d.to)){let p=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(z(h.url));let m=this.params.desiredState.playbackRate.getState(),f=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(m!==f){let b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(m),b.playbackRate=m)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n.state==="requested"&&this.seek(n.position)},i))),this.subscription.add(this.manifests$.pipe(Ro(n=>n.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Lc()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(Do(Ga(n,"addtrack"),Ga(n,"removetrack"),Ga(n,"change"),Co(["init"])).subscribe(()=>{for(let u=0;u<n.length;u++)n[u].mode="hidden"},i))}let s=Do(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Co(["init"])).pipe(xc(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ae(this.video)}prepare(){var a,s;let e=this.selectManifest();if(Pc(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:n,min:u}=(s=(a=t==null?void 0:t.to)!=null?a:i)!=null?s:{};for(let[d,l]of[[n,"mq"],[u,"lq"]]){let c=String(parseFloat(d||""));l&&d&&r.searchParams.set(l,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ha.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Mc,assertNonNullable as Vo,debounce as Rc,ErrorCategory as Bo,isHigher as Dc,isHigherOrEqual as Cc,isInvariantQuality as Oo,isLowerOrEqual as Vc,isNonNullable as Bc,merge as Oc,observableFrom as _c,Subscription as Nc,map as Fc}from"@vkontakte/videoplayer-shared";var Mi=class{constructor(e){this.subscription=new Nc;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new me;this.syncPlayback=()=>{var u,d,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=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:c}=this.video;this.prepare(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),s.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(d=this.trackUrls[s.to.id])==null?void 0:d.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?v(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),Math.floor(this.video.duration)===Math.floor(this.video.currentTime)?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return Mc(e)}};this.params=e,this.video=re(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=n=>{e.error$.next({id:"MpegProvider",category:Bo.WTF,message:"MpegProvider internal logic error",thrown:n})},r=ne(this.video),a=(n,u)=>this.subscription.add(n.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.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(Fc(n=>n.to)),this.params.output.playbackState$),this.subscription.add(Ae(this.video,t.isLooped,i)),this.subscription.add(se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(he(this.video,t.playbackRate,r.playbackRateState$,i)),a(be(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),v(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),v(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,d;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let n=this.params.desiredState.videoTrack.getTransition();if(n&&Bc(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let l=this.params.desiredState.playbackRate.getState(),c=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(l!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Oc(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,_c(["init"])).pipe(Rc(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),ae(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Vo(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Vo(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ti(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(z(t))}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,a,s,n;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(a=Object.values(this.trackUrls).find(c=>!Oo(c.track.quality)&&Vc(c.track.quality,e)))==null?void 0:a.track,d=(s=this.params.desiredState.videoTrack.getState())==null?void 0:s.id,l=(n=this.trackUrls[d!=null?d:"0"])==null?void 0:n.track;if(u&&l&&Cc(l.quality,u.quality)&&(t=u),!t){let c=Object.values(this.trackUrls).filter(h=>!Oo(h.track.quality)&&Dc(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(d=>d.track);t=Qe(u,{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 No,debounce as Wc,merge as Fo,observableFrom as Qc,Subscription as jc,map as Uo,ValueSubject as Yc,ErrorCategory as Qa,VideoQuality as qc}from"@vkontakte/videoplayer-shared";import{ErrorCategory as Uc}from"@vkontakte/videoplayer-shared";var _o=["stun:videostun.mycdn.me:80"],Hc=1e3,Gc=3,Wa=()=>null,wr=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Wa;this.externalStopCallback=Wa;this.externalErrorCallback=Wa;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:_o}]};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:Uc.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(t){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),Hc)}normalizeOptions(e={}){let t={stunServerList:_o,maxRetryNumber:Gc,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ri=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new Yc(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),v(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),Math.floor(this.video.duration)===Math.floor(this.video.currentTime)?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&v(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&v(this.params.desiredState.playbackState,"paused");return;default:return No(e)}};this.subscription=new jc,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=re(e.container,e.tuning),this.liveStreamClient=new wr(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ae(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:Qa.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};Fo(this.videoState.stateChangeStarted$.pipe(Uo(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Uo(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})});let r=ne(this.video),a=(s,n)=>this.subscription.add(s.subscribe(n,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(()=>{var s;((s=this.videoState.getTransition())==null?void 0:s.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(se(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return No(s.to)}},i)).add(Fo(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Qc(["init"])).pipe(Wc(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(z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:qc.INVARIANT}),this.video.srcObject=e,v(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Qa.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){oe(this.video).then(e=>{e||(this.videoState.setState("paused"),v(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qa.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Di=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 Bi,assertNonNullable as qe,ErrorCategory as Lr,filter as ip,isNonNullable as Yo,isNullable as rp,map as ap,merge as sp,once as np,Subject as ge,Subscription as qo,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{Observable as zc,map as Ho,Subscription as Kc,Subject as Jc}from"@vkontakte/videoplayer-shared";var Go=o=>new zc(e=>{let t=new Kc,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Ho(({from:d,to:l})=>`${d}-${l}`)),r=o.desiredPlaybackState$.stateChangeEnded$,a=o.providerChanged$.pipe(Ho(({type:d})=>d!==void 0)),s=new Jc,n=0,u="unknown";return t.add(i.subscribe(d=>{n&&window.clearTimeout(n),u=d,n=window.setTimeout(()=>s.next(d),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(n),u="unknown",n=0})),t.add(a.subscribe(d=>{n&&(window.clearTimeout(n),n=0,d&&(n=window.setTimeout(()=>s.next(u),o.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as Wo,Subscription as Xc,combine as Zc,filter as Qo,once as jo}from"@vkontakte/videoplayer-shared";var Ci=null,$r=null;function ja(){return Ci||(Ci=new(window.AudioContext||window.webkitAudioContext)),$r||($r=new GainNode(Ci,{gain:1}),$r.connect(Ci.destination)),{audioCtx:Ci,gainNode:$r}}import{getCurrentBrowser as ep,CurrentClientBrowser as tp}from"@vkontakte/videoplayer-shared";var Ct=class Ct{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Xc;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(Qo(s=>!!s.type),jo()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){let{browser:t}=ep();t===tp.Safari&&e!=="MPEG"||this.subscriptions.add(Zc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Qo(({playbackState:i,video:r,volume:{muted:a,volume:s}})=>i==="playing"&&!!r&&!a&&!!s),jo()).subscribe(({video:i})=>this.initAudioContextOnce(i)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=ja(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{var s;if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Ct.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(n){this.volumeMultiplierError$.next({id:Ct.errorId,category:Wo.VIDEO_PIPELINE,message:(s=n==null?void 0:n.message)!=null?s:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:n})}}).catch(s=>{var n;this.volumeMultiplierError$.next({id:Ct.errorId,category:Wo.VIDEO_PIPELINE,message:(n=s==null?void 0:s.message)!=null?n:"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=ja();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Ct.errorId="VolumeMultiplierManager";var Vi=Ct;var op={chunkDuration:5e3,maxParallelRequests:5},Oi=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ge;this.noAvailableProvidersError$=new ge;this.volumeMultiplierError$=new ge;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ge,warning$:new ge,willSeekEvent$:new ge,seekedEvent$:new ge,loopedEvent$:new ge,endedEvent$:new ge,firstBytesEvent$:new ge,firstFrameEvent$:new ge,canplay$:new ge,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new qo;var n;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Dn([...Vn(this.params.tuning),...Cn(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>Yo(e.sources[u])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(u=>!r.includes(u)),...t.filter(u=>r.includes(u))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Di(a);let s=[...va(!0),...va(!1)];this.chromecastFormatsIterator=new Di(s.filter(u=>Yo(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Vi(this.providerOutput,this.current$,this.volumeMultiplierError$,(n=this.params.volumeMultiplier)!=null?n: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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(rp(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Lr.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.destroyProvider(),this.initProvider()}switchToNextProvider(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"});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}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Bi(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 n=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qe(n),new Ai({...s,source:n,sourceHls:u})}case"DASH_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return qe(n),new Pi({...s,source:n})}case"HLS":case"HLS_ONDEMAND":{let n=this.applyFailoverHost(t[e]);return qe(n),Pt||!this.params.tuning.useHlsJs?new Li({...s,source:n}):new wi({...s,source:n})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return qe(n),new $i({...s,source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let n=this.applyFailoverHost(t[e]);return qe(n),new Mi({...s,source:n})}case"DASH_LIVE":{let n=this.applyFailoverHost(t[e]);return qe(n),new fn({...s,source:n,config:{...op,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let n=this.applyFailoverHost(t[e]);return qe(n),new Ri({container:i,source:n,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 Bi(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return qe(n),new Ft({connection:n,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 Bi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Bi(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 Bi(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 qo,t=!1,i=0;return e.add(sp(this.providerOutput.error$,Go({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(ap(r=>({id:`ProviderHangup:${r}`,category:Lr.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(ip(({to:a})=>a==="playing"),np()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let s=r.category===Lr.NETWORK,n=r.category===Lr.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!n;u&&!n&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:"SCREEN")}})),e}};import{fromEvent as Mr,once as up,combine as dp,Subscription as zo,ValueSubject as Ya,map as lp,filter as cp,isNonNullable as Rr,now as ce,safeStorage as qa}from"@vkontakte/videoplayer-shared";var pp=5e3,Ko="one_video_throughput",Jo="one_video_rtt",De=window.navigator.connection,Xo=()=>{let o=De==null?void 0:De.downlink;if(Rr(o)&&o!==10)return o*1e3},Zo=()=>{let o=De==null?void 0:De.rtt;if(Rr(o)&&o!==3e3)return o},eu=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},za=class o{constructor(e){this.subscription=new zo;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=o.load(Ko)||(e.useBrowserEstimation?Xo():void 0)||pp,i=(a=(r=o.load(Jo))!=null?r:e.useBrowserEstimation?Zo():void 0)!=null?a:0;if(this.throughput$=new Ya(t),this.rtt$=new Ya(i),this.rttAdjustedThroughput$=new Ya(eu(t,i,e.rttPenaltyRequestSize)),this.throughput=ht.getSmoothedValue(t,-1,e),this.rtt=ht.getSmoothedValue(i,1,e),e.useBrowserEstimation){let s=()=>{let u=Xo();u&&this.throughput.next(u);let d=Zo();Rr(d)&&this.rtt.next(d)};De&&"onchange"in De&&this.subscription.add(Mr(De,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{qa.set(Ko,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{qa.set(Jo,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dp({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(lp(({throughput:s,rtt:n})=>eu(s,n,e.rttPenaltyRequestSize)),cp(s=>{let n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ce(),r=new zo;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Mr(e,"progress").pipe(up()).subscribe(a=>{t=a.loaded,i=ce()}));break;case 1:case 0:r.add(Mr(e,"loadstart").subscribe(()=>{t=0,i=ce()}));break}r.add(Mr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,n=ce(),u=s-t,d=n-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=ce(),s=0,n=ce(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,ce()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=ce();if(p-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=n-a;m&&this.addRawSpeed(s,m,1,t),s=c.byteLength,a=ce()}else s+=c.byteLength;n=ce()}else r+=c.byteLength,s+=c.byteLength,s>=this.tuningConfig.streamMinSampleSize&&ce()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,ce()-n,this.concurrentDownloads.size),s=0,n=ce());await(i==null?void 0:i.read().then(d,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(o.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){var i;let t=qa.get(e);if(Rr(t))return(i=parseInt(t,10))!=null?i:void 0}},tu=za;import{fillWithDefault as hp,VideoQuality as iu}from"@vkontakte/videoplayer-shared";var ru={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,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:iu.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:iu.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,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!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},au=o=>{var e;return{...hp(o,ru),configName:[...(e=o.configName)!=null?e:[],...ru.configName]}};import{assertNonNullable as Dr,combine as Cr,ErrorCategory as Vr,filter as _i,filterChanged as ve,fromEvent as Ja,isNonNullable as yp,isNullable as Tp,Logger as Ip,map as V,mapTo as uu,merge as ze,now as Br,once as Ce,Subject as H,Subscription as du,tap as lu,ValueSubject as I,isHigher as Ep,isInvariantQuality as cu}from"@vkontakte/videoplayer-shared";import{merge as mp,map as fp,filter as su,isNonNullable as bp}from"@vkontakte/videoplayer-shared";var Ka=({seekState:o,position$:e})=>mp(o.stateChangeEnded$.pipe(fp(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),su(bp)),e.pipe(su(()=>o.getState().state==="none")));import{assertNonNullable as Sp}from"@vkontakte/videoplayer-shared";var nu=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return Sp(e,`Wrong container or containerId {${o.container}}`),e};import{filter as gp,once as vp}from"@vkontakte/videoplayer-shared";var ou=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(gp(r=>r.length>0),vp()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(o)};var Or=class{constructor(e={configName:[]}){this.subscription=new du;this.logger=new Ip;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new I(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new I("stopped"),position$:new I(0),duration$:new I(1/0),muted$:new I(!1),volume$:new I(1),availableVideoStreams$:new I([]),currentVideoStream$:new I(void 0),availableQualities$:new I([]),availableQualitiesFps$:new I({}),currentQuality$:new I(void 0),isAutoQualityEnabled$:new I(!0),autoQualityLimitingAvailable$:new I(!1),autoQualityLimits$:new I({}),availableAudioStreams$:new I([]),currentAudioStream$:new I(void 0),availableAudioTracks$:new I([]),isAudioAvailable$:new I(!0),currentPlaybackRate$:new I(1),currentBuffer$:new I({start:0,end:0}),isBuffering$:new I(!0),isStalled$:new I(!1),isEnded$:new I(!1),isLooped$:new I(!1),isLive$:new I(void 0),canChangePlaybackSpeed$:new I(void 0),atLiveEdge$:new I(void 0),atLiveDurationEdge$:new I(void 0),liveTime$:new I(void 0),liveBufferTime$:new I(void 0),currentFormat$:new I(void 0),availableTextTracks$:new I([]),currentTextTrack$:new I(void 0),throughputEstimation$:new I(void 0),rttEstimation$:new I(void 0),videoBitrate$:new I(void 0),hostname$:new I(void 0),httpConnectionType$:new I(void 0),httpConnectionReused$:new I(void 0),surface$:new I("none"),chromecastState$:new I("NOT_AVAILABLE"),chromecastDeviceName$:new I(void 0),intrinsicVideoSize$:new I(void 0),availableSources$:new I(void 0),is3DVideo$:new I(!1),currentVideoSegmentLength$:new I(0),currentAudioSegmentLength$:new I(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,firstBytes$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new I(void 0),tuningConfigName$:new I([]),enableDebugTelemetry$:new I(!1),dumpTelemetry:en};if(this.initLogs(),this.tuning=au(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ji({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new tu(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...s)=>{try{return a.apply(t,s)}catch(n){let u=s.map(c=>JSON.stringify(c,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Vr.WTF,message:l,thrown:n}),n}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=nu(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Oi({sources:e.sources,meta:(i=e.meta)!=null?i:{},failoverHosts:(r=e.failoverHosts)!=null?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!qt()?Ja(document,"visibilitychange").pipe(Ce()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.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){Dr(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(_i(i=>i.length>0),Ce()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;Dr(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return ou(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(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(Tp(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return yp(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.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(ze(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(V(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(_i(({from:e})=>e==="stopped"),Ce()).subscribe(()=>{this.initedAt=Br(),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();s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Vr.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(V(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(V(s=>s.destination),ve()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(V(s=>s.map(({quality:n})=>n).sort((n,u)=>cu(n)?1:cu(u)?-1:Ep(u,n)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let n={};for(let u of s)u.fps&&(n[u.quality]=u.fps);this.info.availableQualitiesFps$.next(n)})).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$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s==null?void 0:s.quality),this.info.videoBitrate$.next(s==null?void 0:s.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ve()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ve()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ve()).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!=null?s:{})})).add(e.providerOutput.currentBuffer$.pipe(V(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Cr({hasLiveOffsetByPaused:ze(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(V(s=>s.to),ve(),V(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:n})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(n));return}this.hasLiveOffsetByPaused.next(!1)})).add(Cr({atLiveEdge:Cr({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ka({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(V(({isLive:s,position:n,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(n)<d/1e3}),ve(),lu(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(V(({atLiveEdge:s,hasPausedTimeoutCase:n})=>s&&!n)).subscribe(this.info.atLiveEdge$)).add(Cr({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(V(({isLive:s,position:n,duration:u})=>s&&(Math.abs(u)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),ve(),lu(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(V(s=>s.muted),ve()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(V(s=>s.volume),ve()).subscribe(this.info.volume$)).add(Ka({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ze(e.providerOutput.endedEvent$.pipe(uu(!0)),e.providerOutput.seekedEvent$.pipe(uu(!1))).pipe(ve()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(V(s=>({id:s?`No${s}`:"NoProviders",category:Vr.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Ce(),V(s=>s!=null?s:Br()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ce(),V(()=>Br()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ce(),V(()=>Br()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new I(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new I(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(_i(({to:s})=>s==="playing"),Ce()).subscribe(()=>i.next(!1)));let r=0,a=ze(e.providerOutput.isBuffering$,t,i).pipe(V(()=>{let s=e.providerOutput.isBuffering$.getValue(),n=t.getValue()||i.getValue();return s&&!n}),ve());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(ze(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s==null?void 0:s.videoWidth,height:s==null?void 0:s.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{var u,d;let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=s==null?void 0:s.size)==null?void 0:u.width,height:(d=s==null?void 0:s.size)==null?void 0:d.height},{width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ze(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),c;l==="CONNECTED"?c="second_screen":u?d?s?c="pip":n?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(V(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new du;this.subscription.add(t),this.subscription.add(e.current$.pipe(ve((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(_i(i=>i.length>0),Ce()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Qe(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(ze(this.desiredState.videoTrack.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(V(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(V(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(V(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Dr(this.providerContainer),Dr(e),Zs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Xs(i)),this.providerContainer.current$.subscribe(({type:i})=>Gt("provider",i)),e.duration$.subscribe(i=>Gt("duration",i)),e.availableVideoTracks$.pipe(_i(i=>!!i.length),Ce()).subscribe(i=>Gt("tracks",i)),this.events.fatalError$.subscribe(new X("fatalError")),this.events.managedError$.subscribe(new X("managedError")),e.position$.subscribe(new X("position")),e.currentVideoTrack$.pipe(V(i=>i==null?void 0:i.quality)).subscribe(new X("quality")),this.info.currentBuffer$.subscribe(new X("buffer")),e.isBuffering$.subscribe(new X("isBuffering"))].forEach(i=>this.subscription.add(i)),Gt("codecs",Rn())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||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:Vr.DOM,message:String(r)})})};this.subscription.add(ze(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!=null&&e.released);r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);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 DA,Observable as CA,Subject as VA,ValueSubject as BA,VideoQuality as OA}from"@vkontakte/videoplayer-shared";var _A=`@vkontakte/videoplayer-core@${Is}`;export{Wi as ChromecastState,Jr as HttpConnectionType,CA as Observable,ie as PlaybackState,Or as Player,_A as SDK_VERSION,VA as Subject,DA as Subscription,Xr as Surface,Is as VERSION,BA as ValueSubject,Ne as VideoFormat,OA as VideoQuality};
|