@vkontakte/videoplayer-core 2.0.108-dev.43b53ca1.0 → 2.0.108-dev.9b636631.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/evergreen.esm.js CHANGED
@@ -1,18 +1,15 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.108-dev.43b53ca1.0
3
- * Thu, 29 Aug 2024 16:46:43 GMT
2
+ * @vkontakte/videoplayer-core v2.0.108-dev.9b636631.0
3
+ * Fri, 30 Aug 2024 14:05:43 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-108/doc/
5
5
  */
6
- var Ba="2.0.108-dev.43b53ca1.0";var K=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(K||{}),Ce=(g=>(g.MPEG="MPEG",g.DASH="DASH",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_STREAMS="DASH_STREAMS",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(Ce||{});var Vi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Vi||{}),Rr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Rr||{});var Dr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Dr||{});import{assertNever as Ha,assertNonNullable as ko,isNonNullable as Bi,ValueSubject as Cr,Subject as Ao,Subscription as Po,merge as wo,observableFrom as $o,fromEvent as Na,map as _a,tap as Fa,filterChanged as Lo,isNullable as Vr,ErrorCategory as Ua}from"@vkontakte/videoplayer-shared";var Oa=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Oi=class{constructor(e){this.connection$=new Cr(void 0);this.castState$=new Cr("NOT_AVAILABLE");this.errorEvent$=new Ao;this.realCastState$=new Cr("NOT_AVAILABLE");this.subscription=new Po;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=Bi(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||Oa("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ua.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Bi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Vr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Vr(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(Na(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Ha(r.sessionState)}})).add(wo(Na(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Fa(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_a(r=>r.castState)),$o([i.getCastState()])).pipe(Lo(),_a(Mo),Fa(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=Bi(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();ko(o);let u=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(Vr(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Bi(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Ua.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Mo=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Ha(n)}};import{assertNever as Ga}from"@vkontakte/videoplayer-shared";var W=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Ga(t)}return n},Br=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:Ga(e)}};var y=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as Ro,Subject as Ni,merge as Qa}from"@vkontakte/videoplayer-shared";var P=class{constructor(e){this.transitionStarted$=new Ni;this.transitionEnded$=new Ni;this.transitionUpdated$=new Ni;this.forceChanged$=new Ni;this.stateChangeStarted$=Qa(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Qa(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||Ro(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 Do}from"@vkontakte/videoplayer-shared";var ja=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Do(n)}};import{assertNever as mt,assertNonNullable as ze,debounce as Wa,ErrorCategory as Ya,fromEvent as Ke,isNonNullable as qa,map as za,merge as Ka,observableFrom as Co,Subject as Vo,Subscription as Or,timeout as Bo,getHighestQuality as Oo}from"@vkontakte/videoplayer-shared";var No=5,_o=5,Fo=500,Ja=7e3,$t=class{constructor(e){this.subscription=new Or;this.loadMediaTimeoutSubscription=new Or;this.videoState=new P("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:mt(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:mt(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:mt(e)}break}default:mt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ja(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 Or;this.subscription.add(e),this.subscription.add(Ka(this.videoState.stateChangeStarted$.pipe(za(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(za(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 Vo;e.add(r.pipe(Wa(Fo)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>No)&&r.next(o),a=o})),e.add(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<_o&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),y(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:mt(s)}}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Ka(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Co(["init"])).pipe(Wa(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&y(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];ze(d);let c=Oo(Object.keys(d));ze(c);let l=d[c];ze(l),i=l,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];ze(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];ze(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];ze(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];ze(d),i=W(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ya.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return mt(e)}let s=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return qa(o)&&(s.metadata.title=o),qa(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(Bo(Ja).subscribe(()=>a(`timeout(${Ja})`)))});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:Ya.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Za}from"@vkontakte/videoplayer-shared";import{clearVideoElement as Uo}from"@vkontakte/videoplayer-shared";var Xa=n=>{try{n.pause(),n.playbackRate=0,Uo(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Ho,Subscription as Go}from"@vkontakte/videoplayer-shared";var Nr=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)}},_r=window.WeakMap?new WeakMap:new Nr,Fr=window.WeakMap?new WeakMap:new Map,Qo=(n,e=20)=>{let t=0;return Ho(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},J=(n,{audioVideoSyncRate:e})=>{let t=n.querySelector("video"),i=!!t;t?Za(t):(t=document.createElement("video"),n.appendChild(t)),_r.set(t,i);let r=new Go;return r.add(Qo(t,e)),Fr.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},X=n=>{Fr.get(n)?.unsubscribe(),Fr.delete(n);let t=_r.get(n);_r.delete(n),t?Za(n):Xa(n)};import{assertNonNullable as Lt,isNonNullable as Ee,isNullable as Yo,fromEvent as ft,merge as es,observableFrom as ts,filterChanged as is,map as Mt,Subject as rs,Subscription as qo,ValueSubject as zo,ErrorCategory as Ko}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ur,isNullable as jo,Subscription as Wo}from"@vkontakte/videoplayer-shared";var _i=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=jo(r),d=new Wo;return r&&d.add(r.subscribe(c=>{let l=n.getState();i(c,l)&&n.setState(c)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),u&&n.setState(c.to)},a)),d},Ie=(n,e,t)=>_i(e,()=>n.loop,i=>{Ur(i)&&(n.loop=i)},{onError:t}),Z=(n,e,t,i)=>_i(e,()=>({muted:n.muted,volume:n.volume}),r=>{Ur(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),ue=(n,e,t,i)=>_i(e,()=>n.playbackRate,r=>{Ur(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Ve=_i;var Jo=n=>["__",n.language,n.label].join("|"),Xo=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Hr=class n{constructor(){this.available$=new rs;this.current$=new zo(void 0);this.error$=new rs;this.subscription=new qo;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:Ko.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(Ve(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ee(a)&&this.setInternal(a)},{equal:(a,s)=>Ee(a)&&Ee(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Mt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Ve(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ee(a)&&this.setExternal(a)},{equal:(a,s)=>Ee(a)&&Ee(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Mt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Ve(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(Ve(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Lt(this.video);let{textTracks:e}=this.video;this.subscription.add(ft(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(es(ft(e,"addtrack"),ft(e,"removetrack"),ts(["init"])).pipe(Mt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),is((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(es(ft(e,"change"),ts(["init"])).pipe(Mt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Mt(i=>i&&this.htmlTextTrackToITextTrack(i).id),is()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ft(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ft(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Ee(t.align)&&(r.align=t.align),Ee(t.position)&&(r.position=t.position),Ee(t.size)&&(r.size=t.size),Ee(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Lt(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Jo(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Lt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Yo(e)||!Xo(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){Lt(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){Lt(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)}},le=Hr;var Ae=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 as=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Gr=n=>{let e=as(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},ss=n=>{let e=as(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as ce,map as Be,merge as os,filterChanged as ed,isNonNullable as ds,Subject as td,filter as us,mapTo as ls,combine as id,once as rd,ErrorCategory as ad,ValueSubject as cs,clientChecker as sd}from"@vkontakte/videoplayer-shared";var Zo=3,ns=(n,e,t=Zo)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var ee=n=>{let e=g=>ce(n,g).pipe(ls(void 0)),i=os(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>ce(n,g))).pipe(Be(g=>g.type==="ended"?n.readyState<2:n.readyState<3),ed()),r=os(ce(n,"progress"),ce(n,"timeupdate")).pipe(Be(()=>ns(n.buffered,n.currentTime))),a=sd.isSafari?id({play:e("play").pipe(rd()),playing:e("playing")}).pipe(ls(void 0)):e("playing"),s=ce(n,"volumechange").pipe(Be(()=>({muted:n.muted,volume:n.volume}))),o=ce(n,"ratechange").pipe(Be(()=>n.playbackRate)),u=ce(n,"error").pipe(us(()=>!!(n.error||n.played.length)),Be(()=>{let g=n.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:ad.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:n.error??void 0}})),d=ce(n,"timeupdate").pipe(Be(()=>n.currentTime)),c=new td,l=.3,p;d.subscribe(g=>{n.loop&&ds(p)&&ds(g)&&p>=n.duration-l&&g<=l&&c.next(p),p=g});let h=e("pause").pipe(us(()=>!n.error&&p!==n.duration)),m=ce(n,"enterpictureinpicture"),f=ce(n,"leavepictureinpicture"),S=new cs(ss(n));m.subscribe(()=>S.next(!0)),f.subscribe(()=>S.next(!1));let k=new cs(Gr(n));return ce(n,"fullscreenchange").pipe(Be(()=>Gr(n))).subscribe(k),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:ce(n,"durationchange").pipe(Be(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:S,inFullscreen$:k}};import{VideoQuality as Oe}from"@vkontakte/videoplayer-shared";var Ne=n=>{switch(n){case"mobile":return Oe.Q_144P;case"lowest":return Oe.Q_240P;case"low":return Oe.Q_360P;case"sd":case"medium":return Oe.Q_480P;case"hd":case"high":return Oe.Q_720P;case"fullhd":case"full":return Oe.Q_1080P;case"quadhd":case"quad":return Oe.Q_1440P;case"ultrahd":case"ultra":return Oe.Q_2160P}};import{isNonNullable as se,isNullable as jr,now as gs,isHigher as Wr,isHigherOrEqual as fs,isInvariantQuality as bs,isLower as Yr,isLowerOrEqual as nd,videoSizeToQuality as od,assertNotEmptyArray as vs,assertNonNullable as dd}from"@vkontakte/videoplayer-shared";var Qr=!1,Pe={},ps=n=>{Qr=n},hs=()=>{Pe={}},ms=n=>{n(Pe)},Rt=(n,e)=>{Qr&&(Pe.meta=Pe.meta??{},Pe.meta[n]=e)},Y=class{constructor(e){this.name=e}next(e){if(!Qr)return;Pe.series=Pe.series??{};let t=Pe.series[this.name]??[];t.push([Date.now(),e]),Pe.series[this.name]=t}};var ud=new Y("best_bitrate"),ys=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var qr=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),Dt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gs()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ts='Assertion "ABR Tracks is empty array" failed',Fi=(n,e,t,i)=>{let r=[...e].sort(qr(1)),a=[...t].sort(qr(1)),s=a.filter(u=>se(u.bitrate)&&se(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=a.at(Math.round(a.length*r.indexOf(n)/(r.length+1)))??a.at(-1);return o&&s.includes(o)?o:s.length?s.at(-1):a.at(0)},Ss=n=>"quality"in n,Is=(n,e,t,i)=>{let r=t&&i&&i.history[t.id]&&gs()-i.history[t.id]<=n.trackCooldown&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!r&&i.recordSelection(t),r&&i?.last){let a=i.last;i?.recordSwitch(a);let s=Ss(a)?"video":"audio",o=Ss(a)?a.quality:a.bitrate;return e({message:`
7
- [last ${s} selected] ${o}
8
- `}),a}return i?.recordSwitch(t),t},_e=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:c,abrLogger:l})=>{vs(n,Ts);let p=i.usePixelRatio?window.devicePixelRatio??1: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&&od(h),f=i.considerPlaybackRate&&se(o)?o:1,S=n.filter(I=>!bs(I.quality)).sort((I,V)=>Wr(I.quality,V.quality)?-1:1),k=S.at(-1)?.quality,C=S.at(0)?.quality,g=jr(r)||se(r.min)&&se(r.max)&&Yr(r.max,r.min)||se(r.min)&&C&&Wr(r.min,C)||se(r.max)&&k&&Yr(r.max,k),b=f*ys(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),v={},T=S.filter(I=>(m?Yr(I.quality,m):!0)?(se(t)&&isFinite(t)&&se(I.bitrate)?t-a>=I.bitrate*b:!0)?i.lazyQualitySwitch&&se(i.minBufferToSwitchUp)&&u&&!bs(u.quality)&&(s??0)<i.minBufferToSwitchUp&&Wr(I.quality,u.quality)?(v[I.quality]="Buffer",!1):!!c&&fs(I.quality,c)?(v[I.quality]="DroppedFramesLimit",!1):g||(jr(r.max)||nd(I.quality,r.max))&&(jr(r.min)||fs(I.quality,r.min))?!0:(v[I.quality]="FitsQualityLimits",!1):(v[I.quality]="FitsThroughput",!1):(v[I.quality]="FitsContainer",!1))[0];T&&T.bitrate&&ud.next(T.bitrate);let w=T??S[Math.ceil((S.length-1)/2)]??n[0];return w.quality!==d?.last?.quality&&l({message:`
9
- [VIDEO TRACKS ABR]
10
- [available video tracks]
11
- ${n.map(I=>`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate} }`).join(`
6
+ var Ca="2.0.108-dev.9b636631.0";var K=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(K||{}),De=(g=>(g.MPEG="MPEG",g.DASH="DASH",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_STREAMS="DASH_STREAMS",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(De||{});var Ci=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ci||{}),Mr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Mr||{});var Rr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Rr||{});import{assertNever as Fa,assertNonNullable as So,isNonNullable as Vi,ValueSubject as Dr,Subject as go,Subscription as vo,merge as yo,observableFrom as To,fromEvent as Ba,map as Oa,tap as _a,filterChanged as Io,isNullable as Cr,ErrorCategory as Na}from"@vkontakte/videoplayer-shared";var Va=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Bi=class{constructor(e){this.connection$=new Dr(void 0);this.castState$=new Dr("NOT_AVAILABLE");this.errorEvent$=new go;this.realCastState$=new Dr("NOT_AVAILABLE");this.subscription=new vo;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=Vi(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&this.initializeCastApi()},r||Va("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Na.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Vi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Cr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Cr(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(Ba(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Fa(r.sessionState)}})).add(yo(Ba(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_a(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Oa(r=>r.castState)),To([i.getCastState()])).pipe(Io(),Oa(Eo),_a(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",s=Vi(this.connection$.getValue());if(a&&!s){let o=i.getCurrentSession();So(o);let u=o.getCastDevice(),d=o.getMediaSession()?.media.contentId;(Cr(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Vi(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Na.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Eo=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Fa(n)}};import{assertNever as Ua}from"@vkontakte/videoplayer-shared";var j=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Ua(t)}return n},Vr=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:Ua(e)}};var y=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as xo,Subject as Oi,merge as Ha}from"@vkontakte/videoplayer-shared";var w=class{constructor(e){this.transitionStarted$=new Oi;this.transitionEnded$=new Oi;this.transitionUpdated$=new Oi;this.forceChanged$=new Oi;this.stateChangeStarted$=Ha(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ha(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||xo(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 ko}from"@vkontakte/videoplayer-shared";var Ga=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return ko(n)}};import{assertNever as mt,assertNonNullable as ze,debounce as Qa,ErrorCategory as Wa,fromEvent as Ke,isNonNullable as ja,map as Ya,merge as qa,observableFrom as Po,Subject as Ao,Subscription as Br,timeout as wo,getHighestQuality as $o}from"@vkontakte/videoplayer-shared";var Lo=5,Mo=5,Ro=500,za=7e3,$t=class{constructor(e){this.subscription=new Br;this.loadMediaTimeoutSubscription=new Br;this.videoState=new w("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:mt(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:mt(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:mt(e)}break}default:mt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ga(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 Br;this.subscription.add(e),this.subscription.add(qa(this.videoState.stateChangeStarted$.pipe(Ya(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ya(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 Ao;e.add(r.pipe(Qa(Ro)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>Lo)&&r.next(o),a=o})),e.add(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Mo&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),y(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:mt(s)}}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ke(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=qa(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Po(["init"])).pipe(Qa(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),y(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&y(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];ze(d);let c=$o(Object.keys(d));ze(c);let l=d[c];ze(l),i=l,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];ze(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];ze(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];ze(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];ze(d),i=j(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Wa.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return mt(e)}let s=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return ja(o)&&(s.metadata.title=o),ja(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(wo(za).subscribe(()=>a(`timeout(${za})`)))});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:Wa.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Ja}from"@vkontakte/videoplayer-shared";import{clearVideoElement as Do}from"@vkontakte/videoplayer-shared";var Ka=n=>{try{n.pause(),n.playbackRate=0,Do(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Co,Subscription as Vo}from"@vkontakte/videoplayer-shared";var Or=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)}},_r=window.WeakMap?new WeakMap:new Or,Nr=window.WeakMap?new WeakMap:new Map,Bo=(n,e=20)=>{let t=0;return Co(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},J=(n,{audioVideoSyncRate:e})=>{let t=n.querySelector("video"),i=!!t;t?Ja(t):(t=document.createElement("video"),n.appendChild(t)),_r.set(t,i);let r=new Vo;return r.add(Bo(t,e)),Nr.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},X=n=>{Nr.get(n)?.unsubscribe(),Nr.delete(n);let t=_r.get(n);_r.delete(n),t?Ja(n):Ka(n)};import{assertNonNullable as Lt,isNonNullable as Ie,isNullable as No,fromEvent as ft,merge as Xa,observableFrom as Za,filterChanged as es,map as Mt,Subject as ts,Subscription as Fo,ValueSubject as Uo,ErrorCategory as Ho}from"@vkontakte/videoplayer-shared";import{isNonNullable as Fr,isNullable as Oo,Subscription as _o}from"@vkontakte/videoplayer-shared";var _i=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=Oo(r),d=new _o;return r&&d.add(r.subscribe(c=>{let l=n.getState();i(c,l)&&n.setState(c)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),u&&n.setState(c.to)},a)),d},Te=(n,e,t)=>_i(e,()=>n.loop,i=>{Fr(i)&&(n.loop=i)},{onError:t}),Z=(n,e,t,i)=>_i(e,()=>({muted:n.muted,volume:n.volume}),r=>{Fr(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),de=(n,e,t,i)=>_i(e,()=>n.playbackRate,r=>{Fr(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Ce=_i;var Go=n=>["__",n.language,n.label].join("|"),Qo=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Ur=class n{constructor(){this.available$=new ts;this.current$=new Uo(void 0);this.error$=new ts;this.subscription=new Fo;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:Ho.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(Ce(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ie(a)&&this.setInternal(a)},{equal:(a,s)=>Ie(a)&&Ie(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Mt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(Ce(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ie(a)&&this.setExternal(a)},{equal:(a,s)=>Ie(a)&&Ie(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Mt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(Ce(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(Ce(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Lt(this.video);let{textTracks:e}=this.video;this.subscription.add(ft(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Xa(ft(e,"addtrack"),ft(e,"removetrack"),Za(["init"])).pipe(Mt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),es((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(Xa(ft(e,"change"),Za(["init"])).pipe(Mt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Mt(i=>i&&this.htmlTextTrackToITextTrack(i).id),es()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ft(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let s=a.target?.cues??null;s&&s.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ft(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Ie(t.align)&&(r.align=t.align),Ie(t.position)&&(r.position=t.position),Ie(t.size)&&(r.size=t.size),Ie(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Lt(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Go(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Lt(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(No(e)||!Qo(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){Lt(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){Lt(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)}},ue=Ur;var ke=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 is=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Hr=n=>{let e=is(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},rs=n=>{let e=is(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as le,map as Ve,merge as ss,filterChanged as jo,isNonNullable as ns,Subject as Yo,filter as os,mapTo as ds,combine as qo,once as zo,ErrorCategory as Ko,ValueSubject as us,clientChecker as Jo}from"@vkontakte/videoplayer-shared";var Wo=3,as=(n,e,t=Wo)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var ee=n=>{let e=g=>le(n,g).pipe(ds(void 0)),i=ss(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>le(n,g))).pipe(Ve(g=>g.type==="ended"?n.readyState<2:n.readyState<3),jo()),r=ss(le(n,"progress"),le(n,"timeupdate")).pipe(Ve(()=>as(n.buffered,n.currentTime))),a=Jo.isSafari?qo({play:e("play").pipe(zo()),playing:e("playing")}).pipe(ds(void 0)):e("playing"),s=le(n,"volumechange").pipe(Ve(()=>({muted:n.muted,volume:n.volume}))),o=le(n,"ratechange").pipe(Ve(()=>n.playbackRate)),u=le(n,"error").pipe(os(()=>!!(n.error||n.played.length)),Ve(()=>{let g=n.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:Ko.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:n.error??void 0}})),d=le(n,"timeupdate").pipe(Ve(()=>n.currentTime)),c=new Yo,l=.3,p;d.subscribe(g=>{n.loop&&ns(p)&&ns(g)&&p>=n.duration-l&&g<=l&&c.next(p),p=g});let h=e("pause").pipe(os(()=>!n.error&&p!==n.duration)),m=le(n,"enterpictureinpicture"),f=le(n,"leavepictureinpicture"),S=new us(rs(n));m.subscribe(()=>S.next(!0)),f.subscribe(()=>S.next(!1));let k=new us(Hr(n));return le(n,"fullscreenchange").pipe(Ve(()=>Hr(n))).subscribe(k),{playing$:a,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:le(n,"durationchange").pipe(Ve(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:s,playbackRateState$:o,inPiP$:S,inFullscreen$:k}};import{VideoQuality as Be}from"@vkontakte/videoplayer-shared";var Oe=n=>{switch(n){case"mobile":return Be.Q_144P;case"lowest":return Be.Q_240P;case"low":return Be.Q_360P;case"sd":case"medium":return Be.Q_480P;case"hd":case"high":return Be.Q_720P;case"fullhd":case"full":return Be.Q_1080P;case"quadhd":case"quad":return Be.Q_1440P;case"ultrahd":case"ultra":return Be.Q_2160P}};import{isNonNullable as _e,isNullable as Qr,now as fs,isHigher as Wr,isHigherOrEqual as hs,isInvariantQuality as ms,isLower as jr,isLowerOrEqual as Xo,videoSizeToQuality as Zo,assertNotEmptyArray as ed}from"@vkontakte/videoplayer-shared";var Gr=!1,Pe={},ls=n=>{Gr=n},cs=()=>{Pe={}},ps=n=>{n(Pe)},Rt=(n,e)=>{Gr&&(Pe.meta=Pe.meta??{},Pe.meta[n]=e)},Y=class{constructor(e){this.name=e}next(e){if(!Gr)return;Pe.series=Pe.series??{};let t=Pe.series[this.name]??[];t.push([Date.now(),e]),Pe.series[this.name]=t}};var td=new Y("best_bitrate"),id=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t,Ni=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=fs()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},rd='Assertion "ABR Tracks is empty array" failed',ad=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:c,abrLogger:l})=>{ed(n,rd);let p=i.usePixelRatio?window.devicePixelRatio??1: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&&Zo(h),f=i.considerPlaybackRate&&_e(o)?o:1,S=n.filter(E=>!ms(E.quality)).sort((E,D)=>Wr(E.quality,D.quality)?-1:1),k=S.at(-1)?.quality,B=S.at(0)?.quality,g=Qr(r)||_e(r.min)&&_e(r.max)&&jr(r.max,r.min)||_e(r.min)&&B&&Wr(r.min,B)||_e(r.max)&&k&&jr(r.max,k),b=f*id(s??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),v={},I=S.filter(E=>(m?jr(E.quality,m):!0)?(_e(t)&&isFinite(t)&&_e(E.bitrate)?t-a>=E.bitrate*b:!0)?i.lazyQualitySwitch&&_e(i.minBufferToSwitchUp)&&u&&!ms(u.quality)&&(s??0)<i.minBufferToSwitchUp&&Wr(E.quality,u.quality)?(v[E.quality]="Buffer",!1):!!c&&hs(E.quality,c)?(v[E.quality]="DroppedFramesLimit",!1):g||(Qr(r.max)||Xo(E.quality,r.max))&&(Qr(r.min)||hs(E.quality,r.min))?!0:(v[E.quality]="FitsQualityLimits",!1):(v[E.quality]="FitsThroughput",!1):(v[E.quality]="FitsContainer",!1))[0];I&&I.bitrate&&td.next(I.bitrate);let A=I??S[Math.ceil((S.length-1)/2)]??n[0];A.quality!==d?.last?.quality&&l({message:`
7
+ [available tracks]
8
+ ${n.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate} }`).join(`
12
9
  `)}
13
10
 
14
11
  [tuning]
15
- ${Object.entries(i??{}).map(([I,V])=>`${I}: ${V}`).join(`
12
+ ${Object.entries(i??{}).map(([E,D])=>`${E}: ${D}`).join(`
16
13
  `)}
17
14
 
18
15
  [limit params]
@@ -29,33 +26,15 @@ var Ba="2.0.108-dev.43b53ca1.0";var K=(r=>(r.STOPPED="stopped",r.READY="ready",r
29
26
  maxQualityLimit: ${r?.max},
30
27
  minQualityLimit: ${r?.min},
31
28
 
32
- [limited video tracks]
33
- ${Object.entries(v).map(([I,V])=>`${I}: ${V}`).join(`
29
+ [limited tracks]
30
+ ${Object.entries(v).map(([E,D])=>`${E}: ${D}`).join(`
34
31
  `)||"All tracks are available"}
35
32
 
36
- [best video track] ${T?.quality}
37
- [selected video track] ${w?.quality}
38
- `}),Is(i,l,w,d)},Es=(n,e,t,{throughput:i,tuning:r,playbackRate:a,forwardBufferHealth:s,history:o,abrLogger:u})=>{vs(t,Ts);let d=r.considerPlaybackRate&&se(a)?a:1,c=[...t].sort(qr(-1)),l=n.bitrate;dd(l);let p=d*ys(s??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h;return se(i)&&isFinite(i)&&(h=c.find(m=>se(m.bitrate)?i-l>=m.bitrate*p:!0)),h||(h=Fi(n,e,t,r.minVideoAudioRatio)),h?.bitrate!==o?.last?.bitrate&&u({message:`
39
- [AUDIO TRACKS ABR]
40
- [available audio tracks]
41
- ${e.map(m=>`{ id: ${m.id}, quality: ${m.quality}, bitrate: ${m.bitrate} }`).join(`
42
- `)}
43
-
44
- [tuning]
45
- ${Object.entries(r??{}).map(([m,f])=>`${m}: ${f}`).join(`
46
- `)}
47
-
48
- [limit params]
49
- throughput: ${i},
50
- reserve: ${l},
51
- playbackRate: ${a},
52
- playbackRateFactor: ${d},
53
- forwardBufferHealth: ${s},
54
- bitrateFactor: ${p},
55
- minBufferToSwitchUp: ${r.minBufferToSwitchUp},
56
-
57
- [selected audio track] ${h?.bitrate}
58
- `}),h&&Is(r,u,h,o)};var G=n=>new URL(n).hostname;import{assertNever as $s,assertNonNullable as Ls,combine as $d,debounce as Ld,ErrorCategory as Ms,filter as Rs,filterChanged as Md,isNonNullable as Zr,map as ji,merge as Ds,observableFrom as Rd,once as Dd,Subscription as Cd,ValueSubject as ea,videoQualityToHeight as Vd,videoSizeToQuality as Bd}from"@vkontakte/videoplayer-shared";var xs=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},te=async n=>{let e=n.muted;try{await n.play()}catch(t){if(!xs(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{await n.play()}catch(i){return xs(i)&&(n.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Hi,isNullable as pd,assertNonNullable as Bt}from"@vkontakte/videoplayer-shared";import{isNonNullable as ks,assertNonNullable as Ui,now as ld}from"@vkontakte/videoplayer-shared";function Q(){return ld()}function zr(n){return Q()-n}function Kr(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function As(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function bt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,c,l,p=!1,h="arraybuffer",m=7e3,f=2e3,S=()=>{if(u)return;Ui(c);let R=zr(c),H;if(R<f){H=f-R,setTimeout(S,H);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,L()},k=R=>(a=R,O),C=R=>(l=R,O),g=()=>(h="json",O),b=()=>{if(!u){if(--d>=0){S(),i&&i();return}u=!0,l&&l(),t&&t()}},v=R=>(p=R,O),L=()=>{c=Q(),s=new r,s.open("get",n);let R=0,H,me=0,de=()=>(Ui(c),Math.max(c,Math.max(H||0,me||0)));if(a&&s.addEventListener("progress",x=>{let A=Q();a.updateChunk&&x.loaded>R&&(a.updateChunk(de(),x.loaded-R),R=x.loaded,H=A)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>b())),s.addEventListener("load",()=>{if(u)return;Ui(s);let x=s.status;if(x>=200&&x<300){if(s.response.byteLength&&a){let A=s.response.byteLength-R;A&&a.updateChunk&&a.updateChunk(de(),A)}s.responseType==="json"&&!Object.values(s.response).length?b():(l&&l(),e(s.response))}else b()}),s.addEventListener("error",()=>{b()}),p){let x=()=>{Ui(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(me=Q(),s.removeEventListener("readystatechange",x))};s.addEventListener("readystatechange",x)}return s.responseType=h,s.send(),O},O={withBitrateReporting:k,withParallel:v,withJSONResponse:g,withRetryCount:R=>(d=R,O),withRetryInterval:(R,H)=>(ks(R)&&(f=R),ks(H)&&(m=H),O),withTimeout:R=>(o=R,O),withFinally:C,send:L,abort:()=>{s&&(s.abort(),s=void 0),u=!0,l&&l()}};return O}var Ct=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Vt=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=Q(),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=Q()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=bt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Q()}_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=Q();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Gi=1e4,Jr=3;var hd=6e4,md=10,fd=1,bd=500,Ot=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 Ct(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Kr(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=Kr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Hi(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=()=>{As(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 Vt(Jr,Gi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,d=null,c=!1,l=()=>{let b=a&&(!c||c===this.rep);return b||t("Not running!"),b},p=(b,v,L)=>{u&&u.abort(),u=bt(this.urlResolver.resolve(b,!1),v,L,()=>this._retryCallback()).withTimeout(Gi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Jr).withFinally(()=>{u=null}).send()},h=(b,v,L)=>{Bt(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),v,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=b=>{let v=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${v}=>${b}`),i.playbackRate=b)},f=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=Q()-1e4,T=0;for(let I=0;I<this.bufferStates.length;I++){let V=this.bufferStates[I];b=Math.min(b,V.buf),V.ts<L&&T++}this.bufferStates.splice(0,T),t(`update playback rate; minBuffer=${b} drop=${T} jitter=${this.sourceJitter}`);let w=b-fd;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?m(1.15):w>1?m(1.1):w>.3?m(1.05):m(1)}},k=b=>{let v,L=()=>v&&v.start?v.start.length:0,T=x=>v.start[x]/1e3,w=x=>v.dur[x]/1e3,I=x=>v.fragIndex+x,V=(x,A)=>({chunkIdx:I(x),startTS:T(x),dur:w(x),discontinuity:A}),O=()=>{let x=0;if(v&&v.dur){let A=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,F=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=A;this.sourceJitter>1&&(j+=this.sourceJitter-1);let ae=v.dur.length-1;for(;ae>=0&&(j-=v.dur[ae],!(j<=0));--ae);x=Math.min(ae,v.dur.length-1-F),x=Math.max(x,0)}return V(x,!0)},R=x=>{let A=L();if(!(A<=0)){if(Hi(x)){for(let F=0;F<A;F++)if(T(F)>x)return V(F)}return O()}},H=x=>{let A=L(),F=x?x.chunkIdx+1:0,j=F-v.fragIndex;if(!(A<=0)){if(!x||j<0||j-A>md)return t(`Resync: offset=${j} bChunks=${A} chunk=`+JSON.stringify(x)),O();if(!(j>=A))return V(F-v.fragIndex,!1)}},me=(x,A,F)=>{d&&d.abort(),d=bt(this.urlResolver.resolve(x,!0,this.lowLatency),A,F,()=>this._retryCallback()).withTimeout(Gi).withRetryCount(Jr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,A)=>{me(b,F=>{if(!l())return;v=F;let j=!!v.lowLatency;j!==this.lowLatency&&f(j);let ae=0;for(let ye=0;ye<v.dur.length;++ye)ae+=v.dur[ye];ae>0&&(Bt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ae/v.dur.length)),r({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,x(R(A))},()=>this._handleNetworkError())},nextChunk:H}},C=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),Bt(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:b=>{let{videoElement:v,logger:L}=this.params,T=k(e.jidxUrl),w,I,V,O,R=0,H,me,de,x=()=>{H&&(clearTimeout(H),H=void 0);let D=Math.max(bd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),U=R+D,z=Q(),fe=Math.min(1e4,U-z);R=z;let Me=()=>{d||l()&&T.seek(()=>{l()&&(R=Q(),A(),x())})};fe>0?H=window.setTimeout(()=>{this.paused?x():Me()},fe):Me()},A=()=>{let D;for(;D=T.nextChunk(O);)O=D,ut(D);let U=T.nextChunk(V);if(U){if(V&&U.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?x():(C(),this._initPlayerWith(e));return}ye(U)}else x()},F=(D,U)=>{if(!l()||!this.sourceBuffer)return;let z,fe,Me,lt=Re=>{window.setTimeout(()=>{l()&&F(D,U)},Re)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),lt(100);else{let Re=Q(),ct=v.currentTime;!this.paused&&v.buffered.length>1&&me===ct&&Re-de>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),me!==ct&&(me=ct,de=Re);let At=this._getBufferSizeSec();if(At>30)L(`Buffered ${At} seconds; delaying appendBuffer`),lt(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:Re,buf:At}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),U&&U()}catch(Li){if(Li.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(z=this.sourceBuffer.buffered.start(0),fe=ct,fe-z>4&&this.sourceBuffer.remove(z,fe-3)),lt(1e3);else throw Li}}},j=()=>{I&&w&&(L([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(V)]),F(I,function(){I=null,A()}))},ae=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),ye=D=>{l()&&h(ae(D),(U,z)=>{if(l()){if(z/=1e3,I=U,V=D,s=D.startTS,z){let fe=Math.min(10,D.dur/z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*fe:fe}j()}},()=>this._handleNetworkError())},ut=D=>{l()&&(Bt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ae(D),!1)))},Qe=D=>{l()&&(e.cachedHeader=D,F(D,()=>{w=!0,j()}))};a=!0,T.seek(D=>{if(l()){if(R=Q(),!D){x();return}O=D,!pd(b)||D.startTS>b?ye(D):(V=D,A())}},b),e.cachedHeader?Qe(e.cachedHeader):p(e.headerUrl,Qe,()=>this._handleNetworkError())},stop:C,getTimestampSec:()=>s},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Hi(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,Bt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Hi(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},a={updateChunk:(p,h)=>{let m=Q();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},s=-1/0,o,u=!0,d=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&zr(s)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,p)=>{let h=a.updateChunk(l,p);return h&&d(),h},notifySwitch:l=>{let p=Q();l<o&&(s=p),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=bt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Gi).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;te(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},hd))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Sd,filter as Ps,fromEvent as gd,interval as vd,isHigher as yd,isInvariantQuality as Td,isLower as Id,merge as Ed,Subject as ws,Subscription as xd}from"@vkontakte/videoplayer-shared";var Xr=class{constructor(){this.onDroopedVideoFramesLimit$=new ws;this.subscription=new xd;this.playing=!1;this.tracks=[];this.forceChecker$=new ws;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!Td(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&yd(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(gd(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=vd(this.droppedFramesChecker.checkTime).pipe(Ps(()=>this.playing),Ps(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Sd(this.droppedFramesChecker.checkTime)),i=Ed(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>Id(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Qi=Xr;import{map as kd,Observable as Ad}from"@vkontakte/videoplayer-shared";import{fromEvent as Pd}from"@vkontakte/videoplayer-shared";var Nt=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var wd=(n,e)=>new Ad(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Nt()))},{...i,...e});r.observe(n);let a=Pd(document,"visibilitychange").pipe(kd(s=>!document.hidden||Nt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),pe=wd;var Od=["paused","playing","ready"],Nd=["paused","playing","ready"],_t=class{constructor(e){this.subscription=new Cd;this.videoState=new P("stopped");this.representations$=new ea([]);this.textTracksManager=new le;this.droppedFramesManager=new Qi;this.maxSeekBackTime$=new ea(1/0);this.zeroTime$=new ea(void 0);this.liveOffset=new Ae;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Ms.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=Ne(r.name)??Bd(r.video),o=r.bitrate/1e3,u={...r.video};if(!s)continue;let d={id:a,quality:s,bitrate:o,size:u};i.push({track:d,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Zr(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Nd.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&Od.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(W(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(W(this.params.source.url,u))}return;default:return $s(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ms.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Ds(this.videoState.stateChangeStarted$.pipe(ji(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ji(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=J(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ee(this.video);this.subscription.add(this.representations$.pipe(ji(r=>r.map(({track:a})=>a)),Rs(r=>!!r.length),Dd()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Md(),ji(r=>-r/1e3)).subscribe(this.params.output.duration$)).add($d({zeroTime:this.zeroTime$.pipe(Rs(Zr)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ie(this.video,this.params.desiredState.isLooped,t)).add(Z(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ue(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(pe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Vd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return $s(r.to)}},t)).add(Ds(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Rd(["init"])).pipe(Ld(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),X(this.video)}createLiveDashPlayer(){let e=new Ot({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Zr(t)?t:_e(e.map(({track:d})=>d),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let d=e.find(({track:c})=>c.id===a)?.representation;Ls(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Ls(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(W(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var Cs=_t;var we=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Au,assertNonNullable as Pu,debounce as wu,ErrorCategory as ya,filter as An,filterChanged as Ta,fromEvent as $u,isLowerOrEqual as Pn,isNonNullable as Lu,isInvariantQuality as Mu,map as wn,merge as ur,observableFrom as Ru,observeElementSize as Du,once as $n,Subscription as Cu,ValueSubject as Vu}from"@vkontakte/videoplayer-shared";var $e=()=>window.ManagedMediaSource||window.MediaSource,Wi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Vs=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Bs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ki,clientChecker as qi}from"@vkontakte/videoplayer-shared";var zi=document.createElement("video"),Ud='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Hd='video/mp4; codecs="hev1.1.6.L93.B0"',Os='video/webm; codecs="vp09.00.10.08"',Ns='video/webm; codecs="av01.0.00M.08"',Gd='audio/mp4; codecs="mp4a.40.2"',Qd='audio/webm; codecs="opus"',Je={mms:Wi(),mse:Vs(),hls:!!(zi.canPlayType?.("application/x-mpegurl")||zi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ie={mp4:!!zi.canPlayType?.("video/mp4"),webm:!!zi.canPlayType?.("video/webm"),cmaf:!0},re={h264:!!$e()?.isTypeSupported?.(Ud),h265:!!$e()?.isTypeSupported?.(Hd),vp9:!!$e()?.isTypeSupported?.(Os),av1:!!$e()?.isTypeSupported?.(Ns),aac:!!$e()?.isTypeSupported?.(Gd),opus:!!$e()?.isTypeSupported?.(Qd)},St=(re.h264||re.h265)&&re.aac,Xe,jd=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Ns}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Os}})]);Xe={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{jd()}catch(n){console.error(n)}var gt=Je.hls&&ie.mp4,_s=()=>Object.keys(re).filter(n=>re[n]),Fs=(n,e=!1,t=!1)=>{let i=Je.mse||Je.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&ie.mp4&&St;case"DASH_WEBM":return i&&ie.webm&&re.vp9&&re.opus;case"DASH_WEBM_AV1":return i&&ie.webm&&re.av1&&re.opus;case"DASH_STREAMS":return i&&(ie.mp4&&St||ie.webm&&(re.vp9||re.av1)&&(re.opus||re.aac));case"DASH_LIVE":return Je.mse&&ie.mp4&&St;case"DASH_LIVE_CMAF":return i&&ie.mp4&&St&&ie.cmaf;case"DASH_ONDEMAND":return i&&ie.mp4&&St;case"HLS":case"HLS_ONDEMAND":return gt||e&&Je.mse&&ie.mp4&&St;case"HLS_LIVE":case"HLS_LIVE_CMAF":return gt;case"MPEG":return ie.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Je.webrtc&&Je.ws&&re.h264&&(ie.mp4||ie.webm);default:return Ki(r)}})},Yi=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Xe?Xe[t].smooth?[t,e]:Xe[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Xe?Xe[t].powerEfficient?[t,e]:Xe[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ki(n)}return[e,t]},Us=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Yi(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(qi.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Yi(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Yi(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Yi(n),...r,"HLS","HLS_ONDEMAND"];default:Ki(e)}return gt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Hs=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=qi.isMac&&qi.isSafari;if(qi.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:Ki(n)}else gt&&!u?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ta=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Gs=n=>{if(n.size!==0){if(n.size===1)return n.values().next().value.split(".").at(0);for(let e of n){let t=e.split(".").at(0);if(t==="opus"||t==="vp09"||t==="av01")return t}return n.values().next().value.split(".").at(0)}};import{ErrorCategory as Ft}from"@vkontakte/videoplayer-shared";var Qs=n=>{if(!n)return{id:"EmptyResponse",category:Ft.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Ft.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ft.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ft.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ft.PARSER,message:"Response is valid XML, but parser failed"}};var Ut=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};import{abortable as Sa,assertNonNullable as ot,combine as rr,ErrorCategory as Ue,filter as ar,filterChanged as vn,fromEvent as Et,interval as ga,isNonNullable as yn,map as va,merge as xt,Subject as Tn,Subscription as In,tap as vu,throttle as yu,clientChecker as Tu,ValueSubject as q}from"@vkontakte/videoplayer-shared";import{assertNever as Wd,ErrorCategory as js,clientChecker as ia,Subject as Ws}from"@vkontakte/videoplayer-shared";var Yd=16,Ys=!1;try{Ys=ia.isSafari&&!!ia.macVersion&&ia.macVersion<=Yd}catch(n){console.error(n)}var ra=class{constructor(e){this.bufferFull$=new Ws;this.error$=new Ws;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:js.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Ys&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:js.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Wd(t)}}},qs=ra;var aa=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as It,assertNonNullable as xe,ErrorCategory as at,fromEvent as ca,getExponentialDelay as pa,isNonNullable as pn,isNullable as ge,once as cu,Subject as pu,Subscription as hu,ValueSubject as ui}from"@vkontakte/videoplayer-shared";var B=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 vt=class extends B{};var Ht=class extends B{};var Gt=class extends B{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Qt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var jt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wt=class extends B{constructor(e,t){super(e,t),this.data=this.content}};var _=class extends B{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ze=class extends _{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,s=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:s,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}};var Yt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zt=class extends _{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Kt=class extends _{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Jt=class extends _{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Xt=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zt=class extends _{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ei=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ti=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ii=class extends _{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ri=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends _{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var si=class extends _{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 ni=class extends _{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 zd={ftyp:Gt,moov:Qt,moof:jt,mdat:Wt,sidx:Ze,trak:Yt,mdia:Xt,mfhd:ii,tkhd:Zt,traf:ri,tfhd:ai,tfdt:si,trun:ni,minf:ei,sv3d:qt,st3d:zt,prhd:Kt,proj:ti,equi:Jt,uuid:Ht,unknown:vt},et=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch{break}return t}createBox(e,t){let i=zd[e];return i?new i(t,new n):new vt(t,new n)}};var yt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Jd=new TextDecoder("ascii"),Xd=n=>Jd.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Zd=n=>{let e=new Ze(n,new et),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},eu=(n,e)=>{let i=new et().parse(n),r=new yt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,l)},tu=(n,e)=>{let i=new et().parse(n),a=new yt(i).findAll("traf"),s=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((l,p)=>l+p,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},iu=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new et().parse(n),r=new yt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},zs={validateData:Xd,parseInit:iu,getIndexRange:()=>{},parseSegments:Zd,parseFeedableSegmentChunk:eu,getSegmentEndTime:tu};import{assertNonNullable as na,isNonNullable as Zs,isNullable as au}from"@vkontakte/videoplayer-shared";import{assertNever as ru}from"@vkontakte/videoplayer-shared";var Ks={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"}},Js=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=oi(n,t),r=i in Ks,a=r?Ks[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,c=oi(u),l=d*2**((o-1)*8)+c,p=t+o,h;return p+l>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},oi=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Se=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return oi(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:ru(e)}},tt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Js(i);if(!e(r))return;r.type==="master"&&tt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Xs=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Js(n);return tt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=Se(o,s):a===17026?t=Se(o,s):a===17029&&(i=Se(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var en=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],su=[231,22612,22743,167,171,163,160,175],nu=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,c=!1,l=0;return tt(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let S=Se(m,h);d=oi(S)}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=Se(m,h):p===17545?r=Se(m,h):p===21420&&d===475249515?u=Se(m,h):p===374648427?tt(m,({tag:S,type:k,value:C})=>S===30321?(c=Se(C,k)===1,!1):!0):a&&s&&en.includes(p)&&(o=!0),!o}),na(e,"Failed to parse webm Segment start"),na(t,"Failed to parse webm Segment end"),na(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ou=n=>{if(au(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},du=(n,e)=>{let t=!1,i=!1,r=o=>Zs(o.time)&&Zs(o.position),a=[],s;return tt(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Se(d,u));break;case 183:break;case 241:s&&(s.position=Se(d,u));break;default:t&&en.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:c}=o,l=a[u+1];return{status:"none",time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},uu=n=>{let e=0,t=!1;try{tt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):su.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},tn={validateData:Xs,parseInit:nu,getIndexRange:ou,parseSegments:du,parseFeedableSegmentChunk:uu};var Tt=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return tn;case"mp4":return zs}}throw new ReferenceError(`Unsupported mime type ${n}`)};var oa=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as an,isNullable as sn}from"@vkontakte/videoplayer-shared";var rn=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var nn=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},it=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>sn(a)?o:sn(u)?a:a.padStart(parseInt(u,10),"0"))}return t},dn=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=a.querySelector("BaseURL")?.textContent?.trim()??"",u=s.children,d=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=c?new Date(c).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),S=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=nn(h);else if(m){let b=nn(m);an(b)&&(p=b)}else S&&(p=parseInt(S,10));let k=0,C=a.getAttribute("profiles")?.split(",")??[];for(let b of u){let v=b.getAttribute("id")??"id"+(k++).toString(10),L=b.getAttribute("mimeType")??"",T=b.getAttribute("codecs")??"",w=b.getAttribute("contentType")??L?.split("/")[0],I=b.getAttribute("profiles")?.split(",")??[],V=b.getAttribute("lang")??void 0,O=b.querySelector("Label")?.textContent?.trim()??void 0,R=b.querySelectorAll("Representation"),H=b.querySelector("SegmentTemplate"),me=b.querySelector("Role")?.getAttribute("value")??void 0,de=w,x={id:v,language:V,isDefault:me==="main",label:O,codecs:T,hdr:de==="video"&&oa(T),mime:L,representations:[]};for(let A of R){let F=A.getAttribute("lang")??void 0,j=A.getAttribute("label")??void 0,ae=A.querySelector("BaseURL")?.textContent?.trim()??"",ye=new URL(ae||o,e).toString(),ut=A.getAttribute("mimeType")??L,Qe=A.getAttribute("codecs")??T??"",D;if(w==="text"){let U=A.getAttribute("id")||"",z=U.includes("_auto");D={id:U,isAuto:z,kind:"text",url:ye}}else{let U=A.getAttribute("contentType")??ut?.split("/")[0]??w,z=b.getAttribute("profiles")?.split(",")??[],fe=parseInt(A.getAttribute("width")??"",10),Me=parseInt(A.getAttribute("height")??"",10),lt=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,Re=A.getAttribute("frameRate")??"",ct=A.getAttribute("quality")??void 0,At=Re?rn(Re):void 0,Li=A.getAttribute("id")??"id"+(k++).toString(10),So=U==="video"?`${Me}p`:U==="audio"?`${lt}Kbps`:Qe,go=`${Li}@${So}`,vo=[...C,...I,...z],kr,yo=A.querySelector("SegmentBase"),je=A.querySelector("SegmentTemplate")??H;if(yo){let We=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ye,Pr]=We.split("-").map(pt=>parseInt(pt,10)),De={from:Ye,to:Pr},Pt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[wr,Mi]=Pt?Pt.split("-").map(pt=>parseInt(pt,10)):[],wt=Pt?{from:wr,to:Mi}:void 0;kr={type:"byteRange",url:ye,initRange:De,indexRange:wt}}else if(je){let We={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},Ye=parseInt(je.getAttribute("timescale")??"",10),Pr=je.getAttribute("initialization")??"",De=je.getAttribute("media"),Pt=parseInt(je.getAttribute("startNumber")??"",10)??1,wr=it(Pr,We);if(!De)throw new ReferenceError("No media attribute in SegmentTemplate");let Mi=je.querySelectorAll("SegmentTimeline S")??[],wt=[],pt=0,$r="",Lr=0;if(Mi.length){let Ri=Pt,be=0;for(let ht of Mi){let Te=parseInt(ht.getAttribute("d")??"",10),qe=parseInt(ht.getAttribute("r")??"",10)||0,Di=parseInt(ht.getAttribute("t")??"",10);be=Number.isFinite(Di)?Di:be;let Mr=Te/Ye*1e3,Io=be/Ye*1e3;for(let Ci=0;Ci<qe+1;Ci++){let Eo=it(De,{...We,segmentNumber:Ri.toString(10),segmentTime:(be+Ci*Te).toString(10)}),Va=(Io??0)+Ci*Mr,xo=Va+Mr;Ri++,wt.push({time:{from:Va,to:xo},url:Eo})}be+=(qe+1)*Te,pt+=(qe+1)*Mr}Lr=be/Ye*1e3,$r=it(De,{...We,segmentNumber:Ri.toString(10),segmentTime:be.toString(10)})}else if(an(p)){let be=parseInt(je.getAttribute("duration")??"",10)/Ye*1e3,ht=Math.ceil(p/be),Te=0;for(let qe=1;qe<ht;qe++){let Di=it(De,{...We,segmentNumber:qe.toString(10),segmentTime:Te.toString(10)});wt.push({time:{from:Te,to:Te+be},url:Di}),Te+=be}Lr=Te,$r=it(De,{...We,segmentNumber:ht.toString(10),segmentTime:Te.toString(10)})}let To={time:{from:Lr,to:1/0},url:$r};kr={type:"template",baseUrl:ye,segmentTemplateUrl:De,initUrl:wr,totalSegmentsDurationMs:pt,segments:wt,nextSegmentBeyondManifest:To,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!U||!ut)continue;let Ar={video:"video",audio:"audio",text:"text"}[U];if(!Ar)continue;de||=Ar,D={id:go,kind:Ar,segmentReference:kr,profiles:vo,duration:p,bitrate:lt,mime:ut,codecs:Qe,width:fe,height:Me,fps:At,quality:ct}}x.language||=F,x.label||=j,x.mime||=ut,x.codecs||=Qe,x.hdr||=de==="video"&&oa(Qe),x.representations.push(D)}de&&r[de].push(x)}return{dynamic:d,liveAvailabilityStartTime:l,duration:p,streams:r}};import{videoSizeToQuality as lu}from"@vkontakte/videoplayer-shared";var un=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{let s=(a?Ne(a):void 0)??lu({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},ln=({id:n,bitrate:e})=>({id:n,bitrate:e}),Ji=(n,e,t)=>{let i=e.indexOf(n);return t.at(Math.round(t.length*i/e.length))??t.at(-1)},cn=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),ua=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),la=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Xi=n=>"url"in n,rt=n=>n.type==="template",di=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var li=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:d}){this.currentSegmentLength$=new ui(0);this.onLastSegment$=new ui(!1);this.fullyBuffered$=new ui(!1);this.playingRepresentation$=new ui(void 0);this.playingRepresentationInit$=new ui(void 0);this.error$=new pu;this.gaps=[];this.subscription=new hu;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=It(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new qs(this.sourceBuffer),this.subscription.add(ca(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:at.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:at.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(ca(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:at.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,aa(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=we(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,d<c)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);xe(i,"No init buffer for starting representation"),xe(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=It(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);xe(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ge(a)||ge(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),xe(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();pn(s)&&(this.isLive||(r.forEach(o=>o.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=It(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let d=t.find(p=>p.id===u);d&&this.representations.set(u,d);let c=this.representations.get(u);if(!c||!rt(c.segmentReference))return;let l=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);xe(r);let a=this.segments.get(i);xe(a,"No segments for starting representation");let s=this.initData.get(i);if(xe(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!d?.dynamic,this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ge(e)||ge(this.downloadingRepresentationId)||ge(this.playingRepresentationId)||ge(this.sourceBuffer)||!ge(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=we(this.sourceBuffer.buffered,e),l=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(a=l)}if(isFinite(this.bufferLimit)&&aa(this.sourceBuffer.buffered)>=this.bufferLimit){let d=we(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let c=o.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&we(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;pn(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),a=this.segments.get(i.id)??[],s=a.at(-1)?.time.to??0,o=r?.findIndex(u=>Math.floor(s)>=Math.floor(u.time.from)&&Math.floor(s)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=r.slice(o+1);this.segments.set(i.id,[...a,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;xe(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!rt(i))return;let r=this.segments.get(t.id)??[],a=r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to),!!!r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),u=it(i.segmentTemplateUrl,{segmentTime:o});r.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:l,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,S=p>i||f||m===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),C=this.preloadOnly&&p<=i+k||h<=i+k;return(l==="none"||l==="partially_ejected"&&S&&C&&this.sourceBuffer&&!Ut(this.sourceBuffer.buffered,i))&&S&&C});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(s<=d||o<=c);l++){let p=a[l];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")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:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await It(o,async function*(){let c=pa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;let l=new DataView(c);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=Tt(t.mime);r.segment.time.to=h.getSegmentEndTime(l,p)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(l,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),di(c)||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:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await It(s,async function*(){let u=pa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),ca(window,"online").pipe(cu()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),di(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(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,c)=>{if(!a.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let s=this.representations.get(t);if(s)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(s.mime).parseFeedableSegmentChunk(d,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,d=e.byteLength;for(let c of this.activeSegments){let{segment:l}=c,p=u==="byteRange",h=p?l.byte.to-l.byte.from+1:d;if(c.representationId!==t||!(!p||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let f=p?l.byte.from-i:0,S=p?l.byte.to-i:e.byteLength,k=f<r,C=S<=r;if(l.status==="downloading"&&k&&C){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+f,h);this.sourceBufferTaskQueue.append(g,a).then(b=>b&&!a.aborted?this.onSegmentFullyAppended(c,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&k&&(c.loadedBytes=Math.min(h,r-f),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+f+c.feedingBytes,c.loadedBytes-c.feedingBytes),b=c.loadedBytes===h?g:Tt(o.mime).parseFeedableSegmentChunk(g);b?.byteLength&&(l.status="partially_fed",c.feedingBytes+=b.byteLength,this.sourceBufferTaskQueue.append(b,a).then(v=>{if(a.aborted)s();else if(v)c.fedBytes+=b.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;s()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let c=d.byte.from-i,l=d.byte.to-i,p=l-c+1,h=c<r,m=l<=r;if(h){if(d.status==="downloading"&&m){d.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+c,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-c),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?f:Tt(o.mime).parseFeedableSegmentChunk(f);S?.byteLength&&(d.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):s())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Xi(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&r.time.from===e.segment.time.from&&r.time.to===e.segment.time.to&&(r.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||=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?It(this.destroyAbortController.signal,async function*(){let o=pa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:d,segments:c}=o,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l);let p=c;this.isLive&&rt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:at.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ge(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((c,l)=>c.from-l.from);let d=[u[0]];for(let c=1;c<u.length;c++){let{from:l,to:p}=u[c],h=d[d.length-1];h.to>=l?h.to=Math.max(h.to,p):d.push(u[c])}return d},o=u=>{if(a>=t)return r;r.push(u.time),r=s(r);let d=Xi(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let c=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||l)&&d.status==="fed"&&o(d)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,l=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(c)&&l++;if(l===this.segments.size){let p={time:{from:d,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let c of d)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,c)=>d||c,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ge(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,u=d=>{a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let c=Xi(d)?d.size??0:d.byte.to-d.byte.from;r+=c};for(let d of this.segments.values())for(let c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(a)&&isFinite(s),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let c=this.sourceBuffer.buffered.start(d)*1e3,l=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(c)&&Math.round(h.time.to)>=Math.round(l)){a=c,s=l;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>e+d&&l.status==="fed"&&u(l)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:at.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(ge(this.sourceBuffer)||ge(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),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=s&&c.to+t>=o),d=e.filter(c=>s>=c.from-t&&s<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var ci=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var hn=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as pi,assertNever as mn,fromEvent as fn,merge as mu,now as ha,Subscription as fu,ValueSubject as ma}from"@vkontakte/videoplayer-shared";var Zi=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 fu;this.fetchManifest=pi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=ci(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(hi);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=pi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){let d=e,c=new Headers;if(i)switch(t){case 0:{c.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:mn(t)}this.requestQuic&&(d=ci(d));let l=this.abortAllController.signal,p;if(s){let w=new AbortController;if(p=mu(fn(this.abortAllController.signal,"abort"),fn(s,"abort")).subscribe(()=>{try{w.abort()}catch(I){hi(I)}}),this.abortAllController.signal.aborted||s.aborted)try{w.abort()}catch(I){hi(I)}l=w.signal}let h=ha(),m=yield fetch(d,{priority:a,headers:c,signal:l}).catch(hi),f=ha();if(!m)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(f-h),!m.ok||!m.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!r&&!o)return p?.unsubscribe(),m.arrayBuffer();let[S,k]=m.body.tee(),C=S.getReader();o&&this.throughputEstimator?.trackStream(k,u);let g=0,b=new Uint8Array(0),v=!1,L=w=>{p?.unsubscribe(),v=!0,hi(w)},T=pi(l,async function*({done:w,value:I}){if(g===0&&this.lastRequestFirstBytes$.next(ha()-h),l.aborted){p?.unsubscribe();return}if(!w&&I){let V=new Uint8Array(b.length+I.length);V.set(b),V.set(I,b.length),b=V,g+=I.byteLength,r?.(new DataView(b.buffer),g),yield C?.read().then(T,L)}}.bind(this));return yield C?.read().then(T,L),p?.unsubscribe(),v?null:b.buffer}.bind(this));this.fetchByteRangeRepresentation=pi(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,d,c;e.indexRange&&(d=e.indexRange.from,c=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(c,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(l,m.from-s,m.to-m.from+1);else{let k=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!k)return null;f=new DataView(k)}let S=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(l),segments:S}}.bind(this));this.fetchTemplateRepresentation=pi(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}=hn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:mn(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},hi=n=>{if(!di(n))throw n};var st=(n,e,t)=>t*e+(1-t)*n,fa=(n,e)=>n.reduce((t,i)=>t+i,0)/e,bn=(n,e,t,i)=>{let r=0,a=t,s=fa(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as bu,ValueSubject as Sn}from"@vkontakte/videoplayer-shared";var Fe=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Sn(e.initial),this.debounced$=new Sn(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Y(`raw_${t}`),this.smoothedSeries$=new Y(`smoothed_${t}`),this.reportedSeries$=new Y(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(bu(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 er=class extends Fe{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=st(this.slow,e,this.params.emaAlphaSlow),this.fast=st(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var tr=class extends Fe{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=fa(this.pastMeasures,this.takenMeasures);this.emaSmoothed=st(this.emaSmoothed,e,this.params.emaAlpha);let i=bn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ir=class extends Fe{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?st(this.smoothed,t,this.params.emaAlpha):t}};var nt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new er({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new tr({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 ir({initial:e,label:"liveEdgeDelay",...t})}};var ba=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var En=["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 In;this.representationSubscription=new In;this.state$=new P("none");this.currentVideoRepresentation$=new q(void 0);this.currentVideoRepresentationInit$=new q(void 0);this.currentAudioRepresentation$=new q(void 0);this.currentVideoSegmentLength$=new q(0);this.currentAudioSegmentLength$=new q(0);this.error$=new Tn;this.lastConnectionType$=new q(void 0);this.lastConnectionReused$=new q(void 0);this.lastRequestFirstBytes$=new q(void 0);this.isLive$=new q(!1);this.liveDuration$=new q(0);this.liveAvailabilityStartTime$=new q(void 0);this.bufferLength$=new q(0);this.liveLoadBufferLength$=new q(0);this.livePositionFromPlayer$=new q(0);this.timeInWaiting=0;this.isActiveLowLatency$=new q(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Tn;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Sa(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=W(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ue.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Sa(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ue.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=dn(e??"",this.manifestUrlString)}catch(a){let s=Qs(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(s)}if(!t)return null;let i=(a,s,o)=>!!(this.element?.canPlayType?.(s)&&$e()?.isTypeSupported?.(`${s}; codecs="${o}"`)||a==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let o=t.streams[a].filter(({mime:c,codecs:l})=>i(a,c,l)),u=new Set(o.map(({codecs:c})=>c)),d=Gs(u);if(d&&(r[a]=o.filter(({codecs:c})=>c.startsWith(d))),a==="video"){let c=this.tuning.preferHDR,l=r.video.some(h=>h.hdr),p=r.video.some(h=>!h.hdr);Tu.isHDR&&c&&l?r.video=r.video.filter(h=>h.hdr):p&&(r.video=r.video.filter(h=>!h.hdr))}}return{...t,streams:r}}.bind(this));this.initRepresentations=Sa(this.destroyController.signal,async function*(e,t,i){ot(this.manifest),ot(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(Et(l,"error").pipe(ar(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ue.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?Bs():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Wi())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new li("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],yn(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new li("audio",this.source,l,s),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ga(1e3).subscribe(l=>{if(this.element?.paused){let p=Br(this.manifestUrlString,2);this.manifestUrlString=W(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(xt(...En.filter(l=>l!=="waiting").map(l=>Et(this.element,l))).pipe(va(l=>this.element?we(this.element.buffered,this.element.currentTime*1e3):0),vn(),ar(l=>!!l),vu(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(vn()).subscribe(p=>ba(this.element,1))),this.representationSubscription.add(rr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(ar(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(rr({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,f=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,k=p-m,C=1;Math.abs(k)>f&&(C=1+Math.sign(k)*S),ba(this.element,C)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(rr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(yu(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(ot(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,f=Br(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),C=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,b=isFinite(p)?p:h,v=this.isActiveLowLatency$.getValue(),L=S<=this.tuning.live.activeLiveDelay&&f===0;this.isActiveLowLatency$.next(v&&L);let T="none";if(v?T="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&L?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),T="active_low_latency"):f!==0&&b<k?T="live_forward_buffering":b<k+g&&(T="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),T==="live_forward_buffering"||T==="live_with_target_offset"){let w=l-(k+C),I=this.normolizeLiveOffset(Math.trunc(f+w/m)),V=Math.abs(I-f),O;!p||V<=this.tuning.dashCmafLive.offsetCalculationError?O=f:I>0&&V>this.tuning.dashCmafLive.offsetCalculationError?O=I:O=0,this.manifestUrlString=W(this.manifestUrlString,O,2)}T!=="none"&&T!=="active_low_latency"&&(l=0,this.updateLive())}))}let u=xt(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(va(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),d=xt(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(va(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(xt(this.forceEnded$,rr({allBuffersFull:u,someBufferEnded:d}).pipe(ar(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(xt(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(l=>this.source?.addEventListener("sourceopen",l)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>l.duration??0)];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&yn(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=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ga(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ue.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Zi({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=nt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){ot(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=W(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){ot(this.element),this.state$.setState("running"),this.subscription.add(xt(...En.map(e=>Et(this.element,e)),Et(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ue.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Et(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Et(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ut(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{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 t=this.element.currentTime*1e3;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=ga(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){ot(this.element),ot(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Ut(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;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 nr=class{constructor(e,t){this.fov=e,this.orientation=t}};var or=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var xn=`attribute vec2 a_vertex;
33
+ [best track] ${I?.quality}
34
+ [selected track] ${A?.quality}
35
+ `});let R=A&&d&&d.history[A.id]&&fs()-d.history[A.id]<=i.trackCooldown&&(!d.last||A.id!==d.last.id);if(A?.id&&d&&!R&&d.recordSelection(A),R&&d?.last){let E=d.last;return d?.recordSwitch(E),l({message:`
36
+ [last selected] ${E?.quality}
37
+ `}),E}return d?.recordSwitch(A),A},Ne=ad;var G=n=>new URL(n).hostname;import{assertNever as Ts,assertNonNullable as Is,combine as xd,debounce as kd,ErrorCategory as Es,filter as xs,filterChanged as Pd,isNonNullable as Jr,map as Qi,merge as ks,observableFrom as Ad,once as wd,Subscription as $d,ValueSubject as Xr,videoQualityToHeight as Ld,videoSizeToQuality as Md}from"@vkontakte/videoplayer-shared";var bs=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},te=async n=>{let e=n.muted;try{await n.play()}catch(t){if(!bs(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{await n.play()}catch(i){return bs(i)&&(n.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Ui,isNullable as od,assertNonNullable as Vt}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ss,assertNonNullable as Fi,now as sd}from"@vkontakte/videoplayer-shared";function Q(){return sd()}function Yr(n){return Q()-n}function qr(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function gs(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function bt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,c,l,p=!1,h="arraybuffer",m=7e3,f=2e3,S=()=>{if(u)return;Fi(c);let C=Yr(c),H;if(C<f){H=f-C,setTimeout(S,H);return}f*=2,f>m&&(f=m),s&&s.abort(),s=new r,L()},k=C=>(a=C,D),B=C=>(l=C,D),g=()=>(h="json",D),b=()=>{if(!u){if(--d>=0){S(),i&&i();return}u=!0,l&&l(),t&&t()}},v=C=>(p=C,D),L=()=>{c=Q(),s=new r,s.open("get",n);let C=0,H,he=0,ae=()=>(Fi(c),Math.max(c,Math.max(H||0,he||0)));if(a&&s.addEventListener("progress",x=>{let P=Q();a.updateChunk&&x.loaded>C&&(a.updateChunk(ae(),x.loaded-C),C=x.loaded,H=P)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>b())),s.addEventListener("load",()=>{if(u)return;Fi(s);let x=s.status;if(x>=200&&x<300){if(s.response.byteLength&&a){let P=s.response.byteLength-C;P&&a.updateChunk&&a.updateChunk(ae(),P)}s.responseType==="json"&&!Object.values(s.response).length?b():(l&&l(),e(s.response))}else b()}),s.addEventListener("error",()=>{b()}),p){let x=()=>{Fi(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(he=Q(),s.removeEventListener("readystatechange",x))};s.addEventListener("readystatechange",x)}return s.responseType=h,s.send(),D},D={withBitrateReporting:k,withParallel:v,withJSONResponse:g,withRetryCount:C=>(d=C,D),withRetryInterval:(C,H)=>(Ss(C)&&(f=C),Ss(H)&&(m=H),D),withTimeout:C=>(o=C,D),withFinally:B,send:L,abort:()=>{s&&(s.abort(),s=void 0),u=!0,l&&l()}};return D}var Dt=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ct=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=Q(),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=Q()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=bt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Q()}_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=Q();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Hi=1e4,zr=3;var dd=6e4,ud=10,ld=1,cd=500,Bt=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 Dt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=qr(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=qr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ui(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=()=>{gs(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 Ct(zr,Hi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,d=null,c=!1,l=()=>{let b=a&&(!c||c===this.rep);return b||t("Not running!"),b},p=(b,v,L)=>{u&&u.abort(),u=bt(this.urlResolver.resolve(b,!1),v,L,()=>this._retryCallback()).withTimeout(Hi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(zr).withFinally(()=>{u=null}).send()},h=(b,v,L)=>{Vt(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),v,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=b=>{let v=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${v}=>${b}`),i.playbackRate=b)},f=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=Q()-1e4,I=0;for(let R=0;R<this.bufferStates.length;R++){let E=this.bufferStates[R];b=Math.min(b,E.buf),E.ts<L&&I++}this.bufferStates.splice(0,I),t(`update playback rate; minBuffer=${b} drop=${I} jitter=${this.sourceJitter}`);let A=b-ld;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?m(1.15):A>1?m(1.1):A>.3?m(1.05):m(1)}},k=b=>{let v,L=()=>v&&v.start?v.start.length:0,I=x=>v.start[x]/1e3,A=x=>v.dur[x]/1e3,R=x=>v.fragIndex+x,E=(x,P)=>({chunkIdx:R(x),startTS:I(x),dur:A(x),discontinuity:P}),D=()=>{let x=0;if(v&&v.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,F=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=P;this.sourceJitter>1&&(W+=this.sourceJitter-1);let se=v.dur.length-1;for(;se>=0&&(W-=v.dur[se],!(W<=0));--se);x=Math.min(se,v.dur.length-1-F),x=Math.max(x,0)}return E(x,!0)},C=x=>{let P=L();if(!(P<=0)){if(Ui(x)){for(let F=0;F<P;F++)if(I(F)>x)return E(F)}return D()}},H=x=>{let P=L(),F=x?x.chunkIdx+1:0,W=F-v.fragIndex;if(!(P<=0)){if(!x||W<0||W-P>ud)return t(`Resync: offset=${W} bChunks=${P} chunk=`+JSON.stringify(x)),D();if(!(W>=P))return E(F-v.fragIndex,!1)}},he=(x,P,F)=>{d&&d.abort(),d=bt(this.urlResolver.resolve(x,!0,this.lowLatency),P,F,()=>this._retryCallback()).withTimeout(Hi).withRetryCount(zr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,P)=>{he(b,F=>{if(!l())return;v=F;let W=!!v.lowLatency;W!==this.lowLatency&&f(W);let se=0;for(let ve=0;ve<v.dur.length;++ve)se+=v.dur[ve];se>0&&(Vt(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/v.dur.length)),r({name:"index",zeroTime:v.zeroTime,shiftDuration:v.shiftDuration}),this.sourceJitter=v.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,v.jitter/1e3)):1,x(C(P))},()=>this._handleNetworkError())},nextChunk:H}},B=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),Vt(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:b=>{let{videoElement:v,logger:L}=this.params,I=k(e.jidxUrl),A,R,E,D,C=0,H,he,ae,x=()=>{H&&(clearTimeout(H),H=void 0);let V=Math.max(cd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),U=C+V,z=Q(),me=Math.min(1e4,U-z);C=z;let Le=()=>{d||l()&&I.seek(()=>{l()&&(C=Q(),P(),x())})};me>0?H=window.setTimeout(()=>{this.paused?x():Le()},me):Le()},P=()=>{let V;for(;V=I.nextChunk(D);)D=V,ut(V);let U=I.nextChunk(E);if(U){if(E&&U.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?x():(B(),this._initPlayerWith(e));return}ve(U)}else x()},F=(V,U)=>{if(!l()||!this.sourceBuffer)return;let z,me,Le,lt=Me=>{window.setTimeout(()=>{l()&&F(V,U)},Me)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),lt(100);else{let Me=Q(),ct=v.currentTime;!this.paused&&v.buffered.length>1&&he===ct&&Me-ae>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),he!==ct&&(he=ct,ae=Me);let Pt=this._getBufferSizeSec();if(Pt>30)L(`Buffered ${Pt} seconds; delaying appendBuffer`),lt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:Me,buf:Pt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),U&&U()}catch($i){if($i.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Le=this.sourceBuffer.buffered.length,Le!==0&&(z=this.sourceBuffer.buffered.start(0),me=ct,me-z>4&&this.sourceBuffer.remove(z,me-3)),lt(1e3);else throw $i}}},W=()=>{R&&A&&(L([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(E)]),F(R,function(){R=null,P()}))},se=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),ve=V=>{l()&&h(se(V),(U,z)=>{if(l()){if(z/=1e3,R=U,E=V,s=V.startTS,z){let me=Math.min(10,V.dur/z);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}W()}},()=>this._handleNetworkError())},ut=V=>{l()&&(Vt(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(V),!1)))},Qe=V=>{l()&&(e.cachedHeader=V,F(V,()=>{A=!0,W()}))};a=!0,I.seek(V=>{if(l()){if(C=Q(),!V){x();return}D=V,!od(b)||V.startTS>b?ve(V):(E=V,P())}},b),e.cachedHeader?Qe(e.cachedHeader):p(e.headerUrl,Qe,()=>this._handleNetworkError())},stop:B,getTimestampSec:()=>s},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Ui(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,Vt(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ui(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),m=l/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},a={updateChunk:(p,h)=>{let m=Q();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},s=-1/0,o,u=!0,d=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&Yr(s)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,p)=>{let h=a.updateChunk(l,p);return h&&d(),h},notifySwitch:l=>{let p=Q();l<o&&(s=p),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=bt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Hi).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;te(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s?.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},dd))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as pd,filter as vs,fromEvent as hd,interval as md,isHigher as fd,isInvariantQuality as bd,isLower as Sd,merge as gd,Subject as ys,Subscription as vd}from"@vkontakte/videoplayer-shared";var Kr=class{constructor(){this.onDroopedVideoFramesLimit$=new ys;this.subscription=new vd;this.playing=!1;this.tracks=[];this.forceChecker$=new ys;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!bd(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&fd(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(hd(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=md(this.droppedFramesChecker.checkTime).pipe(vs(()=>this.playing),vs(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(pd(this.droppedFramesChecker.checkTime)),i=gd(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>Sd(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Gi=Kr;import{map as yd,Observable as Td}from"@vkontakte/videoplayer-shared";import{fromEvent as Id}from"@vkontakte/videoplayer-shared";var Ot=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Ed=(n,e)=>new Td(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Ot()))},{...i,...e});r.observe(n);let a=Id(document,"visibilitychange").pipe(yd(s=>!document.hidden||Ot())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),ce=Ed;var Rd=["paused","playing","ready"],Dd=["paused","playing","ready"],_t=class{constructor(e){this.subscription=new $d;this.videoState=new w("stopped");this.representations$=new Xr([]);this.textTracksManager=new ue;this.droppedFramesManager=new Gi;this.maxSeekBackTime$=new Xr(1/0);this.zeroTime$=new Xr(void 0);this.liveOffset=new ke;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Es.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),s=Oe(r.name)??Md(r.video),o=r.bitrate/1e3,u={...r.video};if(!s)continue;let d={id:a,quality:s,bitrate:o,size:u};i.push({track:d,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Jr(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Dd.includes(e)&&(s||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&Rd.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(j(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(j(this.params.source.url,u))}return;default:return Ts(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Es.WTF,message:"DashLiveProvider internal logic error",thrown:r})};ks(this.videoState.stateChangeStarted$.pipe(Qi(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Qi(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=J(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ee(this.video);this.subscription.add(this.representations$.pipe(Qi(r=>r.map(({track:a})=>a)),xs(r=>!!r.length),wd()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Pd(),Qi(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(xd({zeroTime:this.zeroTime$.pipe(xs(Jr)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Te(this.video,this.params.desiredState.isLooped,t)).add(Z(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(de(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Ld(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Ts(r.to)}},t)).add(ks(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ad(["init"])).pipe(kd(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),X(this.video)}createLiveDashPlayer(){let e=new Bt({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Jr(t)?t:Ne(e.map(({track:d})=>d),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let d=e.find(({track:c})=>c.id===a)?.representation;Is(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Is(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 Ps=_t;var Ae=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as Tu,assertNonNullable as Iu,debounce as Eu,ErrorCategory as ga,filter as gn,filterChanged as va,fromEvent as xu,isLowerOrEqual as vn,isNonNullable as ku,isInvariantQuality as Pu,map as yn,merge as dr,observableFrom as Au,observeElementSize as wu,once as Tn,Subscription as $u,ValueSubject as Lu}from"@vkontakte/videoplayer-shared";var we=()=>window.ManagedMediaSource||window.MediaSource,Wi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),As=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),ws=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as zi,clientChecker as Yi}from"@vkontakte/videoplayer-shared";var qi=document.createElement("video"),Bd='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Od='video/mp4; codecs="hev1.1.6.L93.B0"',$s='video/webm; codecs="vp09.00.10.08"',Ls='video/webm; codecs="av01.0.00M.08"',_d='audio/mp4; codecs="mp4a.40.2"',Nd='audio/webm; codecs="opus"',Je={mms:Wi(),mse:As(),hls:!!(qi.canPlayType?.("application/x-mpegurl")||qi.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ie={mp4:!!qi.canPlayType?.("video/mp4"),webm:!!qi.canPlayType?.("video/webm"),cmaf:!0},re={h264:!!we()?.isTypeSupported?.(Bd),h265:!!we()?.isTypeSupported?.(Od),vp9:!!we()?.isTypeSupported?.($s),av1:!!we()?.isTypeSupported?.(Ls),aac:!!we()?.isTypeSupported?.(_d),opus:!!we()?.isTypeSupported?.(Nd)},St=(re.h264||re.h265)&&re.aac,Xe,Fd=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:Ls}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:$s}})]);Xe={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Fd()}catch(n){console.error(n)}var gt=Je.hls&&ie.mp4,Ms=()=>Object.keys(re).filter(n=>re[n]),Rs=(n,e=!1,t=!1)=>{let i=Je.mse||Je.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&ie.mp4&&St;case"DASH_WEBM":return i&&ie.webm&&re.vp9&&re.opus;case"DASH_WEBM_AV1":return i&&ie.webm&&re.av1&&re.opus;case"DASH_STREAMS":return i&&(ie.mp4&&St||ie.webm&&(re.vp9||re.av1)&&(re.opus||re.aac));case"DASH_LIVE":return Je.mse&&ie.mp4&&St;case"DASH_LIVE_CMAF":return i&&ie.mp4&&St&&ie.cmaf;case"DASH_ONDEMAND":return i&&ie.mp4&&St;case"HLS":case"HLS_ONDEMAND":return gt||e&&Je.mse&&ie.mp4&&St;case"HLS_LIVE":case"HLS_LIVE_CMAF":return gt;case"MPEG":return ie.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Je.webrtc&&Je.ws&&re.h264&&(ie.mp4||ie.webm);default:return zi(r)}})},ji=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Xe?Xe[t].smooth?[t,e]:Xe[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Xe?Xe[t].powerEfficient?[t,e]:Xe[e].powerEfficient?[e,t]:[t,e]:[e,t];default:zi(n)}return[e,t]},Ds=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ji(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Yi.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...ji(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ji(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ji(n),...r,"HLS","HLS_ONDEMAND"];default:zi(e)}return gt?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Cs=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=Yi.isMac&&Yi.isSafari;if(Yi.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:zi(n)}else gt&&!u?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Zr=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Vs=n=>{if(n.size!==0){if(n.size===1)return n.values().next().value.split(".").at(0);for(let e of n){let t=e.split(".").at(0);if(t==="opus"||t==="vp09"||t==="av01")return t}return n.values().next().value.split(".").at(0)}};import{ErrorCategory as Nt}from"@vkontakte/videoplayer-shared";var Bs=n=>{if(!n)return{id:"EmptyResponse",category:Nt.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Nt.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Nt.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Nt.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Nt.PARSER,message:"Response is valid XML, but parser failed"}};var Ft=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};import{abortable as fa,assertNonNullable as ot,combine as ir,ErrorCategory as Ue,filter as rr,filterChanged as cn,fromEvent as Et,interval as ba,isNonNullable as pn,map as Sa,merge as xt,Subject as hn,Subscription as mn,tap as mu,throttle as fu,clientChecker as bu,ValueSubject as q}from"@vkontakte/videoplayer-shared";import{assertNever as Ud,ErrorCategory as Os,clientChecker as ea,Subject as _s}from"@vkontakte/videoplayer-shared";var Hd=16,Ns=!1;try{Ns=ea.isSafari&&!!ea.macVersion&&ea.macVersion<=Hd}catch(n){console.error(n)}var ta=class{constructor(e){this.bufferFull$=new _s;this.error$=new _s;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Os.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Ns&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Os.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Ud(t)}}},Fs=ta;var ia=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as It,assertNonNullable as Ee,ErrorCategory as at,fromEvent as ua,getExponentialDelay as la,isNonNullable as an,isNullable as Se,once as nu,Subject as ou,Subscription as du,ValueSubject as di}from"@vkontakte/videoplayer-shared";var O=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var vt=class extends O{};var Ut=class extends O{};var Ht=class extends O{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Gt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Qt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wt=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var N=class extends O{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ze=class extends N{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,s=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:s,subsegmentDuration:o,SAPType:u,SAPDeltaTime:d})}}};var jt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qt=class extends N{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var zt=class extends N{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Kt=class extends N{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Jt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xt=class extends N{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Zt=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ei=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ti=class extends N{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ii=class extends O{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ri=class extends N{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ai=class extends N{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 si=class extends N{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 Qd={ftyp:Ht,moov:Gt,moof:Qt,mdat:Wt,sidx:Ze,trak:jt,mdia:Jt,mfhd:ti,tkhd:Xt,traf:ii,tfhd:ri,tfdt:ai,trun:si,minf:Zt,sv3d:Yt,st3d:qt,prhd:zt,proj:ei,equi:Kt,uuid:Ut,unknown:vt},et=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch{break}return t}createBox(e,t){let i=Qd[e];return i?new i(t,new n):new vt(t,new n)}};var yt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var jd=new TextDecoder("ascii"),Yd=n=>jd.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",qd=n=>{let e=new Ze(n,new et),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},zd=(n,e)=>{let i=new et().parse(n),r=new yt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,l)},Kd=(n,e)=>{let i=new et().parse(n),a=new yt(i).findAll("traf"),s=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((l,p)=>l+p,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},Jd=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new et().parse(n),r=new yt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Us={validateData:Yd,parseInit:Jd,getIndexRange:()=>{},parseSegments:qd,parseFeedableSegmentChunk:zd,getSegmentEndTime:Kd};import{assertNonNullable as aa,isNonNullable as Ws,isNullable as Zd}from"@vkontakte/videoplayer-shared";import{assertNever as Xd}from"@vkontakte/videoplayer-shared";var Hs={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"}},Gs=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ni(n,t),r=i in Hs,a=r?Hs[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,c=ni(u),l=d*2**((o-1)*8)+c,p=t+o,h;return p+l>n.byteLength?h=new DataView(n.buffer,n.byteOffset+p):h=new DataView(n.buffer,n.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},ni=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},be=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ni(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:Xd(e)}},tt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Gs(i);if(!e(r))return;r.type==="master"&&tt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Qs=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Gs(n);return tt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=be(o,s):a===17026?t=be(o,s):a===17029&&(i=be(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var js=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],eu=[231,22612,22743,167,171,163,160,175],tu=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,c=!1,l=0;return tt(n,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let S=be(m,h);d=ni(S)}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=be(m,h):p===17545?r=be(m,h):p===21420&&d===475249515?u=be(m,h):p===374648427?tt(m,({tag:S,type:k,value:B})=>S===30321?(c=be(B,k)===1,!1):!0):a&&s&&js.includes(p)&&(o=!0),!o}),aa(e,"Failed to parse webm Segment start"),aa(t,"Failed to parse webm Segment end"),aa(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},iu=n=>{if(Zd(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ru=(n,e)=>{let t=!1,i=!1,r=o=>Ws(o.time)&&Ws(o.position),a=[],s;return tt(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=be(d,u));break;case 183:break;case 241:s&&(s.position=be(d,u));break;default:t&&js.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:c}=o,l=a[u+1];return{status:"none",time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},au=n=>{let e=0,t=!1;try{tt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):eu.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},Ys={validateData:Qs,parseInit:tu,getIndexRange:iu,parseSegments:ru,parseFeedableSegmentChunk:au};var Tt=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ys;case"mp4":return Us}}throw new ReferenceError(`Unsupported mime type ${n}`)};var sa=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,s]=i;return!!(s&&parseInt(s,10)>8)}case"vp09":{let[r,a,s]=i;return!!(r&&parseInt(r,10)>=2&&s&&parseInt(s,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,s]=r.toUpperCase(),o=a+s;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as zs,isNullable as Ks}from"@vkontakte/videoplayer-shared";var qs=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Js=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},it=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>Ks(a)?o:Ks(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Zs=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=a.querySelector("BaseURL")?.textContent?.trim()??"",u=s.children,d=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=c?new Date(c).getTime():void 0,p,h=a.getAttribute("mediaPresentationDuration"),m=s.getAttribute("duration"),S=a.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Js(h);else if(m){let b=Js(m);zs(b)&&(p=b)}else S&&(p=parseInt(S,10));let k=0,B=a.getAttribute("profiles")?.split(",")??[];for(let b of u){let v=b.getAttribute("id")??"id"+(k++).toString(10),L=b.getAttribute("mimeType")??"",I=b.getAttribute("codecs")??"",A=b.getAttribute("contentType")??L?.split("/")[0],R=b.getAttribute("profiles")?.split(",")??[],E=b.getAttribute("lang")??void 0,D=b.querySelector("Label")?.textContent?.trim()??void 0,C=b.querySelectorAll("Representation"),H=b.querySelector("SegmentTemplate"),he=b.querySelector("Role")?.getAttribute("value")??void 0,ae=A,x={id:v,language:E,isDefault:he==="main",label:D,codecs:I,hdr:ae==="video"&&sa(I),mime:L,representations:[]};for(let P of C){let F=P.getAttribute("lang")??void 0,W=P.getAttribute("label")??void 0,se=P.querySelector("BaseURL")?.textContent?.trim()??"",ve=new URL(se||o,e).toString(),ut=P.getAttribute("mimeType")??L,Qe=P.getAttribute("codecs")??I??"",V;if(A==="text"){let U=P.getAttribute("id")||"",z=U.includes("_auto");V={id:U,isAuto:z,kind:"text",url:ve}}else{let U=P.getAttribute("contentType")??ut?.split("/")[0]??A,z=b.getAttribute("profiles")?.split(",")??[],me=parseInt(P.getAttribute("width")??"",10),Le=parseInt(P.getAttribute("height")??"",10),lt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,Me=P.getAttribute("frameRate")??"",ct=P.getAttribute("quality")??void 0,Pt=Me?qs(Me):void 0,$i=P.getAttribute("id")??"id"+(k++).toString(10),uo=U==="video"?`${Le}p`:U==="audio"?`${lt}Kbps`:Qe,lo=`${$i}@${uo}`,co=[...B,...R,...z],xr,po=P.querySelector("SegmentBase"),We=P.querySelector("SegmentTemplate")??H;if(po){let je=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ye,Pr]=je.split("-").map(pt=>parseInt(pt,10)),Re={from:Ye,to:Pr},At=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ar,Li]=At?At.split("-").map(pt=>parseInt(pt,10)):[],wt=At?{from:Ar,to:Li}:void 0;xr={type:"byteRange",url:ve,initRange:Re,indexRange:wt}}else if(We){let je={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},Ye=parseInt(We.getAttribute("timescale")??"",10),Pr=We.getAttribute("initialization")??"",Re=We.getAttribute("media"),At=parseInt(We.getAttribute("startNumber")??"",10)??1,Ar=it(Pr,je);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let Li=We.querySelectorAll("SegmentTimeline S")??[],wt=[],pt=0,wr="",$r=0;if(Li.length){let Mi=At,fe=0;for(let ht of Li){let ye=parseInt(ht.getAttribute("d")??"",10),qe=parseInt(ht.getAttribute("r")??"",10)||0,Ri=parseInt(ht.getAttribute("t")??"",10);fe=Number.isFinite(Ri)?Ri:fe;let Lr=ye/Ye*1e3,mo=fe/Ye*1e3;for(let Di=0;Di<qe+1;Di++){let fo=it(Re,{...je,segmentNumber:Mi.toString(10),segmentTime:(fe+Di*ye).toString(10)}),Da=(mo??0)+Di*Lr,bo=Da+Lr;Mi++,wt.push({time:{from:Da,to:bo},url:fo})}fe+=(qe+1)*ye,pt+=(qe+1)*Lr}$r=fe/Ye*1e3,wr=it(Re,{...je,segmentNumber:Mi.toString(10),segmentTime:fe.toString(10)})}else if(zs(p)){let fe=parseInt(We.getAttribute("duration")??"",10)/Ye*1e3,ht=Math.ceil(p/fe),ye=0;for(let qe=1;qe<ht;qe++){let Ri=it(Re,{...je,segmentNumber:qe.toString(10),segmentTime:ye.toString(10)});wt.push({time:{from:ye,to:ye+fe},url:Ri}),ye+=fe}$r=ye,wr=it(Re,{...je,segmentNumber:ht.toString(10),segmentTime:ye.toString(10)})}let ho={time:{from:$r,to:1/0},url:wr};xr={type:"template",baseUrl:ve,segmentTemplateUrl:Re,initUrl:Ar,totalSegmentsDurationMs:pt,segments:wt,nextSegmentBeyondManifest:ho,timescale:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!U||!ut)continue;let kr={video:"video",audio:"audio",text:"text"}[U];if(!kr)continue;ae||=kr,V={id:lo,kind:kr,segmentReference:xr,profiles:co,duration:p,bitrate:lt,mime:ut,codecs:Qe,width:me,height:Le,fps:Pt,quality:ct}}x.language||=F,x.label||=W,x.mime||=ut,x.codecs||=Qe,x.hdr||=ae==="video"&&sa(Qe),x.representations.push(V)}ae&&r[ae].push(x)}return{dynamic:d,liveAvailabilityStartTime:l,duration:p,streams:r}};import{videoSizeToQuality as su}from"@vkontakte/videoplayer-shared";var en=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{let s=(a?Oe(a):void 0)??su({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},tn=({id:n,bitrate:e})=>({id:n,bitrate:e}),Ki=(n,e,t)=>{let i=e.indexOf(n);return t.at(Math.round(t.length*i/e.length))??t.at(-1)},rn=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),oa=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),da=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Ji=n=>"url"in n,rt=n=>n.type==="template",oi=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var ui=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:s,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:d}){this.currentSegmentLength$=new di(0);this.onLastSegment$=new di(!1);this.fullyBuffered$=new di(!1);this.playingRepresentation$=new di(void 0);this.playingRepresentationInit$=new di(void 0);this.error$=new ou;this.gaps=[];this.subscription=new du;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=It(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ee(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Fs(this.sourceBuffer),this.subscription.add(ua(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:at.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s}),o??={id:"SegmentEjection",category:at.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:s},this.error$.next(o)})),this.subscription.add(ua(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:at.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,ia(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=Ae(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,d<c)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Ee(i,"No init buffer for starting representation"),Ee(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=It(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);Ee(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Se(a)||Se(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Ee(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();an(s)&&(this.isLive||(r.forEach(o=>o.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=It(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let d=t.find(p=>p.id===u);d&&this.representations.set(u,d);let c=this.representations.get(u);if(!c||!rt(c.segmentReference))return;let l=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ee(r);let a=this.segments.get(i);Ee(a,"No segments for starting representation");let s=this.initData.get(i);if(Ee(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=s,this.isActiveLowLatency=o,this.isLive=!!d?.dynamic,this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Se(e)||Se(this.downloadingRepresentationId)||Se(this.playingRepresentationId)||Se(this.sourceBuffer)||!Se(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ee(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next((r?.time.to??0)-(r?.time.from??0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Ae(this.sourceBuffer.buffered,e),l=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(a=l)}if(isFinite(this.bufferLimit)&&ia(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ae(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let c=o.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Ae(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;an(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),a=this.segments.get(i.id)??[],s=a.at(-1)?.time.to??0,o=r?.findIndex(u=>Math.floor(s)>=Math.floor(u.time.from)&&Math.floor(s)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=r.slice(o+1);this.segments.set(i.id,[...a,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ee(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!rt(i))return;let r=this.segments.get(t.id)??[],a=r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to),!!!r.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),u=it(i.segmentTemplateUrl,{segmentTime:o});r.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:l,time:{from:p,to:h}},m)=>{let f=p<=i&&h>=i,S=p>i||f||m===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),B=this.preloadOnly&&p<=i+k||h<=i+k;return(l==="none"||l==="partially_ejected"&&S&&B&&this.sourceBuffer&&!Ft(this.sourceBuffer.buffered,i))&&S&&B});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(s<=d||o<=c);l++){let p=a[l];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")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:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await It(o,async function*(){let c=la(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;let l=new DataView(c);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=Tt(t.mime);r.segment.time.to=h.getSegmentEndTime(l,p)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(l,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),oi(c)||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:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await It(s,async function*(){let u=la(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),ua(window,"online").pipe(nu()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),oi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(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,c)=>{if(!a.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;let s=this.representations.get(t);if(s)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(s.mime).parseFeedableSegmentChunk(d,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,d=e.byteLength;for(let c of this.activeSegments){let{segment:l}=c,p=u==="byteRange",h=p?l.byte.to-l.byte.from+1:d;if(c.representationId!==t||!(!p||l.byte.from>=i&&l.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let f=p?l.byte.from-i:0,S=p?l.byte.to-i:e.byteLength,k=f<r,B=S<=r;if(l.status==="downloading"&&k&&B){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+f,h);this.sourceBufferTaskQueue.append(g,a).then(b=>b&&!a.aborted?this.onSegmentFullyAppended(c,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&k&&(c.loadedBytes=Math.min(h,r-f),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+f+c.feedingBytes,c.loadedBytes-c.feedingBytes),b=c.loadedBytes===h?g:Tt(o.mime).parseFeedableSegmentChunk(g);b?.byteLength&&(l.status="partially_fed",c.feedingBytes+=b.byteLength,this.sourceBufferTaskQueue.append(b,a).then(v=>{if(a.aborted)s();else if(v)c.fedBytes+=b.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;s()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let c=d.byte.from-i,l=d.byte.to-i,p=l-c+1,h=c<r,m=l<=r;if(h){if(d.status==="downloading"&&m){d.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+c,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-c),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?f:Tt(o.mime).parseFeedableSegmentChunk(f);S?.byteLength&&(d.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):s())}}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ji(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&r.time.from===e.segment.time.from&&r.time.to===e.segment.time.to&&(r.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||=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?It(this.destroyAbortController.signal,async function*(){let o=la(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:d,segments:c}=o,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l);let p=c;this.isLive&&rt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:at.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Se(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((c,l)=>c.from-l.from);let d=[u[0]];for(let c=1;c<u.length;c++){let{from:l,to:p}=u[c],h=d[d.length-1];h.to>=l?h.to=Math.max(h.to,p):d.push(u[c])}return d},o=u=>{if(a>=t)return r;r.push(u.time),r=s(r);let d=Ji(u)?u.size??0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let c=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||l)&&d.status==="fed"&&o(d)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,l=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(c)&&l++;if(l===this.segments.size){let p={time:{from:d,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let c of d)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,c)=>d||c,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Se(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,u=d=>{a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let c=Ji(d)?d.size??0:d.byte.to-d.byte.from;r+=c};for(let d of this.segments.values())for(let c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(a)&&isFinite(s),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let c=this.sourceBuffer.buffered.start(d)*1e3,l=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(c)&&Math.round(h.time.to)>=Math.round(l)){a=c,s=l;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>e+d&&l.status==="fed"&&u(l)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:at.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Se(this.sourceBuffer)||Se(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),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=s&&c.to+t>=o),d=e.filter(c=>s>=c.from-t&&s<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var li=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var sn=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ci,assertNever as nn,fromEvent as on,merge as uu,now as ca,Subscription as lu,ValueSubject as pa}from"@vkontakte/videoplayer-shared";var Xi=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new pa(void 0);this.lastConnectionReused$=new pa(void 0);this.lastRequestFirstBytes$=new pa(void 0);this.abortAllController=new AbortController;this.subscription=new lu;this.fetchManifest=ci(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=li(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(pi);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=ci(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){let d=e,c=new Headers;if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(d,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),d=A.toString();break}default:nn(t)}this.requestQuic&&(d=li(d));let l=this.abortAllController.signal,p;if(s){let A=new AbortController;if(p=uu(on(this.abortAllController.signal,"abort"),on(s,"abort")).subscribe(()=>{try{A.abort()}catch(R){pi(R)}}),this.abortAllController.signal.aborted||s.aborted)try{A.abort()}catch(R){pi(R)}l=A.signal}let h=ca(),m=yield fetch(d,{priority:a,headers:c,signal:l}).catch(pi),f=ca();if(!m)return p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(f-h),!m.ok||!m.body)return p?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!r&&!o)return p?.unsubscribe(),m.arrayBuffer();let[S,k]=m.body.tee(),B=S.getReader();o&&this.throughputEstimator?.trackStream(k,u);let g=0,b=new Uint8Array(0),v=!1,L=A=>{p?.unsubscribe(),v=!0,pi(A)},I=ci(l,async function*({done:A,value:R}){if(g===0&&this.lastRequestFirstBytes$.next(ca()-h),l.aborted){p?.unsubscribe();return}if(!A&&R){let E=new Uint8Array(b.length+R.length);E.set(b),E.set(R,b.length),b=E,g+=R.byteLength,r?.(new DataView(b.buffer),g),yield B?.read().then(I,L)}}.bind(this));return yield B?.read().then(I,L),p?.unsubscribe(),v?null:b.buffer}.bind(this));this.fetchByteRangeRepresentation=ci(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,d,c;e.indexRange&&(d=e.indexRange.from,c=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(c,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(l,m.from-s,m.to-m.from+1);else{let k=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!k)return null;f=new DataView(k)}let S=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(l),segments:S}}.bind(this));this.fetchTemplateRepresentation=ci(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}=sn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:nn(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},pi=n=>{if(!oi(n))throw n};var st=(n,e,t)=>t*e+(1-t)*n,ha=(n,e)=>n.reduce((t,i)=>t+i,0)/e,dn=(n,e,t,i)=>{let r=0,a=t,s=ha(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as cu,ValueSubject as un}from"@vkontakte/videoplayer-shared";var Fe=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new un(e.initial),this.debounced$=new un(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Y(`raw_${t}`),this.smoothedSeries$=new Y(`smoothed_${t}`),this.reportedSeries$=new Y(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(cu(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 Zi=class extends Fe{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=st(this.slow,e,this.params.emaAlphaSlow),this.fast=st(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var er=class extends Fe{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ha(this.pastMeasures,this.takenMeasures);this.emaSmoothed=st(this.emaSmoothed,e,this.params.emaAlpha);let i=dn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var tr=class extends Fe{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?st(this.smoothed,t,this.params.emaAlpha):t}};var nt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Zi({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new er({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 tr({initial:e,label:"liveEdgeDelay",...t})}};var ma=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var fn=["timeupdate","progress","play","seeked","stalled","waiting"];var ar=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new mn;this.representationSubscription=new mn;this.state$=new w("none");this.currentVideoRepresentation$=new q(void 0);this.currentVideoRepresentationInit$=new q(void 0);this.currentAudioRepresentation$=new q(void 0);this.currentVideoSegmentLength$=new q(0);this.currentAudioSegmentLength$=new q(0);this.error$=new hn;this.lastConnectionType$=new q(void 0);this.lastConnectionReused$=new q(void 0);this.lastRequestFirstBytes$=new q(void 0);this.isLive$=new q(!1);this.liveDuration$=new q(0);this.liveAvailabilityStartTime$=new q(void 0);this.bufferLength$=new q(0);this.liveLoadBufferLength$=new q(0);this.livePositionFromPlayer$=new q(0);this.timeInWaiting=0;this.isActiveLowLatency$=new q(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new hn;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=fa(this.destroyController.signal,async function*(e,t,i){this.element=e,this.manifestUrlString=j(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ue.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=fa(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ue.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=Zs(e??"",this.manifestUrlString)}catch(a){let s=Bs(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(s)}if(!t)return null;let i=(a,s,o)=>!!(this.element?.canPlayType?.(s)&&we()?.isTypeSupported?.(`${s}; codecs="${o}"`)||a==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let o=t.streams[a].filter(({mime:c,codecs:l})=>i(a,c,l)),u=new Set(o.map(({codecs:c})=>c)),d=Vs(u);if(d&&(r[a]=o.filter(({codecs:c})=>c.startsWith(d))),a==="video"){let c=this.tuning.preferHDR,l=r.video.some(h=>h.hdr),p=r.video.some(h=>!h.hdr);bu.isHDR&&c&&l?r.video=r.video.filter(h=>h.hdr):p&&(r.video=r.video.filter(h=>!h.hdr))}}return{...t,streams:r}}.bind(this));this.initRepresentations=fa(this.destroyController.signal,async function*(e,t,i){ot(this.manifest),ot(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(Et(l,"error").pipe(rr(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ue.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?ws():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Wi())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new ui("video",this.source,o,s),this.bufferManagers=[this.videoBufferManager],pn(t)){let l=this.manifest.streams.audio.reduce((p,h)=>[...p,...h.representations],[]);this.audioBufferManager=new ui("audio",this.source,l,s),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ba(1e3).subscribe(l=>{if(this.element?.paused){let p=Vr(this.manifestUrlString,2);this.manifestUrlString=j(this.manifestUrlString,p+1e3,2)}})),this.representationSubscription.add(xt(...fn.filter(l=>l!=="waiting").map(l=>Et(this.element,l))).pipe(Sa(l=>this.element?Ae(this.element.buffered,this.element.currentTime*1e3):0),cn(),rr(l=>!!l),mu(l=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(cn()).subscribe(p=>ma(this.element,1))),this.representationSubscription.add(ir({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(rr(({bufferLength:p,isActiveLowLatency:h})=>h&&!!p)).subscribe(({bufferLength:p})=>this.liveEstimatedDelay.next(p))),this.representationSubscription.add(ir({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:p,isActiveLowLatency:h})=>{if(!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,f=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,k=p-m,B=1;Math.abs(k)>f&&(B=1+Math.sign(k)*S),ma(this.element,B)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let h=0;if(p){let m=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(ir({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(fu(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:h})=>{if(ot(this.element),this.isUpdatingLive)return;let m=this.element.playbackRate,f=Vr(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),B=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,b=isFinite(p)?p:h,v=this.isActiveLowLatency$.getValue(),L=S<=this.tuning.live.activeLiveDelay&&f===0;this.isActiveLowLatency$.next(v&&L);let I="none";if(v?I="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&L?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(A=>A.proceedLowLatencyLive()),I="active_low_latency"):f!==0&&b<k?I="live_forward_buffering":b<k+g&&(I="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),I==="live_forward_buffering"||I==="live_with_target_offset"){let A=l-(k+B),R=this.normolizeLiveOffset(Math.trunc(f+A/m)),E=Math.abs(R-f),D;!p||E<=this.tuning.dashCmafLive.offsetCalculationError?D=f:R>0&&E>this.tuning.dashCmafLive.offsetCalculationError?D=R:D=0,this.manifestUrlString=j(this.manifestUrlString,D,2)}I!=="none"&&I!=="active_low_latency"&&(l=0,this.updateLive())}))}let u=xt(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(Sa(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),d=xt(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(Sa(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(xt(this.forceEnded$,ir({allBuffersFull:u,someBufferEnded:d}).pipe(rr(({allBuffersFull:l,someBufferEnded:p})=>l&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(xt(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(l=>this.source?.addEventListener("sourceopen",l)));let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(l=>l.representations).flatMap(l=>l.duration??0)];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&pn(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=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ba(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ue.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Xi({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=nt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){ot(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 this.videoBufferManager?.seekLive(this.manifest?.streams.video),await this.audioBufferManager?.seekLive(this.manifest?.streams.audio))}initBuffer(){ot(this.element),this.state$.setState("running"),this.subscription.add(xt(...fn.map(e=>Et(this.element,e)),Et(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ue.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Et(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Et(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ft(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{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 t=this.element.currentTime*1e3;this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)}}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=ba(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){ot(this.element),ot(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Ft(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;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 sr=class{constructor(e,t){this.fov=e,this.orientation=t}};var nr=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var bn=`attribute vec2 a_vertex;
59
38
  attribute vec2 a_texel;
60
39
 
61
40
  varying vec2 v_texel;
@@ -66,7 +45,7 @@ void main(void) {
66
45
  // save texel vector to pass to fragment shader
67
46
  v_texel = a_texel;
68
47
  }
69
- `;var kn=`#ifdef GL_ES
48
+ `;var Sn=`#ifdef GL_ES
70
49
  precision highp float;
71
50
  precision highp int;
72
51
  #else
@@ -109,5 +88,5 @@ void main(void) {
109
88
  // sample using new coordinates
110
89
  gl_FragColor = texture2D(u_texture, tc);
111
90
  }
112
- `;var dr=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 nr(this.params.fov,this.params.orientation),this.cameraRotationManager=new or(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(xn,this.gl.VERTEX_SHADER),i=this.createShader(kn,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,d=e+i,c=t+r,l=e-i,p=t+r;return[a,s,o,u,d,c,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var dt=class{constructor(e){this.subscription=new Cu;this.videoState=new P("stopped");this.elementSize$=new Vu(void 0);this.textTracksManager=new le;this.droppedFramesManager=new Qi;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Dt;this.audioTrackSwitchHistory=new Dt;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let s=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-s,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&y(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Au(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=J(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(G(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=ee(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ya.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(An(d=>!!d.length),$n()).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(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(An(Lu),$n()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(wn(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ie(this.video,t.isLooped,r)),this.subscription.add(Z(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ue(this.video,t.playbackRate,i.playbackRateState$,r)),a(Du(this.video),this.elementSize$),a(pe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(Pu(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(ua(h));let m=[];for(let f of h.representations){let S=ln(f);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of c.video){l.push(la(p));let h=[];for(let m of p.representations){let f=un(m);f&&(h.push(f),this.videoTracksMap.set(f,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(l);for(let p of c.text)for(let h of p.representations){let m=cn(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:ya.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(ur(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$,$u(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(d)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,h]=l,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),d==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(s),h){let f=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,f).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to: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(Ta()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(la(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ta()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[l,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(ua(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(wn(({to:d})=>d==="ready"),Ta());this.subscription.add(ur(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(ur(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ur(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ru(["init"])).pipe(wu(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:T})=>T===r),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let d=[...this.videoStreamsMap.keys()].find(({id:T})=>T===u.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let l=we(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),f=[...this.audioStreamsMap.keys()].find(({id:T})=>T===m?.id)??this.audioStreamsMap.keys().next().value,S=0;if(f){if(s&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let T=Fi(s,c,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,T?.bitrate??-1/0)}else{let T=Ji(s,c,this.audioStreamsMap.get(f)??[]);S=Math.max(S,T?.bitrate??-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let T=Fi(o,c,this.audioStreamsMap.get(f)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,T?.bitrate??-1/0)}else{let T=Ji(o,c,this.audioStreamsMap.get(f)??[]);S=Math.max(S,T?.bitrate??-1/0)}}let k=_e(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:C}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&i&&(k=c.filter(T=>!Mu(T.quality)).sort((T,w)=>(w.bitrate??0)-(T.bitrate??0)).filter(T=>Pn(T.quality,k.quality)&&Pn(T.quality,C))[0]??k);let g=i?k??s:s??k,b;this.params.tuning.useSeparateAudioVideoABR?b=f&&Es(g,c,this.audioStreamsMap.get(f)??[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):b=f&&Ji(g,c,this.audioStreamsMap.get(f)??[]);let v=this.videoTracksMap.get(g)?.representation,L=b&&this.audioTracksMap.get(b)?.representation;if(v&&L)return[v,L];if(v&&!L&&this.audioTracksMap.size===0)return[v,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){te(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ya.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),X(this.video)}};var fi=class extends dt{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 Ln,interval as Bu,map as Ou}from"@vkontakte/videoplayer-shared";var bi=class extends dt{constructor(e){super(e),this.liveOffset=new Ae}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(Ln({interval:Bu(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()==="playing"){let a=e.position$.getValue()+(r-1);a<=0&&e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(Ln({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Ou(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(s,r)})}};import{assertNever as Si,assertNonNullable as Mn,debounce as Nu,ErrorCategory as lr,filter as _u,isNonNullable as Fu,isNullable as Uu,map as cr,merge as Hu,Observable as Gu,observableFrom as Qu,Subscription as ju,videoSizeToQuality as Wu}from"@vkontakte/videoplayer-shared";var ve={};var kt=(n,e)=>new Gu(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),gi=class{constructor(e){this.subscription=new ju;this.videoState=new P("initializing");this.textTracksManager=new le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Si(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Si(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Si(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Si(e)}break;default:Si(t)}};this.video=J(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),X(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:lr.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(ve.Hls=r.default,ve.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){Mn(ve.Hls,"hls.js not loaded"),this.hls=new ve.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Mn(ve.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:lr.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ee(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ie(this.video,e.isLooped,i)),this.subscription.add(Z(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ue(this.video,e.playbackRate,r.playbackRateState$,i)),a(pe(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(cr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(kt(this.hls,ve.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:lr.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(kt(this.hls,ve.Events.MANIFEST_PARSED).pipe(cr(({levels:d})=>d.reduce((c,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,f=Ne(l.attrs.QUALITY??"")??Wu({width:h,height:m});if(!f)return c;let S=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,k={id:p.toString(),quality:f,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:k,level:l}),c.push(k),c},[]))),t.availableVideoTracks$),a(kt(this.hls,ve.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let c=[];for(let l of d.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),a(kt(this.hls,ve.Events.LEVEL_LOADING).pipe(cr(({url:d})=>G(d))),t.hostname$),a(kt(this.hls,ve.Events.FRAG_CHANGED),d=>{let{video:c,audio:l}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(Ve(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>Array.from(this.trackLevels.values()).find(({level:c})=>c===d)?.track,o=kt(this.hls,ve.Events.LEVEL_SWITCHED).pipe(cr(({level:d})=>s(this.hls.levels[d])));o.pipe(_u(Fu)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ve(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{if(Uu(d))return;let c=this.trackLevels.get(d.id)?.level;if(!c)return;let l=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=Hu(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Qu(["init"])).pipe(Nu(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 te(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lr.DOM,thrown:t}))||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0)}};var Rn="X-Playback-Duration",Ia=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(Rn)?parseInt(e.headers.get(Rn),10):void 0};import{assertNever as Xu,combine as Zu,debounce as el,ErrorCategory as hr,filter as tl,filterChanged as il,isNonNullable as Cn,isNullable as mr,map as Vn,merge as rl,observableFrom as al,Subscription as sl,ValueSubject as xa,VideoQuality as nl}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as Yu,getExponentialDelay as qu}from"@vkontakte/videoplayer-shared";var zu=n=>{let e=null;if(n.QUALITY&&(e=Ne(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Yu({width:t,height:i})}return e??null},Ku=(n,e)=>{let t=n.split(`
113
- `),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),u=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let d=Object.fromEntries(o[1].split(",").map(S=>S.split("="))),c=d.QUALITY??`stream-${d.BANDWIDTH}`,l=zu(d),p;d.BANDWIDTH&&(p=parseInt(d.BANDWIDTH,10)/1e3||void 0),!p&&d["AVERAGE-BANDWIDTH"]&&(p=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,m;if(d.RESOLUTION){let[S,k]=d.RESOLUTION.split("x").map(C=>parseInt(C,10));S&&k&&(m={width:S,height:k})}let f=new URL(t[++a],e).toString();l&&i.push({id:c,quality:l,url:f,bandwidth:p,size:m,fps:h})}if(u){let d=Object.fromEntries(u[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=d.URI?.replace(/playlist$/,"subtitles.vtt"),l=d.LANGUAGE,p=d.NAME;c&&l&&r.push({type:"internal",id:l,label:p,language:l,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Ju=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Ea=0,Dn=async(n,e=n,t)=>{let r=await(await fetch(n)).text();Ea+=1;try{let{qualityManifests:a,textTracks:s}=Ku(r,e);return{qualityManifests:a,textTracks:s}}catch{if(Ea<=t.manifestRetryMaxCount)return await Ju(qu(Ea-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Dn(n,e,t)}return{qualityManifests:[],textTracks:[]}},pr=Dn;var vi=class{constructor(e){this.subscription=new sl;this.videoState=new P("stopped");this.textTracksManager=new le;this.manifests$=new xa([]);this.liveOffset=new Ae;this.manifestStartTime$=new xa(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(y(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Xu(t)}};this.params=e,this.video=J(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nl.INVARIANT,url:this.params.source.url},pr(W(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:hr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:hr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.maxSeekBackTime$=new xa(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:hr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Z(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ue(this.video,t.playbackRate,r.playbackRateState$,i)),a(pe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(il(),Vn(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Cn(d.to)){let l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Zu({startTime:this.manifestStartTime$.pipe(tl(Cn)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Vn(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:p})=>({id:u,quality:d,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let s=rl(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,al(["init"])).pipe(el(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),X(this.video)}prepare(){let e=this.selectManifest();if(mr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[d,c]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(d||""));c&&d&&r.searchParams.set(c,l)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=W(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),Ia(s).then(o=>{if(!mr(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(mr(u)||!isFinite(u))try{fetch(s).then(d=>d.text()).then(d=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(c){let l=new URL(c,s).toString();Ia(l).then(p=>{mr(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){te(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hr.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 ol,debounce as dl,ErrorCategory as ka,fromEvent as Aa,isNonNullable as ul,isNullable as ll,map as Bn,merge as On,observableFrom as Nn,Subscription as cl,ValueSubject as pl,VideoQuality as hl,clientChecker as ml}from"@vkontakte/videoplayer-shared";var yi=class{constructor(e){this.subscription=new cl;this.videoState=new P("stopped");this.textTracksManager=new le;this.manifests$=new pl([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return ol(t)}};this.params=e,this.video=J(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:hl.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),pr(W(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:ka.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ka.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(Bn(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ie(this.video,t.isLooped,i)),this.subscription.add(Z(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ue(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&ul(d.to)){let l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(h),f.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(Bn(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:p})=>({id:u,quality:d,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!ml.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(On(Aa(o,"addtrack"),Aa(o,"removetrack"),Aa(o,"change"),Nn(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=On(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Nn(["init"])).pipe(dl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),X(this.video)}prepare(){let e=this.selectManifest();if(ll(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:s}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[s,"lq"]]){let d=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){te(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ka.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as fl,assertNonNullable as _n,debounce as bl,ErrorCategory as Fn,isHigher as Sl,isHigherOrEqual as gl,isInvariantQuality as Un,isLowerOrEqual as vl,isNonNullable as yl,merge as Tl,observableFrom as Il,Subscription as El,map as xl}from"@vkontakte/videoplayer-shared";var Ti=class{constructor(e){this.subscription=new El;this.videoState=new P("stopped");this.trackUrls={};this.textTracksManager=new le;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),s.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[s.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?y(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return fl(e)}};this.params=e,this.video=J(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Fn.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(xl(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ie(this.video,t.isLooped,i)),this.subscription.add(Z(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ue(this.video,t.playbackRate,r.playbackRateState$,i)),a(pe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&yl(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(u!==d){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=Tl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Il(["init"])).pipe(bl(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),X(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;_n(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];_n(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ci(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){te(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!Un(o.track.quality)&&vl(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&gl(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(d=>!Un(d.track.quality)&&Sl(d.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=_e(r,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as Gn,debounce as wl,merge as Qn,observableFrom as $l,Subscription as Ll,map as jn,ValueSubject as Ml,ErrorCategory as wa,VideoQuality as Rl}from"@vkontakte/videoplayer-shared";import{ErrorCategory as kl}from"@vkontakte/videoplayer-shared";var Hn=["stun:videostun.mycdn.me:80"],Al=1e3,Pl=3,Pa=()=>null,fr=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=Pa;this.externalStopCallback=Pa;this.externalErrorCallback=Pa;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:Hn}]};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:kl.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Al)}normalizeOptions(e={}){let t={stunServerList:Hn,maxRetryNumber:Pl,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ii=class{constructor(e){this.videoState=new P("stopped");this.maxSeekBackTime$=new Ml(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Gn(e)}};this.subscription=new Ll,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=J(e.container,e.tuning),this.liveStreamClient=new fr(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),X(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:wa.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};Qn(this.videoState.stateChangeStarted$.pipe(jn(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(jn(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=ee(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(pe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Z(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 Gn(s.to)}},i)).add(Qn(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,$l(["init"])).pipe(wl(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Rl.INVARIANT}),this.video.srcObject=e,y(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:wa.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){te(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wa.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ei=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 Ai,assertNonNullable as He,ErrorCategory as Sr,filter as _l,isNonNullable as Jn,isNullable as Fl,map as Ul,merge as Hl,once as Gl,Subject as ne,Subscription as Xn,ValueSubject as $}from"@vkontakte/videoplayer-shared";import{Observable as Dl,map as Wn,Subscription as Cl,Subject as Vl}from"@vkontakte/videoplayer-shared";var Yn=n=>new Dl(e=>{let t=new Cl,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(Wn(({from:d,to:c})=>`${d}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(Wn(({type:d})=>d!==void 0)),s=new Vl,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as qn,Subscription as Bl,combine as Ol,filter as zn,once as Kn}from"@vkontakte/videoplayer-shared";var xi=null,br=null;function $a(){return xi||(xi=new(window.AudioContext||window.webkitAudioContext)),br||(br=new GainNode(xi,{gain:1}),br.connect(xi.destination)),{audioCtx:xi,gainNode:br}}import{clientChecker as Nl}from"@vkontakte/videoplayer-shared";var ki=class n{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Bl;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(zn(s=>!!s.type),Kn()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Nl.isSafari&&e!=="MPEG"||this.subscriptions.add(Ol({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(zn(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),Kn()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=$a(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${n.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(s){this.volumeMultiplierError$.next({id:n.errorId,category:qn.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:s})}}).catch(s=>{this.volumeMultiplierError$.next({id:n.errorId,category:qn.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=$a();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Ql={chunkDuration:5e3,maxParallelRequests:5},Pi=class{constructor(e){this.current$=new $({type:void 0});this.providerError$=new ne;this.noAvailableProvidersError$=new ne;this.volumeMultiplierError$=new ne;this.providerOutput={position$:new $(0),duration$:new $(1/0),volume$:new $({muted:!1,volume:1}),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableVideoTracks$:new $([]),currentVideoTrack$:new $(void 0),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0),isAudioAvailable$:new $(!0),autoVideoTrackLimitingAvailable$:new $(!1),autoVideoTrackLimits$:new $(void 0),currentBuffer$:new $(void 0),isBuffering$:new $(!0),error$:new ne,warning$:new ne,willSeekEvent$:new ne,seekedEvent$:new ne,loopedEvent$:new ne,endedEvent$:new ne,firstBytesEvent$:new ne,loadedMetadataEvent$:new ne,firstFrameEvent$:new ne,canplay$:new ne,isLive$:new $(void 0),isLowLatency$:new $(!1),canChangePlaybackSpeed$:new $(!0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),inPiP$:new $(!1),inFullscreen$:new $(!1),element$:new $(void 0),elementVisible$:new $(!0),availableSources$:new $(void 0),is3DVideo$:new $(!1),playbackState$:new $("")};this.subscription=new Xn;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Fs([...Hs(this.params.tuning),...Us(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>Jn(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Ei(a);let s=[...ta(!0),...ta(!1)];this.chromecastFormatsIterator=new Ei(s.filter(o=>Jn(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ki(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Fl(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Sr.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 Ai(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return He(o),new fi({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return He(o),new bi({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return He(o),gt||!this.params.tuning.useHlsJs?new yi({...s,source:o}):new gi({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return He(o),new vi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return He(o),new Ti({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return He(o),new Cs({...s,source:o,config:{...Ql,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return He(o),new Ii({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ai(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return He(o),new $t({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Ai(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ai(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 Ai(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 Xn,t=!1,i=0;return e.add(Hl(this.providerOutput.error$,Yn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Ul(r=>({id:`ProviderHangup:${r}`,category:Sr.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(_l(({to:a})=>a==="playing"),Gl()).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===Sr.NETWORK,o=r.category===Sr.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}})),e}};import{fromEvent as gr,once as jl,combine as Wl,Subscription as Zn,ValueSubject as La,map as Yl,filter as ql,isNonNullable as vr,now as oe,safeStorage as Ma}from"@vkontakte/videoplayer-shared";var zl=5e3,eo="one_video_throughput",to="one_video_rtt",wi=window.navigator.connection,io=()=>{let n=wi?.downlink;if(vr(n)&&n!==10)return n*1e3},ro=()=>{let n=wi?.rtt;if(vr(n)&&n!==3e3)return n},ao=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Ra=class n{constructor(e){this.subscription=new Zn;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(eo)||(e.useBrowserEstimation?io():void 0)||zl,i=n.load(to)??(e.useBrowserEstimation?ro():void 0)??0;if(this.throughput$=new La(t),this.rtt$=new La(i),this.rttAdjustedThroughput$=new La(ao(t,i,e.rttPenaltyRequestSize)),this.throughput=nt.getSmoothedValue(t,-1,e),this.rtt=nt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=io();s&&this.throughput.next(s);let o=ro();vr(o)&&this.rtt.next(o)};wi&&"onchange"in wi&&this.subscription.add(gr(wi,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Ma.set(eo,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Ma.set(to,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Wl({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Yl(({throughput:r,rtt:a})=>ao(r,a,e.rttPenaltyRequestSize)),ql(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=oe(),r=new Zn;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(gr(e,"progress").pipe(jl()).subscribe(a=>{t=a.loaded,i=oe()}));break;case 1:case 0:r.add(gr(e,"loadstart").subscribe(()=>{t=0,i=oe()}));break}r.add(gr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=oe(),u=s-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=oe(),s=0,o=oe(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=async({done:c,value:l})=>{if(c)!t&&this.addRawSpeed(r,oe()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=oe();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(s,m,1,t),s=l.byteLength,a=oe()}else s+=l.byteLength;o=oe()}else r+=l.byteLength,s+=l.byteLength,s>=this.tuningConfig.streamMinSampleSize&&oe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,oe()-o,this.concurrentDownloads.size),s=0,o=oe());await i?.read().then(d,u)}};this.concurrentDownloads.add(e),i?.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Ma.get(e);if(vr(t))return parseInt(t,10)??void 0}},so=Ra;import{fillWithDefault as Kl,VideoQuality as no}from"@vkontakte/videoplayer-shared";var oo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:no.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:no.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,useSeparateAudioVideoABR:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},uo=n=>({...Kl(n,oo),configName:[...n.configName??[],...oo.configName]});import{assertNonNullable as yr,combine as Tr,ErrorCategory as Ir,filter as $i,filterChanged as he,fromEvent as Ca,isNonNullable as rc,isNullable as ac,Logger as sc,map as M,mapTo as ho,merge as Ge,now as Er,once as Le,Subject as N,Subscription as mo,tap as fo,ValueSubject as E,isHigher as nc,isInvariantQuality as bo}from"@vkontakte/videoplayer-shared";import{merge as Jl,map as Xl,filter as lo,isNonNullable as Zl}from"@vkontakte/videoplayer-shared";var Da=({seekState:n,position$:e})=>Jl(n.stateChangeEnded$.pipe(Xl(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),lo(Zl)),e.pipe(lo(()=>n.getState().state==="none")));import{assertNonNullable as ec}from"@vkontakte/videoplayer-shared";var co=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return ec(e,`Wrong container or containerId {${n.container}}`),e};import{filter as tc,once as ic}from"@vkontakte/videoplayer-shared";var po=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(tc(r=>r.length>0),ic()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var xr=class{constructor(e={configName:[]}){this.subscription=new mo;this.logger=new sc;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new P("stopped"),seekState:new P({state:"none"}),volume:new P({volume:1,muted:!1}),videoTrack:new P(void 0),videoStream:new P(void 0),audioStream:new P(void 0),autoVideoTrackSwitching:new P(!0),autoVideoTrackLimits:new P({}),isLooped:new P(!1),playbackRate:new P(1),externalTextTracks:new P([]),internalTextTracks:new P([]),currentTextTrack:new P(void 0),textTrackCuesSettings:new P({}),cameraOrientation:new P({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,loadedMetadata$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:ms};if(this.initLogs(),this.tuning=uo(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Oi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new so(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(o){let u=s.map(l=>JSON.stringify(l,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Ir.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=co(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Pi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.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&&!Nt()?Ca(document,"visibilitychange").pipe(Le()).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){yr(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),Le()).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){yr(this.providerContainer);let t=this.providerContainer?.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){return po(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.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(ac(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return rc(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe($i(({from:e})=>e==="stopped"),Le()).subscribe(()=>{this.initedAt=Er(),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:Ir.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(M(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(M(s=>s.destination),he()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(M(s=>s.map(({quality:o})=>o).sort((o,u)=>bo(o)?1:bo(u)?-1:nc(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(he()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(he()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(he()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(s=>{this.desiredState.autoVideoTrackLimits.setState(s??{})})).add(e.providerOutput.currentBuffer$.pipe(M(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Tr({hasLiveOffsetByPaused:Ge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(s=>s.to),he(),M(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Tr({atLiveEdge:Tr({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Da({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(M(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),he(),fo(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(M(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(Tr({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(M(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),he(),fo(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(M(s=>s.muted),he()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(M(s=>s.volume),he()).subscribe(this.info.volume$)).add(Da({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ge(e.providerOutput.endedEvent$.pipe(ho(!0)),e.providerOutput.seekedEvent$.pipe(ho(!1))).pipe(he()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(M(s=>({id:s?`No${s}`:"NoProviders",category:Ir.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(Le(),M(s=>s??Er()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Le(),M(()=>Er()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Le(),M(()=>Er()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe($i(({to:s})=>s==="playing"),Le()).subscribe(()=>i.next(!1)));let r=0,a=Ge(e.providerOutput.isBuffering$,t,i).pipe(M(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),he());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(Ge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),l;c==="CONNECTED"?l="second_screen":u?d?s?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(M(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new mo;this.subscription.add(t),this.subscription.add(e.current$.pipe(he((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe($i(i=>i.length>0),Le()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=_e(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(Ge(this.desiredState.videoTrack.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(M(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;yr(this.providerContainer),yr(e),hs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ps(t)),this.providerContainer.current$.subscribe(({type:t})=>Rt("provider",t)),e.duration$.subscribe(t=>Rt("duration",t)),e.availableVideoTracks$.pipe($i(t=>!!t.length),Le()).subscribe(t=>Rt("tracks",t)),this.events.fatalError$.subscribe(new Y("fatalError")),this.events.managedError$.subscribe(new Y("managedError")),e.position$.subscribe(new Y("position")),e.currentVideoTrack$.pipe(M(t=>t?.quality)).subscribe(new Y("quality")),this.info.currentBuffer$.subscribe(new Y("buffer")),e.isBuffering$.subscribe(new Y("isBuffering"))].forEach(t=>this.subscription.add(t)),Rt("codecs",_s())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ir.DOM,message:String(r)})})};this.subscription.add(Ge(Ca(document,"visibilitychange"),Ca(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);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 fx,Observable as bx,Subject as Sx,ValueSubject as gx,VideoQuality as vx}from"@vkontakte/videoplayer-shared";var yx=`@vkontakte/videoplayer-core@${Ba}`;export{Vi as ChromecastState,Rr as HttpConnectionType,bx as Observable,K as PlaybackState,xr as Player,yx as SDK_VERSION,Sx as Subject,fx as Subscription,Dr as Surface,Ba as VERSION,gx as ValueSubject,Ce as VideoFormat,vx as VideoQuality};
91
+ `;var or=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 sr(this.params.fov,this.params.orientation),this.cameraRotationManager=new nr(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(bn,this.gl.VERTEX_SHADER),i=this.createShader(Sn,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,d=e+i,c=t+r,l=e-i,p=t+r;return[a,s,o,u,d,c,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var dt=class{constructor(e){this.subscription=new $u;this.videoState=new w("stopped");this.elementSize$=new Lu(void 0);this.textTracksManager=new ue;this.droppedFramesManager=new Gi;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ni;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let s=this.liveOffset?.getTotalPausedTime()??0;this.seek(r.position-s,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&y(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Tu(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new or(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=J(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(G(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ar({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=ee(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ga.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(gn(d=>!!d.length),Tn()).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(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(gn(ku),Tn()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(yn(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Te(this.video,t.isLooped,r)),this.subscription.add(Z(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(de(this.video,t.playbackRate,i.playbackRateState$,r)),a(wu(this.video),this.elementSize$),a(ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(Iu(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(oa(h));let m=[];for(let f of h.representations){let S=tn(f);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let l=[];for(let p of c.video){l.push(da(p));let h=[];for(let m of p.representations){let f=en(m);f&&(h.push(f),this.videoTracksMap.set(f,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(l);for(let p of c.text)for(let h of p.representations){let m=rn(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:ga.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(dr(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$,xu(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(d)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoAudioRepresentations();if(!l)return;let[p,h]=l,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),d==="manifest_ready")this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(s),h){let f=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,f).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to: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(va()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[l,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(l),e.currentVideoStream$.next(da(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(va()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[l,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(oa(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(yn(({to:d})=>d==="ready"),va());this.subscription.add(dr(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add(dr(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=dr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Au(["init"])).pipe(Eu(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=e.videoTrack.getState()?.id,s=[...this.videoTracksMap.keys()].find(({id:I})=>I===r),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(s&&this.videoTracksMap.get(s)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let d=[...this.videoStreamsMap.keys()].find(({id:I})=>I===u.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let l=Ae(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(l/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),f=[...this.audioStreamsMap.keys()].find(({id:I})=>I===m?.id)??this.audioStreamsMap.keys().next().value,S=0;if(f){if(s&&!i){let I=Ki(s,c,this.audioStreamsMap.get(f)??[]);S=Math.max(S,I?.bitrate??-1/0)}if(o){let I=Ki(o,c,this.audioStreamsMap.get(f)??[]);S=Math.max(S,I?.bitrate??-1/0)}}let k=Ne(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:B}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&i&&(k=c.filter(I=>!Pu(I.quality)).sort((I,A)=>(A.bitrate??0)-(I.bitrate??0)).filter(I=>vn(I.quality,k.quality)&&vn(I.quality,B))[0]??k);let g=i?k??s:s??k,b=f&&Ki(g,c,this.audioStreamsMap.get(f)??[]),v=this.videoTracksMap.get(g)?.representation,L=b&&this.audioTracksMap.get(b)?.representation;if(v&&L)return[v,L];if(v&&!L&&this.audioTracksMap.size===0)return[v,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){te(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ga.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),X(this.video)}};var mi=class extends dt{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 In,interval as Mu,map as Ru}from"@vkontakte/videoplayer-shared";var fi=class extends dt{constructor(e){super(e),this.liveOffset=new ke}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(In({interval:Mu(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{if(this.videoState.getState()==="playing"){let a=e.position$.getValue()+(r-1);a<=0&&e.position$.next(a),this.liveOffset?.resetTo(-a*1e3)}})).add(In({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Ru(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(s,r)})}};import{assertNever as bi,assertNonNullable as En,debounce as Du,ErrorCategory as ur,filter as Cu,isNonNullable as Vu,isNullable as Bu,map as lr,merge as Ou,Observable as _u,observableFrom as Nu,Subscription as Fu,videoSizeToQuality as Uu}from"@vkontakte/videoplayer-shared";var ge={};var kt=(n,e)=>new _u(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Si=class{constructor(e){this.subscription=new Fu;this.videoState=new w("initializing");this.textTracksManager=new ue;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:bi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:bi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:bi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:bi(e)}break;default:bi(t)}};this.video=J(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),X(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:ur.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||(ge.Hls=r.default,ge.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){En(ge.Hls,"hls.js not loaded"),this.hls=new ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){En(ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:ur.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ee(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Te(this.video,e.isLooped,i)),this.subscription.add(Z(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(de(this.video,e.playbackRate,r.playbackRateState$,i)),a(ce(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(lr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(kt(this.hls,ge.Events.ERROR).subscribe(d=>{d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:ur.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${d.err?.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(kt(this.hls,ge.Events.MANIFEST_PARSED).pipe(lr(({levels:d})=>d.reduce((c,l)=>{let p=l.name||l.height.toString(10),{width:h,height:m}=l,f=Oe(l.attrs.QUALITY??"")??Uu({width:h,height:m});if(!f)return c;let S=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,k={id:p.toString(),quality:f,bitrate:l.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:k,level:l}),c.push(k),c},[]))),t.availableVideoTracks$),a(kt(this.hls,ge.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let c=[];for(let l of d.subtitleTracks){let p=l.name,h=l.attrs.URI||"",m=l.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),a(kt(this.hls,ge.Events.LEVEL_LOADING).pipe(lr(({url:d})=>G(d))),t.hostname$),a(kt(this.hls,ge.Events.FRAG_CHANGED),d=>{let{video:c,audio:l}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((l?.endPTS??0)-(l?.startPTS??0))*1e3)}),this.subscription.add(Ce(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>Array.from(this.trackLevels.values()).find(({level:c})=>c===d)?.track,o=kt(this.hls,ge.Events.LEVEL_SWITCHED).pipe(lr(({level:d})=>s(this.hls.levels[d])));o.pipe(Cu(Vu)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ce(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{if(Bu(d))return;let c=this.trackLevels.get(d.id)?.level;if(!c)return;let l=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=Ou(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Nu(["init"])).pipe(Du(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 te(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ur.DOM,thrown:t}))||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0)}};var xn="X-Playback-Duration",ya=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(xn)?parseInt(e.headers.get(xn),10):void 0};import{assertNever as Yu,combine as qu,debounce as zu,ErrorCategory as pr,filter as Ku,filterChanged as Ju,isNonNullable as Pn,isNullable as hr,map as An,merge as Xu,observableFrom as Zu,Subscription as el,ValueSubject as Ia,VideoQuality as tl}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as Hu,getExponentialDelay as Gu}from"@vkontakte/videoplayer-shared";var Qu=n=>{let e=null;if(n.QUALITY&&(e=Oe(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Hu({width:t,height:i})}return e??null},Wu=(n,e)=>{let t=n.split(`
92
+ `),i=[],r=[];for(let a=0;a<t.length;a++){let s=t[a],o=s.match(/^#EXT-X-STREAM-INF:(.+)/),u=s.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let d=Object.fromEntries(o[1].split(",").map(S=>S.split("="))),c=d.QUALITY??`stream-${d.BANDWIDTH}`,l=Qu(d),p;d.BANDWIDTH&&(p=parseInt(d.BANDWIDTH,10)/1e3||void 0),!p&&d["AVERAGE-BANDWIDTH"]&&(p=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,m;if(d.RESOLUTION){let[S,k]=d.RESOLUTION.split("x").map(B=>parseInt(B,10));S&&k&&(m={width:S,height:k})}let f=new URL(t[++a],e).toString();l&&i.push({id:c,quality:l,url:f,bandwidth:p,size:m,fps:h})}if(u){let d=Object.fromEntries(u[1].split(",").map(h=>h.split("=")).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=d.URI?.replace(/playlist$/,"subtitles.vtt"),l=d.LANGUAGE,p=d.NAME;c&&l&&r.push({type:"internal",id:l,label:p,language:l,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},ju=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Ta=0,kn=async(n,e=n,t)=>{let r=await(await fetch(n)).text();Ta+=1;try{let{qualityManifests:a,textTracks:s}=Wu(r,e);return{qualityManifests:a,textTracks:s}}catch{if(Ta<=t.manifestRetryMaxCount)return await ju(Gu(Ta-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),kn(n,e,t)}return{qualityManifests:[],textTracks:[]}},cr=kn;var gi=class{constructor(e){this.subscription=new el;this.videoState=new w("stopped");this.textTracksManager=new ue;this.manifests$=new Ia([]);this.liveOffset=new ke;this.manifestStartTime$=new Ia(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(y(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Yu(t)}};this.params=e,this.video=J(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:tl.INVARIANT,url:this.params.source.url},cr(j(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:pr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:pr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.maxSeekBackTime$=new Ia(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:pr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Z(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(de(this.video,t.playbackRate,r.playbackRateState$,i)),a(ce(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(Ju(),An(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Pn(d.to)){let l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(qu({startTime:this.manifestStartTime$.pipe(Ku(Pn)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(An(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:p})=>({id:u,quality:d,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let s=Xu(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Zu(["init"])).pipe(zu(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),X(this.video)}prepare(){let e=this.selectManifest();if(hr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[d,c]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(d||""));c&&d&&r.searchParams.set(c,l)}}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(),ya(s).then(o=>{if(!hr(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(hr(u)||!isFinite(u))try{fetch(s).then(d=>d.text()).then(d=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(c){let l=new URL(c,s).toString();ya(l).then(p=>{hr(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){te(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category: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 il,debounce as rl,ErrorCategory as Ea,fromEvent as xa,isNonNullable as al,isNullable as sl,map as wn,merge as $n,observableFrom as Ln,Subscription as nl,ValueSubject as ol,VideoQuality as dl,clientChecker as ul}from"@vkontakte/videoplayer-shared";var vi=class{constructor(e){this.subscription=new nl;this.videoState=new w("stopped");this.textTracksManager=new ue;this.manifests$=new ol([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?y(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return il(t)}};this.params=e,this.video=J(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:dl.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),cr(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:Ea.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Ea.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(wn(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Te(this.video,t.isLooped,i)),this.subscription.add(Z(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(de(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&al(d.to)){let l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(h=>h.id===l);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(G(p.url));let h=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(h!==m){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(h),f.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(wn(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:p})=>({id:u,quality:d,size:c,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!ul.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add($n(xa(o,"addtrack"),xa(o,"removetrack"),xa(o,"change"),Ln(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=$n(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ln(["init"])).pipe(rl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),X(this.video)}prepare(){let e=this.selectManifest();if(sl(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:s}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[s,"lq"]]){let d=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){te(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ea.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as ll,assertNonNullable as Mn,debounce as cl,ErrorCategory as Rn,isHigher as pl,isHigherOrEqual as hl,isInvariantQuality as Dn,isLowerOrEqual as ml,isNonNullable as fl,merge as bl,observableFrom as Sl,Subscription as gl,map as vl}from"@vkontakte/videoplayer-shared";var yi=class{constructor(e){this.subscription=new gl;this.videoState=new w("stopped");this.trackUrls={};this.textTracksManager=new ue;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),s.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[s.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?y(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return ll(e)}};this.params=e,this.video=J(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Rn.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ee(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(vl(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Te(this.video,t.isLooped,i)),this.subscription.add(Z(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(de(this.video,t.playbackRate,r.playbackRateState$,i)),a(ce(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),y(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),y(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&fl(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(u!==d){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=bl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Sl(["init"])).pipe(cl(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),X(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Mn(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Mn(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=li(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(G(t))}playIfAllowed(){te(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Rn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let r=Object.values(this.trackUrls).find(o=>!Dn(o.track.quality)&&ml(o.track.quality,e))?.track,a=this.params.desiredState.videoTrack.getState()?.id,s=this.trackUrls[a??"0"]?.track;if(r&&s&&hl(s.quality,r.quality)&&(t=r),!t){let o=Object.values(this.trackUrls).filter(d=>!Dn(d.track.quality)&&pl(d.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let r=Object.values(this.trackUrls).map(a=>a.track);t=Ne(r,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as Vn,debounce as El,merge as Bn,observableFrom as xl,Subscription as kl,map as On,ValueSubject as Pl,ErrorCategory as Pa,VideoQuality as Al}from"@vkontakte/videoplayer-shared";import{ErrorCategory as yl}from"@vkontakte/videoplayer-shared";var Cn=["stun:videostun.mycdn.me:80"],Tl=1e3,Il=3,ka=()=>null,mr=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=ka;this.externalStopCallback=ka;this.externalErrorCallback=ka;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:Cn}]};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:yl.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Tl)}normalizeOptions(e={}){let t={stunServerList:Cn,maxRetryNumber:Il,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ti=class{constructor(e){this.videoState=new w("stopped");this.maxSeekBackTime$=new Pl(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),y(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&y(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&y(this.params.desiredState.playbackState,"paused");return;default:return Vn(e)}};this.subscription=new kl,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=J(e.container,e.tuning),this.liveStreamClient=new mr(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),X(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:Pa.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};Bn(this.videoState.stateChangeStarted$.pipe(On(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(On(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=ee(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(ce(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Z(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 Vn(s.to)}},i)).add(Bn(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,xl(["init"])).pipe(El(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(G(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Al.INVARIANT}),this.video.srcObject=e,y(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Pa.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){te(this.video).then(e=>{e||(this.videoState.setState("paused"),y(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pa.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ii=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 ki,assertNonNullable as He,ErrorCategory as br,filter as Cl,isNonNullable as Gn,isNullable as Vl,map as Bl,merge as Ol,once as _l,Subject as ne,Subscription as Qn,ValueSubject as $}from"@vkontakte/videoplayer-shared";import{Observable as wl,map as _n,Subscription as $l,Subject as Ll}from"@vkontakte/videoplayer-shared";var Nn=n=>new wl(e=>{let t=new $l,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(_n(({from:d,to:c})=>`${d}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(_n(({type:d})=>d!==void 0)),s=new Ll,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as Fn,Subscription as Ml,combine as Rl,filter as Un,once as Hn}from"@vkontakte/videoplayer-shared";var Ei=null,fr=null;function Aa(){return Ei||(Ei=new(window.AudioContext||window.webkitAudioContext)),fr||(fr=new GainNode(Ei,{gain:1}),fr.connect(Ei.destination)),{audioCtx:Ei,gainNode:fr}}import{clientChecker as Dl}from"@vkontakte/videoplayer-shared";var xi=class n{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Ml;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(Un(s=>!!s.type),Hn()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){Dl.isSafari&&e!=="MPEG"||this.subscriptions.add(Rl({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Un(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),Hn()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=Aa(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${n.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(s){this.volumeMultiplierError$.next({id:n.errorId,category:Fn.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:s})}}).catch(s=>{this.volumeMultiplierError$.next({id:n.errorId,category:Fn.VIDEO_PIPELINE,message:s?.message??"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=Aa();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};var Nl={chunkDuration:5e3,maxParallelRequests:5},Pi=class{constructor(e){this.current$=new $({type:void 0});this.providerError$=new ne;this.noAvailableProvidersError$=new ne;this.volumeMultiplierError$=new ne;this.providerOutput={position$:new $(0),duration$:new $(1/0),volume$:new $({muted:!1,volume:1}),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableVideoTracks$:new $([]),currentVideoTrack$:new $(void 0),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0),isAudioAvailable$:new $(!0),autoVideoTrackLimitingAvailable$:new $(!1),autoVideoTrackLimits$:new $(void 0),currentBuffer$:new $(void 0),isBuffering$:new $(!0),error$:new ne,warning$:new ne,willSeekEvent$:new ne,seekedEvent$:new ne,loopedEvent$:new ne,endedEvent$:new ne,firstBytesEvent$:new ne,loadedMetadataEvent$:new ne,firstFrameEvent$:new ne,canplay$:new ne,isLive$:new $(void 0),isLowLatency$:new $(!1),canChangePlaybackSpeed$:new $(!0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),inPiP$:new $(!1),inFullscreen$:new $(!1),element$:new $(void 0),elementVisible$:new $(!0),availableSources$:new $(void 0),is3DVideo$:new $(!1),playbackState$:new $("")};this.subscription=new Qn;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Rs([...Cs(this.params.tuning),...Ds(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>Gn(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Ii(a);let s=[...Zr(!0),...Zr(!1)];this.chromecastFormatsIterator=new Ii(s.filter(o=>Gn(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new xi(this.providerOutput,this.current$,this.volumeMultiplierError$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Vl(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:br.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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 ki(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return He(o),new mi({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return He(o),new fi({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return He(o),gt||!this.params.tuning.useHlsJs?new vi({...s,source:o}):new Si({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return He(o),new gi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return He(o),new yi({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return He(o),new Ps({...s,source:o,config:{...Nl,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return He(o),new Ti({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ki(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return He(o),new $t({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return ki(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ki(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 ki(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 Qn,t=!1,i=0;return e.add(Ol(this.providerOutput.error$,Nn({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Bl(r=>({id:`ProviderHangup:${r}`,category:br.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Cl(({to:a})=>a==="playing"),_l()).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===br.NETWORK,o=r.category===br.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a??"SCREEN")}})),e}};import{fromEvent as Sr,once as Fl,combine as Ul,Subscription as Wn,ValueSubject as wa,map as Hl,filter as Gl,isNonNullable as gr,now as oe,safeStorage as $a}from"@vkontakte/videoplayer-shared";var Ql=5e3,jn="one_video_throughput",Yn="one_video_rtt",Ai=window.navigator.connection,qn=()=>{let n=Ai?.downlink;if(gr(n)&&n!==10)return n*1e3},zn=()=>{let n=Ai?.rtt;if(gr(n)&&n!==3e3)return n},Kn=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},La=class n{constructor(e){this.subscription=new Wn;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(jn)||(e.useBrowserEstimation?qn():void 0)||Ql,i=n.load(Yn)??(e.useBrowserEstimation?zn():void 0)??0;if(this.throughput$=new wa(t),this.rtt$=new wa(i),this.rttAdjustedThroughput$=new wa(Kn(t,i,e.rttPenaltyRequestSize)),this.throughput=nt.getSmoothedValue(t,-1,e),this.rtt=nt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let s=qn();s&&this.throughput.next(s);let o=zn();gr(o)&&this.rtt.next(o)};Ai&&"onchange"in Ai&&this.subscription.add(Sr(Ai,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{$a.set(jn,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{$a.set(Yn,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ul({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Hl(({throughput:r,rtt:a})=>Kn(r,a,e.rttPenaltyRequestSize)),Gl(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=oe(),r=new Wn;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Sr(e,"progress").pipe(Fl()).subscribe(a=>{t=a.loaded,i=oe()}));break;case 1:case 0:r.add(Sr(e,"loadstart").subscribe(()=>{t=0,i=oe()}));break}r.add(Sr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=oe(),u=s-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=oe(),s=0,o=oe(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=async({done:c,value:l})=>{if(c)!t&&this.addRawSpeed(r,oe()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=oe();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(s,m,1,t),s=l.byteLength,a=oe()}else s+=l.byteLength;o=oe()}else r+=l.byteLength,s+=l.byteLength,s>=this.tuningConfig.streamMinSampleSize&&oe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,oe()-o,this.concurrentDownloads.size),s=0,o=oe());await i?.read().then(d,u)}};this.concurrentDownloads.add(e),i?.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=$a.get(e);if(gr(t))return parseInt(t,10)??void 0}},Jn=La;import{fillWithDefault as Wl,VideoQuality as Xn}from"@vkontakte/videoplayer-shared";var Zn={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:Xn.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Xn.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},eo=n=>({...Wl(n,Zn),configName:[...n.configName??[],...Zn.configName]});import{assertNonNullable as vr,combine as yr,ErrorCategory as Tr,filter as wi,filterChanged as pe,fromEvent as Ra,isNonNullable as Xl,isNullable as Zl,Logger as ec,map as M,mapTo as ao,merge as Ge,now as Ir,once as $e,Subject as _,Subscription as so,tap as no,ValueSubject as T,isHigher as tc,isInvariantQuality as oo}from"@vkontakte/videoplayer-shared";import{merge as jl,map as Yl,filter as to,isNonNullable as ql}from"@vkontakte/videoplayer-shared";var Ma=({seekState:n,position$:e})=>jl(n.stateChangeEnded$.pipe(Yl(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),to(ql)),e.pipe(to(()=>n.getState().state==="none")));import{assertNonNullable as zl}from"@vkontakte/videoplayer-shared";var io=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return zl(e,`Wrong container or containerId {${n.container}}`),e};import{filter as Kl,once as Jl}from"@vkontakte/videoplayer-shared";var ro=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Kl(r=>r.length>0),Jl()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Er=class{constructor(e={configName:[]}){this.subscription=new so;this.logger=new ec;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new T(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new w("stopped"),seekState:new w({state:"none"}),volume:new w({volume:1,muted:!1}),videoTrack:new w(void 0),videoStream:new w(void 0),audioStream:new w(void 0),autoVideoTrackSwitching:new w(!0),autoVideoTrackLimits:new w({}),isLooped:new w(!1),playbackRate:new w(1),externalTextTracks:new w([]),internalTextTracks:new w([]),currentTextTrack:new w(void 0),textTrackCuesSettings:new w({}),cameraOrientation:new w({x:0,y:0})};this.info={playbackState$:new T("stopped"),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableVideoStreams$:new T([]),currentVideoStream$:new T(void 0),availableQualities$:new T([]),availableQualitiesFps$:new T({}),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),availableAudioStreams$:new T([]),currentAudioStream$:new T(void 0),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),canChangePlaybackSpeed$:new T(void 0),atLiveEdge$:new T(void 0),atLiveDurationEdge$:new T(void 0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T("none"),chromecastState$:new T("NOT_AVAILABLE"),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1),currentVideoSegmentLength$:new T(0),currentAudioSegmentLength$:new T(0)};this.events={inited$:new _,ready$:new _,started$:new _,playing$:new _,paused$:new _,stopped$:new _,willStart$:new _,willResume$:new _,willPause$:new _,willStop$:new _,willDestruct$:new _,watchCoverageRecord$:new _,watchCoverageLive$:new _,managedError$:new _,fatalError$:new _,ended$:new _,looped$:new _,seeked$:new _,willSeek$:new _,firstBytes$:new _,loadedMetadata$:new _,firstFrame$:new _,canplay$:new _,log$:new _};this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:ps};if(this.initLogs(),this.tuning=eo(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Bi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Jn(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(o){let u=s.map(l=>JSON.stringify(l,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Tr.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=io(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Pi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.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&&!Ot()?Ra(document,"visibilitychange").pipe($e()).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){vr(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(wi(i=>i.length>0),$e()).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){vr(this.providerContainer);let t=this.providerContainer?.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){return ro(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.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(Zl(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Xl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(wi(({from:e})=>e==="stopped"),$e()).subscribe(()=>{this.initedAt=Ir(),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:Tr.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(M(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(M(s=>s.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(M(s=>s.map(({quality:o})=>o).sort((o,u)=>oo(o)?1:oo(u)?-1:tc(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s?.quality),this.info.videoBitrate$.next(s?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(s=>{this.desiredState.autoVideoTrackLimits.setState(s??{})})).add(e.providerOutput.currentBuffer$.pipe(M(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(yr({hasLiveOffsetByPaused:Ge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(s=>s.to),pe(),M(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(yr({atLiveEdge:yr({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ma({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(M(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),pe(),no(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(M(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(yr({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(M(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),pe(),no(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(M(s=>s.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(M(s=>s.volume),pe()).subscribe(this.info.volume$)).add(Ma({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ge(e.providerOutput.endedEvent$.pipe(ao(!0)),e.providerOutput.seekedEvent$.pipe(ao(!1))).pipe(pe()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(M(s=>({id:s?`No${s}`:"NoProviders",category:Tr.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($e(),M(s=>s??Ir()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe($e(),M(()=>Ir()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe($e(),M(()=>Ir()-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 T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(wi(({to:s})=>s==="playing"),$e()).subscribe(()=>i.next(!1)));let r=0,a=Ge(e.providerOutput.isBuffering$,t,i).pipe(M(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),pe());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(Ge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.videoWidth,height:s?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s?.size?.width,height:s?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),l;c==="CONNECTED"?l="second_screen":u?d?s?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(M(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new so;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(wi(i=>i.length>0),$e()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t,i=this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Ne(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(Ge(this.desiredState.videoTrack.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(M(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;vr(this.providerContainer),vr(e),cs(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ls(t)),this.providerContainer.current$.subscribe(({type:t})=>Rt("provider",t)),e.duration$.subscribe(t=>Rt("duration",t)),e.availableVideoTracks$.pipe(wi(t=>!!t.length),$e()).subscribe(t=>Rt("tracks",t)),this.events.fatalError$.subscribe(new Y("fatalError")),this.events.managedError$.subscribe(new Y("managedError")),e.position$.subscribe(new Y("position")),e.currentVideoTrack$.pipe(M(t=>t?.quality)).subscribe(new Y("quality")),this.info.currentBuffer$.subscribe(new Y("buffer")),e.isBuffering$.subscribe(new Y("isBuffering"))].forEach(t=>this.subscription.add(t)),Rt("codecs",Ms())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Tr.DOM,message:String(r)})})};this.subscription.add(Ge(Ra(document,"visibilitychange"),Ra(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!e?.released;r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);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 lx,Observable as cx,Subject as px,ValueSubject as hx,VideoQuality as mx}from"@vkontakte/videoplayer-shared";var fx=`@vkontakte/videoplayer-core@${Ca}`;export{Ci as ChromecastState,Mr as HttpConnectionType,cx as Observable,K as PlaybackState,Er as Player,fx as SDK_VERSION,px as Subject,lx as Subscription,Rr as Surface,Ca as VERSION,hx as ValueSubject,De as VideoFormat,mx as VideoQuality};