@vkontakte/videoplayer-core 2.0.135-dev.efff7df5.0 → 2.0.135-dev.f33adad6.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,11 +1,11 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.135-dev.efff7df5.0
3
- * Fri, 20 Jun 2025 14:09:03 GMT
2
+ * @vkontakte/videoplayer-core v2.0.135-dev.f33adad6.0
3
+ * Tue, 01 Jul 2025 11:36:41 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-135/doc/
5
5
  */
6
- var Oo="2.0.135-dev.efff7df5.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ve||{}),Et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(Et||{});var As=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(As||{}),tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tn||{});var rn=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(rn||{}),Ps=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ps||{});import{assertNever as jo,assertNonNullable as qc,isNonNullable as Ms,ValueSubject as sn,Subject as Gc,Subscription as Yc,merge as Kc,observableFrom as Xc,fromEvent as _o,map as No,tap as Uo,filterChanged as Jc,isNullable as an,ErrorCategory as Ho}from"@vkontakte/videoplayer-shared/evergreen";var Fo=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Ls=class{constructor(e){this.connection$=new sn(void 0);this.castState$=new sn("NOT_AVAILABLE");this.errorEvent$=new Gc;this.realCastState$=new sn("NOT_AVAILABLE");this.subscription=new Yc;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ms(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Fo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ho.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(){Ms(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();an(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();an(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(_o(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 jo(r.sessionState)}})).add(Kc(_o(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Uo(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),No(r=>r.castState)),Xc([i.getCastState()])).pipe(Jc(),No(Zc),Uo(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=Ms(this.connection$.getValue());if(s&&!a){let o=i.getCurrentSession();qc(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(an(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ms(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:Ho.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Zc=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 jo(n)}};import{assertNever as zo}from"@vkontakte/videoplayer-shared/evergreen";var pe=(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:zo(t)}return n},Vt=(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:zo(e)}};var M=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as ed,Subject as Bs,merge as Qo}from"@vkontakte/videoplayer-shared/evergreen";var _=class{constructor(e){this.transitionStarted$=new Bs;this.transitionEnded$=new Bs;this.transitionUpdated$=new Bs;this.forceChanged$=new Bs;this.stateChangeStarted$=Qo(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Qo(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||ed(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 td}from"@vkontakte/videoplayer-shared/evergreen";var Wo=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 td(n)}};import{assertNever as pi,assertNonNullable as Xt,debounce as qo,ErrorCategory as Go,fromEvent as Jt,isNonNullable as Yo,map as Ko,merge as Xo,observableFrom as id,Subject as rd,Subscription as nn,timeout as sd,getHighestQuality as ad}from"@vkontakte/videoplayer-shared/evergreen";var nd=5,od=5,ud=500,Jo=7e3,_i=class{constructor(e){this.subscription=new nn;this.loadMediaTimeoutSubscription=new nn;this.videoState=new _("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=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(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.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:pi(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:pi(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:pi(e)}break}default:pi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Wo(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 nn;this.subscription.add(e),this.subscription.add(Xo(this.videoState.stateChangeStarted$.pipe(Ko(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ko(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new rd;e.add(r.pipe(qo(ud)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let o=a.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>nd)&&r.next(o),s=o})),e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,o=this.params.output.isBuffering$.getValue(),u=a===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<od&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),M(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:pi(a)}}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Xo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,id(["init"])).pipe(qo(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"),M(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),M(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"),M(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),M(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&M(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,s;switch(e){case"MPEG":{let l=t[e];Xt(l);let p=ad(Object.keys(l));Xt(p);let c=l[p];Xt(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Xt(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Xt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Xt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Xt(l),i=pe(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Go.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return pi(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Yo(o)&&(a.metadata.title=o),Yo(u)&&(a.metadata.subtitle=u),a}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,s)=>{this.loadMediaTimeoutSubscription.add(sd(Jo).subscribe(()=>s(`timeout(${Jo})`)))});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 s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Go.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as eu}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as ld}from"@vkontakte/videoplayer-shared/evergreen";var Zo=n=>{try{n.pause(),n.playbackRate=0,ld(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as cd,Subscription as dd}from"@vkontakte/videoplayer-shared/evergreen";var on=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)}},un=window.WeakMap?new WeakMap:new on,ln=window.WeakMap?new WeakMap:new Map,pd=(n,e=20)=>{let t=0;return cd(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},Oe=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?eu(i):(i=document.createElement("video"),n.appendChild(i)),un.set(i,r);let s=new dd;return s.add(pd(i,e)),ln.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Fe=n=>{ln.get(n)?.unsubscribe(),ln.delete(n);let t=un.get(n);un.delete(n),t?eu(n):Zo(n)};import{assertNonNullable as Ui,isNonNullable as pt,isNullable as fd,fromEvent as hi,merge as tu,observableFrom as iu,filterChanged as ru,map as Hi,Subject as su,Subscription as bd,ValueSubject as gd,ErrorCategory as Sd}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as cn,isNullable as hd,Subscription as md}from"@vkontakte/videoplayer-shared/evergreen";var $s=(n,e,t,{equal:i=(a,o)=>a===o,changed$:r,onError:s}={})=>{let a=n.getState(),o=e(),u=hd(r),l=new md;return r&&l.add(r.subscribe(p=>{let c=n.getState();i(p,c)&&n.setState(p)},s)),i(o,a)||(t(a),u&&n.setState(a)),l.add(n.stateChangeStarted$.subscribe(p=>{t(p.to),u&&n.setState(p.to)},s)),l},dt=(n,e,t)=>$s(e,()=>n.loop,i=>{cn(i)&&(n.loop=i)},{onError:t}),_e=(n,e,t,i)=>$s(e,()=>({muted:n.muted,volume:n.volume}),r=>{cn(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),et=(n,e,t,i)=>$s(e,()=>n.playbackRate,r=>{cn(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Ni=$s;var vd=n=>["__",n.language,n.label].join("|"),yd=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},dn=class n{constructor(e){this.available$=new su;this.current$=new gd(void 0);this.error$=new su;this.subscription=new bd;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:Sd.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};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(Ni(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{pt(s)&&this.setInternal(s)},{equal:(s,a)=>pt(s)&&pt(a)&&s.length===a.length&&s.every(({id:o},u)=>o===a[u].id),changed$:this.available$.pipe(Hi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Ni(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{pt(s)&&this.setExternal(s)},{equal:(s,a)=>pt(s)&&pt(a)&&s.length===a.length&&s.every(({id:o},u)=>o===a[u].id),changed$:this.available$.pipe(Hi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Ni(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Ni(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ui(this.video);let{textTracks:e}=this.video;this.subscription.add(hi(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(tu(hi(e,"addtrack"),hi(e,"removetrack"),iu(["init"])).pipe(Hi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ru((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(tu(hi(e,"change"),iu(["init"])).pipe(Hi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Hi(i=>i&&this.htmlTextTrackToITextTrack(i).id),ru()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(hi(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(hi(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;pt(t.align)&&(r.align=t.align),pt(t.position)&&(r.position=t.position),pt(t.size)&&(r.size=t.size),pt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ui(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:vd(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,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:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ui(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(fd(e)||!yd(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){Ui(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ui(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)}},tt=dn;var Zt=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 au=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},pn=n=>{let e=au(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},nu=n=>{let e=au(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as $e,map as ht,merge as _s,filterChanged as hu,isNonNullable as mu,Subject as Md,filter as mn,mapTo as fn,combine as Ld,once as Bd,throttle as $d,ErrorCategory as Rd,ValueSubject as fu,Subscription as Dd}from"@vkontakte/videoplayer-shared/evergreen";var Td=3,ou=(n,e,t=Td)=>{let i=0,r=0;for(let s=0;s<n.length;s++){let a=n.start(s),o=n.end(s);if(a<=e&&e<=o){if(i=a,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=s+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var Rs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isFirefox(){return this.current==="Firefox"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var ji=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Ds=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=ji()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Cs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,mi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),uu=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Vs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Id=document.createElement("video"),xd='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ed='video/mp4; codecs="hev1.1.6.L93.B0"',lu='video/webm; codecs="vp09.00.10.08"',cu='video/webm; codecs="av01.0.00M.08"',kd='audio/mp4; codecs="mp4a.40.2"',wd='audio/webm; codecs="opus"',du,Ad=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:cu}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:lu}})]);du={DASH_WEBM_AV1:e,DASH_WEBM:t}};Ad().catch(n=>{console.log(Id),console.error(n)});var Os=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return du}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:mi(),mse:uu(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Je()?.isTypeSupported?.(xd),t=!!Je()?.isTypeSupported?.(Ed),i=!!Je()?.isTypeSupported?.(kd);this._codecs={h264:e,h265:t,vp9:!!Je()?.isTypeSupported?.(lu),av1:!!Je()?.isTypeSupported?.(cu),aac:i,opus:!!Je()?.isTypeSupported?.(wd),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}this.destroyVideoElement()}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var pu="audio/mpeg",Fs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(pu)},this._codecs={mp3:!!Je()?.isTypeSupported?.(pu)}}catch(e){console.error(e)}this.destroyAudioElement()}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as Pd}from"@vkontakte/videoplayer-shared/evergreen";var hn=class{constructor(){this.isInited$=new Pd(!1);this._displayChecker=new Cs,this._deviceChecker=new Ds(this._displayChecker),this._browserChecker=new Rs,this._videoChecker=new Os(this._deviceChecker,this._browserChecker),this._audioChecker=new Fs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},O=new hn;var Ne=n=>{let e=g=>$e(n,g).pipe(fn(void 0)),t=new Dd,i=()=>t.unsubscribe(),r=_s($e(n,"progress"),$e(n,"timeupdate")).pipe(ht(()=>ou(n.buffered,n.currentTime))),s=O.browser.isSafari?Ld({play:e("play").pipe(Bd()),playing:e("playing")}).pipe(fn(void 0)):e("playing"),a=$e(n,"volumechange").pipe(ht(()=>({muted:n.muted,volume:n.volume}))),o=$e(n,"ratechange").pipe(ht(()=>n.playbackRate)),u=$e(n,"error").pipe(mn(()=>!!(n.error||n.played.length)),ht(()=>{let g=n.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:Rd.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=$e(n,"timeupdate").pipe(ht(()=>n.currentTime)),p=["waiting","seeking","seeked","timeupdate"],c=new Md,d=.3,h;t.add(_s(...p.map(g=>$e(n,g))).subscribe(g=>{let R=n.currentTime;n.loop&&mu(h)&&mu(R)&&h>=n.duration-d&&R<=d&&c.next(h),h=R}));let m=e("pause").pipe(mn(()=>!n.error&&h!==n.duration)),f=$e(n,"enterpictureinpicture"),b=$e(n,"leavepictureinpicture"),S=new fu(nu(n));t.add(f.subscribe(()=>S.next(!0))),t.add(b.subscribe(()=>S.next(!1)));let E=new fu(pn(n)),v=$e(n,"fullscreenchange");t.add(v.pipe(ht(()=>pn(n))).subscribe(E));let I=.1,x=1e3,L=$e(n,"timeupdate").pipe(ht(g=>n.duration-n.currentTime<I),hu()),C=_s(L.pipe(mn(g=>!n.loop&&g)),$e(n,"ended")).pipe($d(x),fn(void 0)),w=_s(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>$e(n,g)),L.pipe(ht(g=>({type:g?"ended":"unknown"})))).pipe(ht(g=>O.browser.isFirefox&&g.type==="ended"?n.readyState<2:n.readyState<3),hu());return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:C,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:$e(n,"durationchange").pipe(ht(()=>n.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:a,playbackRateState$:o,inPiP$:S,inFullscreen$:E,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/evergreen";var Ft=n=>{switch(n){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};import{isNonNullable as Y,isNullable as zs,now as ku,isHigher as Qs,isHigherOrEqual as bi,isInvariantQuality as Ws,isLowerOrEqual as gi,videoSizeToQuality as wu,assertNotEmptyArray as qs,assertNonNullable as Au}from"@vkontakte/videoplayer-shared/evergreen";var bn=!1,wt={},bu=n=>{bn=n},gu=()=>{wt={}},Su=n=>{n(wt)},zi=(n,e)=>{bn&&(wt.meta=wt.meta??{},wt.meta[n]=e)},Re=class{constructor(e){this.name=e}next(e){if(!bn)return;wt.series=wt.series??{};let t=wt.series[this.name]??[];t.push([Date.now(),e]),wt.series[this.name]=t}};import{isHigher as Cd,isHigherOrEqual as Ug,isLower as vu,isLowerOrEqual as Hg,isNonNullable as Ns,isNullable as Vd,videoHeightToQuality as Us}from"@vkontakte/videoplayer-shared/evergreen";function gn(n,e,t){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function Hs(n,e,t){return!!n&&gn(n,e,t)==="high_quality"}function fi(n,e,t){return Vd(n)||Ns(n.min)&&Ns(n.max)&&vu(n.max,n.min)||Ns(n.min)&&e&&Cd(n.min,e)||Ns(n.max)&&t&&vu(n.max,t)}function yu({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return fi({max:n?.max?Us(n.max):void 0,min:n?.min?Us(n.min):void 0},e?Us(e):void 0,t?Us(t):void 0)}var Pu=new Re("best_bitrate"),Gs=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var Si=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),_t=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ku()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ys='Assertion "ABR Tracks is empty array" failed',js=new WeakMap,Tu=new WeakMap,Iu=new WeakMap,Qi=(n,e,t,i)=>{let r=[...e].sort(Si(1)),s=[...t].sort(Si(1)),a=s.filter(u=>Y(u.bitrate)&&Y(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return o&&a.includes(o)?o:a.length?a.at(-1):s.at(0)},Wi=(n,e,t,i)=>{let r=js.get(e);r||(r=[...e].sort(Si(1)),js.set(e,r));let s=js.get(t);s||(s=[...t].sort(Si(1)),js.set(t,s));let a=Iu.get(n);a||(a=s.filter(u=>Y(u.bitrate)&&Y(n.bitrate)?n.bitrate/u.bitrate>i:!0),Iu.set(n,a));let o=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return o&&a.includes(o)?o:a.length?a.at(-1):s.at(0)},xu=n=>"quality"in n,Ks=(n,e,t,i)=>{let r=Y(i?.last?.bitrate)&&Y(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&ku()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let o=xu(a)?"video":"audio",u=xu(a)?a.quality:a.bitrate;return e({message:`
6
+ var Oo="2.0.135-dev.f33adad6.0";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ce||{}),Et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(Et||{});var As=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(As||{}),tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(tn||{});var rn=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(rn||{}),Ps=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ps||{});import{assertNever as jo,assertNonNullable as qc,isNonNullable as Ms,ValueSubject as sn,Subject as Gc,Subscription as Yc,merge as Kc,observableFrom as Xc,fromEvent as _o,map as No,tap as Uo,filterChanged as Jc,isNullable as an,ErrorCategory as Ho}from"@vkontakte/videoplayer-shared/evergreen";var Fo=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Ls=class{constructor(e){this.connection$=new sn(void 0);this.castState$=new sn("NOT_AVAILABLE");this.errorEvent$=new Gc;this.realCastState$=new sn("NOT_AVAILABLE");this.subscription=new Yc;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ms(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Fo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ho.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(){Ms(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();an(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();an(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(_o(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 jo(r.sessionState)}})).add(Kc(_o(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Uo(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),No(r=>r.castState)),Xc([i.getCastState()])).pipe(Jc(),No(Zc),Uo(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=Ms(this.connection$.getValue());if(s&&!a){let o=i.getCurrentSession();qc(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(an(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ms(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:Ho.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Zc=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 jo(n)}};import{assertNever as zo}from"@vkontakte/videoplayer-shared/evergreen";var pe=(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:zo(t)}return n},Ct=(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:zo(e)}};var M=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as ed,Subject as Bs,merge as Qo}from"@vkontakte/videoplayer-shared/evergreen";var _=class{constructor(e){this.transitionStarted$=new Bs;this.transitionEnded$=new Bs;this.transitionUpdated$=new Bs;this.forceChanged$=new Bs;this.stateChangeStarted$=Qo(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Qo(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||ed(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 td}from"@vkontakte/videoplayer-shared/evergreen";var Wo=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 td(n)}};import{assertNever as pi,assertNonNullable as Xt,debounce as qo,ErrorCategory as Go,fromEvent as Jt,isNonNullable as Yo,map as Ko,merge as Xo,observableFrom as id,Subject as rd,Subscription as nn,timeout as sd,getHighestQuality as ad}from"@vkontakte/videoplayer-shared/evergreen";var nd=5,od=5,ud=500,Jo=7e3,_i=class{constructor(e){this.subscription=new nn;this.loadMediaTimeoutSubscription=new nn;this.videoState=new _("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=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(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.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:pi(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:pi(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:pi(e)}break}default:pi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Wo(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 nn;this.subscription.add(e),this.subscription.add(Xo(this.videoState.stateChangeStarted$.pipe(Ko(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ko(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new rd;e.add(r.pipe(qo(ud)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let o=a.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>nd)&&r.next(o),s=o})),e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,o=this.params.output.isBuffering$.getValue(),u=a===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<od&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),M(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:pi(a)}}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Xo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,id(["init"])).pipe(qo(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"),M(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),M(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"),M(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),M(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&M(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,s;switch(e){case"MPEG":{let l=t[e];Xt(l);let p=ad(Object.keys(l));Xt(p);let c=l[p];Xt(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Xt(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Xt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Xt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Xt(l),i=pe(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",p=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Go.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return pi(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Yo(o)&&(a.metadata.title=o),Yo(u)&&(a.metadata.subtitle=u),a}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,s)=>{this.loadMediaTimeoutSubscription.add(sd(Jo).subscribe(()=>s(`timeout(${Jo})`)))});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 s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Go.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as eu}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as ld}from"@vkontakte/videoplayer-shared/evergreen";var Zo=n=>{try{n.pause(),n.playbackRate=0,ld(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as cd,Subscription as dd}from"@vkontakte/videoplayer-shared/evergreen";var on=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)}},un=window.WeakMap?new WeakMap:new on,ln=window.WeakMap?new WeakMap:new Map,pd=(n,e=20)=>{let t=0;return cd(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},Oe=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?eu(i):(i=document.createElement("video"),n.appendChild(i)),un.set(i,r);let s=new dd;return s.add(pd(i,e)),ln.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Fe=n=>{ln.get(n)?.unsubscribe(),ln.delete(n);let t=un.get(n);un.delete(n),t?eu(n):Zo(n)};import{assertNonNullable as Ui,isNonNullable as pt,isNullable as fd,fromEvent as hi,merge as tu,observableFrom as iu,filterChanged as ru,map as Hi,Subject as su,Subscription as bd,ValueSubject as gd,ErrorCategory as Sd}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as cn,isNullable as hd,Subscription as md}from"@vkontakte/videoplayer-shared/evergreen";var $s=(n,e,t,{equal:i=(a,o)=>a===o,changed$:r,onError:s}={})=>{let a=n.getState(),o=e(),u=hd(r),l=new md;return r&&l.add(r.subscribe(p=>{let c=n.getState();i(p,c)&&n.setState(p)},s)),i(o,a)||(t(a),u&&n.setState(a)),l.add(n.stateChangeStarted$.subscribe(p=>{t(p.to),u&&n.setState(p.to)},s)),l},dt=(n,e,t)=>$s(e,()=>n.loop,i=>{cn(i)&&(n.loop=i)},{onError:t}),_e=(n,e,t,i)=>$s(e,()=>({muted:n.muted,volume:n.volume}),r=>{cn(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),et=(n,e,t,i)=>$s(e,()=>n.playbackRate,r=>{cn(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Ni=$s;var vd=n=>["__",n.language,n.label].join("|"),yd=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},dn=class n{constructor(e){this.available$=new su;this.current$=new gd(void 0);this.error$=new su;this.subscription=new bd;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:Sd.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};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(Ni(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{pt(s)&&this.setInternal(s)},{equal:(s,a)=>pt(s)&&pt(a)&&s.length===a.length&&s.every(({id:o},u)=>o===a[u].id),changed$:this.available$.pipe(Hi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Ni(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{pt(s)&&this.setExternal(s)},{equal:(s,a)=>pt(s)&&pt(a)&&s.length===a.length&&s.every(({id:o},u)=>o===a[u].id),changed$:this.available$.pipe(Hi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Ni(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Ni(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ui(this.video);let{textTracks:e}=this.video;this.subscription.add(hi(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(tu(hi(e,"addtrack"),hi(e,"removetrack"),iu(["init"])).pipe(Hi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ru((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(tu(hi(e,"change"),iu(["init"])).pipe(Hi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Hi(i=>i&&this.htmlTextTrackToITextTrack(i).id),ru()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(hi(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(hi(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;pt(t.align)&&(r.align=t.align),pt(t.position)&&(r.position=t.position),pt(t.size)&&(r.size=t.size),pt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ui(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:vd(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,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:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ui(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(fd(e)||!yd(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){Ui(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ui(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)}},tt=dn;var Zt=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 au=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},pn=n=>{let e=au(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},nu=n=>{let e=au(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as $e,map as ht,merge as _s,filterChanged as hu,isNonNullable as mu,Subject as Md,filter as mn,mapTo as fn,combine as Ld,once as Bd,throttle as $d,ErrorCategory as Rd,ValueSubject as fu,Subscription as Dd}from"@vkontakte/videoplayer-shared/evergreen";var Td=3,ou=(n,e,t=Td)=>{let i=0,r=0;for(let s=0;s<n.length;s++){let a=n.start(s),o=n.end(s);if(a<=e&&e<=o){if(i=a,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=s+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var Rs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var ji=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Ds=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=ji()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Vs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,mi=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),uu=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Cs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Id=document.createElement("video"),xd='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ed='video/mp4; codecs="hev1.1.6.L93.B0"',lu='video/webm; codecs="vp09.00.10.08"',cu='video/webm; codecs="av01.0.00M.08"',kd='audio/mp4; codecs="mp4a.40.2"',wd='audio/webm; codecs="opus"',du,Ad=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:cu}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:lu}})]);du={DASH_WEBM_AV1:e,DASH_WEBM:t}};Ad().catch(n=>{console.log(Id),console.error(n)});var Os=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return du}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:mi(),mse:uu(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Je()?.isTypeSupported?.(xd),t=!!Je()?.isTypeSupported?.(Ed),i=!!Je()?.isTypeSupported?.(kd);this._codecs={h264:e,h265:t,vp9:!!Je()?.isTypeSupported?.(lu),av1:!!Je()?.isTypeSupported?.(cu),aac:i,opus:!!Je()?.isTypeSupported?.(wd),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var pu="audio/mpeg",Fs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(pu)},this._codecs={mp3:!!Je()?.isTypeSupported?.(pu)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as Pd}from"@vkontakte/videoplayer-shared/evergreen";var hn=class{constructor(){this.isInited$=new Pd(!1);this._displayChecker=new Vs,this._deviceChecker=new Ds(this._displayChecker),this._browserChecker=new Rs,this._videoChecker=new Os(this._deviceChecker,this._browserChecker),this._audioChecker=new Fs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},O=new hn;var Ne=n=>{let e=g=>$e(n,g).pipe(fn(void 0)),t=new Dd,i=()=>t.unsubscribe(),r=_s($e(n,"progress"),$e(n,"timeupdate")).pipe(ht(()=>ou(n.buffered,n.currentTime))),s=O.browser.isSafari?Ld({play:e("play").pipe(Bd()),playing:e("playing")}).pipe(fn(void 0)):e("playing"),a=$e(n,"volumechange").pipe(ht(()=>({muted:n.muted,volume:n.volume}))),o=$e(n,"ratechange").pipe(ht(()=>n.playbackRate)),u=$e(n,"error").pipe(mn(()=>!!(n.error||n.played.length)),ht(()=>{let g=n.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:Rd.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:n.error??void 0}})),l=$e(n,"timeupdate").pipe(ht(()=>n.currentTime)),p=["waiting","seeking","seeked","timeupdate"],c=new Md,d=.3,h;t.add(_s(...p.map(g=>$e(n,g))).subscribe(g=>{let R=n.currentTime;n.loop&&mu(h)&&mu(R)&&h>=n.duration-d&&R<=d&&c.next(h),h=R}));let m=e("pause").pipe(mn(()=>!n.error&&h!==n.duration)),f=$e(n,"enterpictureinpicture"),b=$e(n,"leavepictureinpicture"),S=new fu(nu(n));t.add(f.subscribe(()=>S.next(!0))),t.add(b.subscribe(()=>S.next(!1)));let x=new fu(pn(n)),v=$e(n,"fullscreenchange");t.add(v.pipe(ht(()=>pn(n))).subscribe(x));let I=.1,E=1e3,L=$e(n,"timeupdate").pipe(ht(g=>n.duration-n.currentTime<I),hu()),V=_s(L.pipe(mn(g=>!n.loop&&g)),$e(n,"ended")).pipe($d(E),fn(void 0)),w=_s(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>$e(n,g)),L.pipe(ht(g=>({type:g?"ended":"unknown"})))).pipe(ht(g=>O.browser.isFirefox&&g.type==="ended"?n.readyState<2:n.readyState<3),hu());return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:V,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:$e(n,"durationchange").pipe(ht(()=>n.duration)),isBuffering$:w,currentBuffer$:r,volumeState$:a,playbackRateState$:o,inPiP$:S,inFullscreen$:x,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/evergreen";var Ft=n=>{switch(n){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};import{isNonNullable as K,isNullable as zs,now as ku,isHigher as Qs,isHigherOrEqual as bi,isInvariantQuality as Ws,isLowerOrEqual as gi,videoSizeToQuality as wu,assertNotEmptyArray as qs,assertNonNullable as Au}from"@vkontakte/videoplayer-shared/evergreen";var bn=!1,wt={},bu=n=>{bn=n},gu=()=>{wt={}},Su=n=>{n(wt)},zi=(n,e)=>{bn&&(wt.meta=wt.meta??{},wt.meta[n]=e)},Re=class{constructor(e){this.name=e}next(e){if(!bn)return;wt.series=wt.series??{};let t=wt.series[this.name]??[];t.push([Date.now(),e]),wt.series[this.name]=t}};import{isHigher as Vd,isHigherOrEqual as jg,isLower as vu,isLowerOrEqual as zg,isNonNullable as Ns,isNullable as Cd,videoHeightToQuality as Us}from"@vkontakte/videoplayer-shared/evergreen";function gn(n,e,t){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function Hs(n,e,t){return!!n&&gn(n,e,t)==="high_quality"}function fi(n,e,t){return Cd(n)||Ns(n.min)&&Ns(n.max)&&vu(n.max,n.min)||Ns(n.min)&&e&&Vd(n.min,e)||Ns(n.max)&&t&&vu(n.max,t)}function yu({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return fi({max:n?.max?Us(n.max):void 0,min:n?.min?Us(n.min):void 0},e?Us(e):void 0,t?Us(t):void 0)}var Pu=new Re("best_bitrate"),Gs=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var Si=n=>(e,t)=>n*(Number(e.bitrate)-Number(t.bitrate)),_t=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ku()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ys='Assertion "ABR Tracks is empty array" failed',js=new WeakMap,Tu=new WeakMap,Iu=new WeakMap,Qi=(n,e,t,i)=>{let r=[...e].sort(Si(1)),s=[...t].sort(Si(1)),a=s.filter(u=>K(u.bitrate)&&K(n.bitrate)?n.bitrate/u.bitrate>i:!0),o=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return o&&a.includes(o)?o:a.length?a.at(-1):s.at(0)},Wi=(n,e,t,i)=>{let r=js.get(e);r||(r=[...e].sort(Si(1)),js.set(e,r));let s=js.get(t);s||(s=[...t].sort(Si(1)),js.set(t,s));let a=Iu.get(n);a||(a=s.filter(u=>K(u.bitrate)&&K(n.bitrate)?n.bitrate/u.bitrate>i:!0),Iu.set(n,a));let o=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return o&&a.includes(o)?o:a.length?a.at(-1):s.at(0)},xu=n=>"quality"in n,Ks=(n,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&ku()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let o=xu(a)?"video":"audio",u=xu(a)?a.quality:a.bitrate;return e({message:`
7
7
  [last ${o} selected] ${u}
8
- `}),a}return i?.recordSwitch(t),t},Od=(n,e)=>Math.log(e)/Math.log(n),Mu=({tuning:n,container:e,limits:t,panelSize:i})=>{let r=n.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(n.usePixelRatio&&O.display.pixelRatio){let s=O.display.pixelRatio;if(n.pixelRatioMultiplier)r*=n.pixelRatioMultiplier*(s-1)+1;else{let a=n.pixelRatioLogBase,[o=0,u=0,l=0]=n.pixelRatioLogCoefficients,p=Od(a,o*s+u)+l;Number.isFinite(p)&&(r*=p)}}return Hs(t,n.highQualityLimit,n.trafficSavingLimit)&&(r*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Eu=new WeakMap,mt=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{qs(n,Ys);let{containerSizeFactor:b,containerSizeLimit:S}=Mu({container:e,tuning:i,limits:r,panelSize:f}),E=i.considerPlaybackRate&&Y(o)?o:1,v=Eu.get(n);v||(v=n.filter(T=>!Ws(T.quality)).sort((T,A)=>Qs(T.quality,A.quality)?-1:1),Eu.set(n,v));let I=v.at(-1)?.quality,x=v.at(0)?.quality,L=fi(r,x,I),C=E*Gs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},w=null;for(let T of v){let A=!0;if(S)if(T.size)A=T.size.width<=S.width&&T.size.height<=S.height;else{let P=S&&wu(S);A=P?gi(T.quality,P):!0}if(!A){k[T.quality]="FitsContainer";continue}let ee=h||t,$=Y(ee)&&isFinite(ee)&&Y(T.bitrate)?ee-s>=T.bitrate*C:!0,N=Hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===T.quality;if(!$&&!N){k[T.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&Y(i.minBufferToSwitchUp)&&u&&!Ws(u.quality)&&(a??0)<i.minBufferToSwitchUp&&Qs(T.quality,u.quality)){k[T.quality]="Buffer";continue}if(!!c&&bi(T.quality,c)&&!N){k[T.quality]="DroppedFramesLimit";continue}if(!!d&&bi(T.quality,d)&&!N){k[T.quality]="StallsLimit";continue}let se=L||(zs(r?.max)||gi(T.quality,r.max))&&(zs(r?.min)||bi(T.quality,r.min)),X=Y(p)&&!p?gi(T.quality,i.backgroundVideoQualityLimit):!0;if(!se||!X){k[T.quality]="FitsQualityLimits";continue}w||(w=T)}w&&w.bitrate&&Pu.next(w.bitrate);let g=w??v.at(-1)??n[0],R=l?.last,y=Ks(i,m,g,l);return Y(l)&&y.quality!==R?.quality&&m({message:`
8
+ `}),a}return i?.recordSwitch(t),t},Od=(n,e)=>Math.log(e)/Math.log(n),Mu=({tuning:n,container:e,limits:t,panelSize:i})=>{let r=n.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(n.usePixelRatio&&O.display.pixelRatio){let s=O.display.pixelRatio;if(n.pixelRatioMultiplier)r*=n.pixelRatioMultiplier*(s-1)+1;else{let a=n.pixelRatioLogBase,[o=0,u=0,l=0]=n.pixelRatioLogCoefficients,p=Od(a,o*s+u)+l;Number.isFinite(p)&&(r*=p)}}return Hs(t,n.highQualityLimit,n.trafficSavingLimit)&&(r*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Eu=new WeakMap,mt=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{qs(n,Ys);let{containerSizeFactor:b,containerSizeLimit:S}=Mu({container:e,tuning:i,limits:r,panelSize:f}),x=i.considerPlaybackRate&&K(o)?o:1,v=Eu.get(n);v||(v=n.filter(T=>!Ws(T.quality)).sort((T,A)=>Qs(T.quality,A.quality)?-1:1),Eu.set(n,v));let I=v.at(-1)?.quality,E=v.at(0)?.quality,L=fi(r,E,I),V=x*Gs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},w=null;for(let T of v){let A=!0;if(S)if(T.size)A=T.size.width<=S.width&&T.size.height<=S.height;else{let P=S&&wu(S);A=P?gi(T.quality,P):!0}if(!A){k[T.quality]="FitsContainer";continue}let ee=h||t,$=K(ee)&&isFinite(ee)&&K(T.bitrate)?ee-s>=T.bitrate*V:!0,N=Hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===T.quality;if(!$&&!N){k[T.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Ws(u.quality)&&(a??0)<i.minBufferToSwitchUp&&Qs(T.quality,u.quality)){k[T.quality]="Buffer";continue}if(!!c&&bi(T.quality,c)&&!N){k[T.quality]="DroppedFramesLimit";continue}if(!!d&&bi(T.quality,d)&&!N){k[T.quality]="StallsLimit";continue}let se=L||(zs(r?.max)||gi(T.quality,r.max))&&(zs(r?.min)||bi(T.quality,r.min)),X=K(p)&&!p?gi(T.quality,i.backgroundVideoQualityLimit):!0;if(!se||!X){k[T.quality]="FitsQualityLimits";continue}w||(w=T)}w&&w.bitrate&&Pu.next(w.bitrate);let g=w??v.at(-1)??n[0],R=l?.last,y=Ks(i,m,g,l);return K(l)&&y.quality!==R?.quality&&m({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
11
  ${n.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
@@ -22,9 +22,9 @@ var Oo="2.0.135-dev.efff7df5.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",
22
22
  stallsPredictedThroughput: ${h},
23
23
  reserve: ${s},
24
24
  playbackRate: ${o},
25
- playbackRateFactor: ${E},
25
+ playbackRateFactor: ${x},
26
26
  forwardBufferHealth: ${a},
27
- bitrateFactor: ${C},
27
+ bitrateFactor: ${V},
28
28
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
29
29
  droppedVideoMaxQualityLimit: ${c},
30
30
  stallsVideoMaxQualityLimit: ${d},
@@ -38,7 +38,7 @@ var Oo="2.0.135-dev.efff7df5.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",
38
38
 
39
39
  [best video track] ${w?.quality}
40
40
  [selected video track] ${y?.quality}
41
- `}),y},Xs=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{qs(n,Ys);let{containerSizeFactor:b,containerSizeLimit:S}=Mu({container:e,tuning:i,limits:r,panelSize:f}),E=i.considerPlaybackRate&&Y(o)?o:1,v=n.filter(A=>!Ws(A.quality)).sort((A,ee)=>Qs(A.quality,ee.quality)?-1:1),I=v.at(-1)?.quality,x=v.at(0)?.quality,L=fi(r,x,I),C=E*Gs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},g=v.filter(A=>{let ee=!0;if(S)if(A.size)ee=A.size.width<=S.width&&A.size.height<=S.height;else{let D=S&&wu(S);ee=D?gi(A.quality,D):!0}if(!ee)return k[A.quality]="FitsContainer",!1;let $=h||t,N=Y($)&&isFinite($)&&Y(A.bitrate)?$-s>=A.bitrate*C:!0,G=Hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===A.quality;if(!N&&!G)return k[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Y(i.minBufferToSwitchUp)&&u&&!Ws(u.quality)&&(a??0)<i.minBufferToSwitchUp&&Qs(A.quality,u.quality))return k[A.quality]="Buffer",!1;if(!!c&&bi(A.quality,c)&&!G)return k[A.quality]="DroppedFramesLimit",!1;if(!!d&&bi(A.quality,d)&&!G)return k[A.quality]="StallsLimit",!1;let X=L||(zs(r?.max)||gi(A.quality,r.max))&&(zs(r?.min)||bi(A.quality,r.min)),P=Y(p)&&!p?gi(A.quality,i.backgroundVideoQualityLimit):!0;return!X||!P?(k[A.quality]="FitsQualityLimits",!1):!0})[0];g&&g.bitrate&&Pu.next(g.bitrate);let R=g??v.at(-1)??n[0],y=l?.last,T=Ks(i,m,R,l);return Y(l)&&T.quality!==y?.quality&&m({message:`
41
+ `}),y},Xs=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{qs(n,Ys);let{containerSizeFactor:b,containerSizeLimit:S}=Mu({container:e,tuning:i,limits:r,panelSize:f}),x=i.considerPlaybackRate&&K(o)?o:1,v=n.filter(A=>!Ws(A.quality)).sort((A,ee)=>Qs(A.quality,ee.quality)?-1:1),I=v.at(-1)?.quality,E=v.at(0)?.quality,L=fi(r,E,I),V=x*Gs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},g=v.filter(A=>{let ee=!0;if(S)if(A.size)ee=A.size.width<=S.width&&A.size.height<=S.height;else{let D=S&&wu(S);ee=D?gi(A.quality,D):!0}if(!ee)return k[A.quality]="FitsContainer",!1;let $=h||t,N=K($)&&isFinite($)&&K(A.bitrate)?$-s>=A.bitrate*V:!0,Y=Hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===A.quality;if(!N&&!Y)return k[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Ws(u.quality)&&(a??0)<i.minBufferToSwitchUp&&Qs(A.quality,u.quality))return k[A.quality]="Buffer",!1;if(!!c&&bi(A.quality,c)&&!Y)return k[A.quality]="DroppedFramesLimit",!1;if(!!d&&bi(A.quality,d)&&!Y)return k[A.quality]="StallsLimit",!1;let X=L||(zs(r?.max)||gi(A.quality,r.max))&&(zs(r?.min)||bi(A.quality,r.min)),P=K(p)&&!p?gi(A.quality,i.backgroundVideoQualityLimit):!0;return!X||!P?(k[A.quality]="FitsQualityLimits",!1):!0})[0];g&&g.bitrate&&Pu.next(g.bitrate);let R=g??v.at(-1)??n[0],y=l?.last,T=Ks(i,m,R,l);return K(l)&&T.quality!==y?.quality&&m({message:`
42
42
  [VIDEO TRACKS ABR]
43
43
  [available video tracks]
44
44
  ${n.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${A.size?.width}:${A.size?.height} }`).join(`
@@ -55,9 +55,9 @@ var Oo="2.0.135-dev.efff7df5.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",
55
55
  stallsPredictedThroughput: ${h},
56
56
  reserve: ${s},
57
57
  playbackRate: ${o},
58
- playbackRateFactor: ${E},
58
+ playbackRateFactor: ${x},
59
59
  forwardBufferHealth: ${a},
60
- bitrateFactor: ${C},
60
+ bitrateFactor: ${V},
61
61
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
62
62
  droppedVideoMaxQualityLimit: ${c},
63
63
  stallsVideoMaxQualityLimit: ${d},
@@ -71,7 +71,7 @@ var Oo="2.0.135-dev.efff7df5.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",
71
71
 
72
72
  [best video track] ${g?.quality}
73
73
  [selected video track] ${T?.quality}
74
- `}),T},Js=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{qs(t,Ys);let p=r.considerPlaybackRate&&Y(s)?s:1,c=[...t].sort(Si(-1)),d=n.bitrate;Au(d);let h=p*Gs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Qi(n,e,t,r.minVideoAudioRatio),b=l||i;Y(b)&&isFinite(b)&&(m=c.find(v=>Y(v.bitrate)&&Y(f?.bitrate)?b-d>=v.bitrate*h&&v.bitrate>=f.bitrate:!1)),m||(m=f);let S=o?.last,E=m&&Ks(r,u,m,o);return Y(o)&&E?.bitrate!==S?.bitrate&&u({message:`
74
+ `}),T},Js=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{qs(t,Ys);let p=r.considerPlaybackRate&&K(s)?s:1,c=[...t].sort(Si(-1)),d=n.bitrate;Au(d);let h=p*Gs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Qi(n,e,t,r.minVideoAudioRatio),b=l||i;K(b)&&isFinite(b)&&(m=c.find(v=>K(v.bitrate)&&K(f?.bitrate)?b-d>=v.bitrate*h&&v.bitrate>=f.bitrate:!1)),m||(m=f);let S=o?.last,x=m&&Ks(r,u,m,o);return K(o)&&x?.bitrate!==S?.bitrate&&u({message:`
75
75
  [AUDIO TRACKS ABR]
76
76
  [available audio tracks]
77
77
  ${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
@@ -91,8 +91,8 @@ var Oo="2.0.135-dev.efff7df5.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",
91
91
  bitrateFactor: ${h},
92
92
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
93
93
 
94
- [selected audio track] ${E?.id}
95
- `}),E},Zs=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{qs(t,Ys);let p=r.considerPlaybackRate&&Y(s)?s:1,c=Tu.get(t);c||(c=[...t].sort(Si(-1)),Tu.set(t,c));let d=n.bitrate;Au(d);let h=p*Gs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Wi(n,e,t,r.minVideoAudioRatio),b=l||i;Y(b)&&isFinite(b)&&(m=c.find(v=>Y(v.bitrate)&&Y(f?.bitrate)?b-d>=v.bitrate*h&&v.bitrate>=f.bitrate:!1)),m||(m=f);let S=o?.last,E=m&&Ks(r,u,m,o);return Y(o)&&E?.bitrate!==S?.bitrate&&u({message:`
94
+ [selected audio track] ${x?.id}
95
+ `}),x},Zs=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{qs(t,Ys);let p=r.considerPlaybackRate&&K(s)?s:1,c=Tu.get(t);c||(c=[...t].sort(Si(-1)),Tu.set(t,c));let d=n.bitrate;Au(d);let h=p*Gs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Wi(n,e,t,r.minVideoAudioRatio),b=l||i;K(b)&&isFinite(b)&&(m=c.find(v=>K(v.bitrate)&&K(f?.bitrate)?b-d>=v.bitrate*h&&v.bitrate>=f.bitrate:!1)),m||(m=f);let S=o?.last,x=m&&Ks(r,u,m,o);return K(o)&&x?.bitrate!==S?.bitrate&&u({message:`
96
96
  [AUDIO TRACKS ABR]
97
97
  [available audio tracks]
98
98
  ${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
@@ -112,15 +112,15 @@ var Oo="2.0.135-dev.efff7df5.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",
112
112
  bitrateFactor: ${h},
113
113
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
114
114
 
115
- [selected audio track] ${E?.id}
116
- `}),E};var Ee=n=>new URL(n).hostname;import{assertNever as Cu,assertNonNullable as Vu,combine as sp,debounce as ap,ErrorCategory as Ou,filter as Fu,filterChanged as np,isNonNullable as In,map as ra,merge as _u,observableFrom as op,once as up,Subscription as lp,ValueSubject as xn,videoQualityToHeight as Nu,videoSizeToQuality as cp}from"@vkontakte/videoplayer-shared/evergreen";var Lu=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"))},Ue=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!Lu(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return Lu(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as ta,isNullable as Nd,assertNonNullable as Yi}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Bu,assertNonNullable as ea,now as Fd}from"@vkontakte/videoplayer-shared/evergreen";function Te(){return Fd()}function Sn(n){return Te()-n}function vn(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,o,u=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let l=a.indexOf("?")>-1?"&":"?";return u&&(a+=l+"lowLat=1",l="&"),o&&(a+=l+"_rnd="+Math.floor(999999999*Math.random())),a}}}function $u(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function vi(n,e,t,i){let r=window.XMLHttpRequest,s,a,o,u=!1,l=0,p,c,d=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;ea(p);let y=Sn(p),T;if(y<f){T=f-y,setTimeout(b,T);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,L()},S=y=>(s=y,R),E=y=>(c=y,R),v=()=>(h="json",R),I=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},x=y=>(d=y,R),L=()=>{p=Te(),a=new r,a.open("get",n);let y=0,T,A=0,ee=()=>(ea(p),Math.max(p,Math.max(T||0,A||0)));if(s&&a.addEventListener("progress",$=>{let N=Te();s.updateChunk&&$.loaded>y&&(s.updateChunk(ee(),$.loaded-y),y=$.loaded,T=N)}),o&&(a.timeout=o,a.addEventListener("timeout",()=>I())),a.addEventListener("load",()=>{if(u)return;ea(a);let $=a.status;if($>=200&&$<300){let{response:N,responseType:G}=a,re=N?.byteLength;if(typeof re=="number"&&s){let he=re-y;he&&s.updateChunk&&s.updateChunk(ee(),he)}G==="json"&&(!N||!Object.values(N).length)?I():(c&&c(),e(N))}else I()}),a.addEventListener("error",()=>{I()}),d){let $=()=>{ea(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(A=Te(),a.removeEventListener("readystatechange",$))};a.addEventListener("readystatechange",$)}return a.responseType=h,a.send(),R},R={withBitrateReporting:S,withParallel:x,withJSONResponse:v,withRetryCount:y=>(l=y,R),withRetryInterval:(y,T)=>(Bu(y)&&(f=y),Bu(T)&&(m=T),R),withTimeout:y=>(o=y,R),withFinally:E,send:L,abort:()=>{a&&(a.abort(),a=void 0),u=!0,c&&c()}};return R}var qi=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 s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,o=s.end-s.start;i+=a;let u=s.bytes*a/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/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 Gi=class{constructor(e,t,i,r,s){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=s}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=Te(),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)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=vi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_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=Te();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 s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._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(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,s),s}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}};import{Subject as Ud}from"@vkontakte/videoplayer-shared/evergreen";var ia=1e4,yn=3;var Hd=6e4,jd=10,zd=1,Qd=500,Ki=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Ud,this.chunkRateEstimator=new qi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=vn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=vn(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}, details: ${e.error?.message}`),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&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*(O.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!yu({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ta(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=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 a=()=>{$u(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Gi(yn,ia,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,s=!1,a=null,o=null,u=null,l=null,p=!1,c=()=>{let I=s&&(!p||p===this.rep);return I||t("Not running!"),I},d=(I,x,L)=>{u&&u.abort(),u=vi(this.urlResolver.resolve(I,!1),x,L,()=>this._retryCallback()).withTimeout(ia).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yn).withFinally(()=>{u=null}).send()},h=(I,x,L)=>{Yi(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),x,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let x=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${x}=>${I}`),i.playbackRate=I)},f=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=Te()-1e4,C=0;for(let w=0;w<this.bufferStates.length;w++){let g=this.bufferStates[w];I=Math.min(I,g.buf),g.ts<L&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${I} drop=${C} jitter=${this.sourceJitter}`);let k=I-zd;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?m(1.15):k>1?m(1.1):k>.3?m(1.05):m(1)}},S=I=>{let x,L=()=>x&&x.start?x.start.length:0,C=$=>x.start[$]/1e3,k=$=>x.dur[$]/1e3,w=$=>x.fragIndex+$,g=($,N)=>({chunkIdx:w($),startTS:C($),dur:k($),discontinuity:N}),R=()=>{let $=0;if(x&&x.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,re=N;this.sourceJitter>1&&(re+=this.sourceJitter-1);let he=x.dur.length-1;for(;he>=0&&(re-=x.dur[he],!(re<=0));--he);$=Math.min(he,x.dur.length-1-G),$=Math.max($,0)}return g($,!0)},y=$=>{let N=L();if(!(N<=0)){if(ta($)){for(let G=0;G<N;G++)if(C(G)>$)return g(G)}return R()}},T=$=>{let N=L(),G=$?$.chunkIdx+1:0,re=G-x.fragIndex;if(!(N<=0)){if(!$||re<0||re-N>jd)return t(`Resync: offset=${re} bChunks=${N} chunk=`+JSON.stringify($)),R();if(!(re>=N))return g(G-x.fragIndex,!1)}},A=($,N,G)=>{l&&l.abort(),l=vi(this.urlResolver.resolve($,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(ia).withRetryCount(yn).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,N)=>{A(I,G=>{if(!c())return;x=G;let re=!!x.lowLatency;re!==this.lowLatency&&f(re);let he=0;for(let se=0;se<x.dur.length;++se)he+=x.dur[se];he>0&&(Yi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/x.dur.length)),r({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,$(y(N))},()=>this._handleNetworkError())},nextChunk:T}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Yi(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:I=>{let{videoElement:x,logger:L}=this.params,C=S(e.jidxUrl),k,w,g,R,y=0,T,A,ee,$=()=>{T&&(clearTimeout(T),T=void 0);let D=Math.max(Qd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=y+D,me=Te(),J=Math.min(1e4,Se-me);y=me;let fe=()=>{l||c()&&C.seek(()=>{c()&&(y=Te(),N(),$())})};J>0?T=window.setTimeout(()=>{this.paused?$():fe()},J):fe()},N=()=>{let D;for(;D=C.nextChunk(R);)R=D,X(D);let Se=C.nextChunk(g);if(Se){if(g&&Se.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?$():(E(),this._initPlayerWith(e));return}se(Se)}else $()},G=(D,Se)=>{if(!c()||!this.sourceBuffer)return;let me,J,fe,ze=Pe=>{window.setTimeout(()=>{c()&&G(D,Se)},Pe)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),ze(100);else{let Pe=Te(),oe=x.currentTime;!this.paused&&x.buffered.length>1&&A===oe&&Pe-ee>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),A!==oe&&(A=oe,ee=Pe);let Qe=this._getBufferSizeSec();if(Qe>30)L(`Buffered ${Qe} seconds; delaying appendBuffer`),ze(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:Pe,buf:Qe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(ge){if(ge.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),fe=this.sourceBuffer.buffered.length,fe!==0&&(me=this.sourceBuffer.buffered.start(0),J=oe,J-me>4&&this.sourceBuffer.remove(me,J-3)),ze(1e3);else throw ge}}},re=()=>{w&&k&&(L([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(g)]),G(w,function(){w=null,N()}))},he=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),se=D=>{c()&&h(he(D),(Se,me)=>{if(c()){if(me/=1e3,w=Se,g=D,a=D.startTS,me){let J=Math.min(10,D.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*J:J}re()}},()=>this._handleNetworkError())},X=D=>{c()&&(Yi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he(D),!1)))},P=D=>{c()&&(e.cachedHeader=D,G(D,()=>{k=!0,re()}))};s=!0,C.seek(D=>{if(c()){if(y=Te(),!D){$();return}R=D,!Nd(I)||D.startTS>I?se(D):(g=D,N())}},I),e.cachedHeader?P(e.cachedHeader):d(e.headerUrl,P,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>a},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),ta(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,Yi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ta(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(d,h)=>{let m=Te();if(this.chunkRateEstimator.addInterval(d,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-d,speed:b}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},a=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Sn(a)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,d)=>{let h=s.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=Te();c<o&&(a=d),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=vi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ia).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;Ue(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let o=[];return a?.length?(a.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(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 Wd,filter as Ru,fromEvent as qd,interval as Gd,isHigher as Yd,isInvariantQuality as Kd,isLower as Xd,merge as Jd,Subject as Du,Subscription as Zd}from"@vkontakte/videoplayer-shared/evergreen";var Tn=class{constructor(){this.onDroopedVideoFramesLimit$=new Du;this.subscription=new Zd;this.playing=!1;this.tracks=[];this.forceChecker$=new Du;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&&!Kd(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=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(qd(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Gd(this.droppedFramesChecker.checkTime).pipe(Ru(()=>this.playing),Ru(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Wd(this.droppedFramesChecker.checkTime)),i=Jd(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])=>Xd(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}},yi=Tn;import{map as ep,Observable as tp}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as ip}from"@vkontakte/videoplayer-shared/evergreen";var Xi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var rp=(n,e)=>new tp(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,o)=>{a.forEach(u=>t.next(u.isIntersecting||Xi()))},{...i,...e});r.observe(n);let s=ip(document,"visibilitychange").pipe(ep(a=>!document.hidden||Xi())).subscribe(a=>t.next(a));return()=>{r.unobserve(n),s.unsubscribe()}}),it=rp;var dp=["paused","playing","ready"],pp=["paused","playing","ready"],Ji=class{constructor(e){this.subscription=new lp;this.videoState=new _("stopped");this.representations$=new xn([]);this.droppedFramesManager=new yi;this.maxSeekBackTime$=new xn(1/0);this.zeroTime$=new xn(void 0);this.liveOffset=new Zt;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:Ou.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=Ft(r.name)??cp(r.video),o=r.bitrate/1e3,u={...r.video};if(!a)continue;let l={id:s,quality:a,bitrate:o,size:u};i.push({track:l,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),In(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(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),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 a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(pp.includes(e)&&(a||o)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&dp.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(pe(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(pe(this.params.source.url,u))}return;default:return Cu(e)}};this.textTracksManager=new tt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ou.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(_u(this.videoState.stateChangeStarted$.pipe(ra(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ra(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),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(Ee(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ne(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ra(r=>r.map(({track:s})=>s)),Fu(r=>!!r.length),up()).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(np(),ra(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(sp({zeroTime:this.zeroTime$.pipe(Fu(In)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(_e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(et(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(it(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Nu(r),min:s&&Nu(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).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 Cu(r.to)}},t)).add(_u(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,op(["init"])).pipe(ap(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),Fe(this.video)}createLiveDashPlayer(){let e=new Ki({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,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&&In(t)?t:mt(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput: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}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),a||u||s!==o){let l=e.find(({track:p})=>p.id===s)?.representation;Vu(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Vu(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",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(pe(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var Uu=Ji;var Ie=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,s=n.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as hh,assertNonNullable as mh,debounce as fh,ErrorCategory as xl,filter as Wn,filterChanged as ka,fromEvent as bh,isNonNullable as El,map as qn,merge as wa,observableFrom as Gn,once as kl,Subscription as gh}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Zi}from"@vkontakte/videoplayer-shared/evergreen";var sa=n=>{if(!n)return{id:"EmptyResponse",category:Zi.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Zi.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:Zi.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:Zi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Zi.PARSER,message:"Response is valid XML, but parser failed"}};var ke=(n,e,t=0)=>{for(let i=0;i<n.length;i++)if(n.start(i)*1e3-t<=e&&n.end(i)*1e3+t>e)return!0;return!1};import{abortable as Fn,assertNonNullable as Ai,combine as Pi,ErrorCategory as ut,filter as ga,filterChanged as Br,flattenObject as $r,fromEvent as $t,getTraceSubscriptionMethod as Yp,interval as _n,isNonNullable as Rr,isNullable as gl,map as Mi,merge as ri,now as Nn,Subject as Sa,Subscription as Sl,tap as Kp,throttle as Xp,ValueSubject as ue}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as hp,ErrorCategory as Hu,Subject as ju}from"@vkontakte/videoplayer-shared/evergreen";var mp=18,zu=!1;try{zu=O.browser.isSafari&&!!O.browser.safariVersion&&O.browser.safariVersion<=mp}catch(n){console.error(n)}var En=class{constructor(e){this.bufferFull$=new ju;this.error$=new ju;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!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:Hu.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 s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};zu&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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)&&!this.abortRequested)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:Hu.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:hp(t)}}},Qu=En;var Ti=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 Ut,assertNonNullable as He,ErrorCategory as Mt,fromEvent as $n,getExponentialDelay as Rn,isNonNullable as Ei,isNullable as we,now as na,once as Op,Subject as Fp,Subscription as _p,ValueSubject as ii}from"@vkontakte/videoplayer-shared/evergreen";var j=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,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}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 Ii=class extends j{};var er=class extends j{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,a=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(a);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var tr=class extends j{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 ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends j{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var rr=class extends te{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var sr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ar=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var ei=class extends te{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(),s=r>>>31,a=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var nr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var or=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ur=class extends te{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 lr=class extends te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var cr=class extends te{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var dr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pr=class extends te{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 hr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var mr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fr=class extends te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var br=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gr=class extends te{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 Sr=class extends te{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 vr=class extends te{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 yr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Tr=class extends te{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var bp={ftyp:tr,moov:ir,mvhd:rr,moof:sr,mdat:ar,sidx:ei,trak:nr,mdia:dr,mfhd:fr,tkhd:pr,traf:br,tfhd:gr,tfdt:Sr,trun:vr,minf:hr,sv3d:or,st3d:ur,prhd:lr,proj:mr,equi:cr,uuid:er,stbl:yr,stsd:Tr,avc1:Ir,unknown:Ii},At=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!a.size)break;t.push(a),i+=a.size}catch{break}return t}createBox(e,t){let i=bp[e];return i?new i(t,new n):new Ii(t,new n)}};var Nt=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 Sp=new TextDecoder("ascii"),vp=n=>Sp.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",yp=n=>{let e=new ei(n,new At),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,o})},Tp=(n,e)=>{let i=new At().parse(n),r=new Nt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let o=s[0],u=a[a.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,c)},Ip=n=>{let t=new At().parse(n),i=new Nt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},xp=n=>{let t=new At().parse(n);return new Nt(t).find("sidx")?.timescale},Ep=(n,e)=>{let i=new At().parse(n),s=new Nt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=a.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},kp=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new At().parse(n),r=new Nt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.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},Wu={validateData:vp,parseInit:kp,getIndexRange:()=>{},parseSegments:yp,parseFeedableSegmentChunk:Tp,getChunkEndTime:Ep,getServerLatencyTimestamps:Ip,getTimescaleFromIndex:xp};import{assertNonNullable as wn,isNonNullable as Ku,isNullable as Ap}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as wp}from"@vkontakte/videoplayer-shared/evergreen";var qu={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"}},Gu=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=xr(n,t),r=i in qu,s=r?qu[i].type:"binary",a=n.getUint8(t),o=0;a&128?o=1:a&64?o=2:a&32?o=3:a&16?o=4:a&8?o=5:a&4?o=6:a&2?o=7:a&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),l=a&255>>o,p=xr(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+d):h=new DataView(n.buffer,n.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},xr=(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},ot=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return xr(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:wp(e)}},ti=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Gu(i);if(!e(r))return;r.type==="master"&&ti(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Yu=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Gu(n);return ti(r.value,({tag:s,type:a,value:o})=>(s===17143?e=ot(o,a):s===17026?t=ot(o,a):s===17029&&(i=ot(o,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Xu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Pp=[231,22612,22743,167,171,163,160,175],Mp=n=>{let e,t,i,r,s=!1,a=!1,o=!1,u,l,p=!1,c=0;return ti(n,({tag:d,type:h,value:m,valueSize:f})=>{if(d===21419){let b=ot(m,h);l=xr(b)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+f):d===357149030?s=!0:d===290298740?a=!0:d===2807729?i=ot(m,h):d===17545?r=ot(m,h):d===21420&&l===475249515?u=ot(m,h):d===374648427?ti(m,({tag:b,type:S,value:E})=>b===30321?(p=ot(E,S)===1,!1):!0):s&&a&&Xu.includes(d)&&(o=!0),!o}),wn(e,"Failed to parse webm Segment start"),wn(t,"Failed to parse webm Segment end"),wn(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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Lp=n=>{if(Ap(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Bp=(n,e)=>{let t=!1,i=!1,r=o=>Ku(o.time)&&Ku(o.position),s=[],a;return ti(n,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=ot(l,u));break;case 183:break;case 241:a&&(a.position=ot(l,u));break;default:t&&Xu.includes(o)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((o,u)=>{let{time:l,position:p}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},$p=n=>{let e=0,t=!1;try{ti(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Pp.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},Ju={validateData:Yu,parseInit:Mp,getIndexRange:Lp,parseSegments:Bp,parseFeedableSegmentChunk:$p};var Er=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ju;case"mp4":return Wu}}throw new ReferenceError(`Unsupported mime type ${n}`)};var xi=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),o=s+a;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Cp,isNullable as sl}from"@vkontakte/videoplayer-shared/evergreen";var aa=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Zu=n=>{try{let e=Rp(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(o=>{let u=a[o];(typeof u>"u"||u==="")&&delete a[o]}),a}return null}catch{return null}};function Rp(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
115
+ [selected audio track] ${x?.id}
116
+ `}),x};var Ee=n=>new URL(n).hostname;import{assertNever as Vu,assertNonNullable as Cu,combine as sp,debounce as ap,ErrorCategory as Ou,filter as Fu,filterChanged as np,isNonNullable as In,map as ra,merge as _u,observableFrom as op,once as up,Subscription as lp,ValueSubject as xn,videoQualityToHeight as Nu,videoSizeToQuality as cp}from"@vkontakte/videoplayer-shared/evergreen";var Lu=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"))},Ue=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!Lu(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return Lu(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as ta,isNullable as Nd,assertNonNullable as Yi}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Bu,assertNonNullable as ea,now as Fd}from"@vkontakte/videoplayer-shared/evergreen";function Te(){return Fd()}function Sn(n){return Te()-n}function vn(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,o,u=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let l=a.indexOf("?")>-1?"&":"?";return u&&(a+=l+"lowLat=1",l="&"),o&&(a+=l+"_rnd="+Math.floor(999999999*Math.random())),a}}}function $u(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function vi(n,e,t,i){let r=window.XMLHttpRequest,s,a,o,u=!1,l=0,p,c,d=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;ea(p);let y=Sn(p),T;if(y<f){T=f-y,setTimeout(b,T);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,L()},S=y=>(s=y,R),x=y=>(c=y,R),v=()=>(h="json",R),I=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},E=y=>(d=y,R),L=()=>{p=Te(),a=new r,a.open("get",n);let y=0,T,A=0,ee=()=>(ea(p),Math.max(p,Math.max(T||0,A||0)));if(s&&a.addEventListener("progress",$=>{let N=Te();s.updateChunk&&$.loaded>y&&(s.updateChunk(ee(),$.loaded-y),y=$.loaded,T=N)}),o&&(a.timeout=o,a.addEventListener("timeout",()=>I())),a.addEventListener("load",()=>{if(u)return;ea(a);let $=a.status;if($>=200&&$<300){let{response:N,responseType:Y}=a,re=N?.byteLength;if(typeof re=="number"&&s){let he=re-y;he&&s.updateChunk&&s.updateChunk(ee(),he)}Y==="json"&&(!N||!Object.values(N).length)?I():(c&&c(),e(N))}else I()}),a.addEventListener("error",()=>{I()}),d){let $=()=>{ea(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(A=Te(),a.removeEventListener("readystatechange",$))};a.addEventListener("readystatechange",$)}return a.responseType=h,a.send(),R},R={withBitrateReporting:S,withParallel:E,withJSONResponse:v,withRetryCount:y=>(l=y,R),withRetryInterval:(y,T)=>(Bu(y)&&(f=y),Bu(T)&&(m=T),R),withTimeout:y=>(o=y,R),withFinally:x,send:L,abort:()=>{a&&(a.abort(),a=void 0),u=!0,c&&c()}};return R}var qi=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 s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,o=s.end-s.start;i+=a;let u=s.bytes*a/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/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 Gi=class{constructor(e,t,i,r,s){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=s}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=Te(),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)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=vi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_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=Te();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 s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._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(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,s),s}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}};import{Subject as Ud}from"@vkontakte/videoplayer-shared/evergreen";var ia=1e4,yn=3;var Hd=6e4,jd=10,zd=1,Qd=500,Ki=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Ud,this.chunkRateEstimator=new qi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=vn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=vn(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}, details: ${e.error?.message}`),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&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*(O.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!yu({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ta(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=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 a=()=>{$u(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Gi(yn,ia,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,s=!1,a=null,o=null,u=null,l=null,p=!1,c=()=>{let I=s&&(!p||p===this.rep);return I||t("Not running!"),I},d=(I,E,L)=>{u&&u.abort(),u=vi(this.urlResolver.resolve(I,!1),E,L,()=>this._retryCallback()).withTimeout(ia).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yn).withFinally(()=>{u=null}).send()},h=(I,E,L)=>{Yi(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let E=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),i.playbackRate=I)},f=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=Te()-1e4,V=0;for(let w=0;w<this.bufferStates.length;w++){let g=this.bufferStates[w];I=Math.min(I,g.buf),g.ts<L&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${I} drop=${V} jitter=${this.sourceJitter}`);let k=I-zd;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?m(1.15):k>1?m(1.1):k>.3?m(1.05):m(1)}},S=I=>{let E,L=()=>E&&E.start?E.start.length:0,V=$=>E.start[$]/1e3,k=$=>E.dur[$]/1e3,w=$=>E.fragIndex+$,g=($,N)=>({chunkIdx:w($),startTS:V($),dur:k($),discontinuity:N}),R=()=>{let $=0;if(E&&E.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,re=N;this.sourceJitter>1&&(re+=this.sourceJitter-1);let he=E.dur.length-1;for(;he>=0&&(re-=E.dur[he],!(re<=0));--he);$=Math.min(he,E.dur.length-1-Y),$=Math.max($,0)}return g($,!0)},y=$=>{let N=L();if(!(N<=0)){if(ta($)){for(let Y=0;Y<N;Y++)if(V(Y)>$)return g(Y)}return R()}},T=$=>{let N=L(),Y=$?$.chunkIdx+1:0,re=Y-E.fragIndex;if(!(N<=0)){if(!$||re<0||re-N>jd)return t(`Resync: offset=${re} bChunks=${N} chunk=`+JSON.stringify($)),R();if(!(re>=N))return g(Y-E.fragIndex,!1)}},A=($,N,Y)=>{l&&l.abort(),l=vi(this.urlResolver.resolve($,!0,this.lowLatency),N,Y,()=>this._retryCallback()).withTimeout(ia).withRetryCount(yn).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,N)=>{A(I,Y=>{if(!c())return;E=Y;let re=!!E.lowLatency;re!==this.lowLatency&&f(re);let he=0;for(let se=0;se<E.dur.length;++se)he+=E.dur[se];he>0&&(Yi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(y(N))},()=>this._handleNetworkError())},nextChunk:T}},x=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Yi(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:I=>{let{videoElement:E,logger:L}=this.params,V=S(e.jidxUrl),k,w,g,R,y=0,T,A,ee,$=()=>{T&&(clearTimeout(T),T=void 0);let D=Math.max(Qd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=y+D,me=Te(),J=Math.min(1e4,Se-me);y=me;let fe=()=>{l||c()&&V.seek(()=>{c()&&(y=Te(),N(),$())})};J>0?T=window.setTimeout(()=>{this.paused?$():fe()},J):fe()},N=()=>{let D;for(;D=V.nextChunk(R);)R=D,X(D);let Se=V.nextChunk(g);if(Se){if(g&&Se.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?$():(x(),this._initPlayerWith(e));return}se(Se)}else $()},Y=(D,Se)=>{if(!c()||!this.sourceBuffer)return;let me,J,fe,ze=Pe=>{window.setTimeout(()=>{c()&&Y(D,Se)},Pe)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),ze(100);else{let Pe=Te(),oe=E.currentTime;!this.paused&&E.buffered.length>1&&A===oe&&Pe-ee>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),A!==oe&&(A=oe,ee=Pe);let Qe=this._getBufferSizeSec();if(Qe>30)L(`Buffered ${Qe} seconds; delaying appendBuffer`),ze(2e3);else try{this.sourceBuffer.appendBuffer(D),this.videoPlayStarted?(this.bufferStates.push({ts:Pe,buf:Qe}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(ge){if(ge.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),fe=this.sourceBuffer.buffered.length,fe!==0&&(me=this.sourceBuffer.buffered.start(0),J=oe,J-me>4&&this.sourceBuffer.remove(me,J-3)),ze(1e3);else throw ge}}},re=()=>{w&&k&&(L([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(g)]),Y(w,function(){w=null,N()}))},he=D=>e.fragUrlTemplate.replace("%%id%%",D.chunkIdx),se=D=>{c()&&h(he(D),(Se,me)=>{if(c()){if(me/=1e3,w=Se,g=D,a=D.startTS,me){let J=Math.min(10,D.dur/me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*J:J}re()}},()=>this._handleNetworkError())},X=D=>{c()&&(Yi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he(D),!1)))},P=D=>{c()&&(e.cachedHeader=D,Y(D,()=>{k=!0,re()}))};s=!0,V.seek(D=>{if(c()){if(y=Te(),!D){$();return}R=D,!Nd(I)||D.startTS>I?se(D):(g=D,N())}},I),e.cachedHeader?P(e.cachedHeader):d(e.headerUrl,P,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>a},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),ta(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,Yi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ta(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(d,h)=>{let m=Te();if(this.chunkRateEstimator.addInterval(d,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-d,speed:b}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},a=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Sn(a)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,d)=>{let h=s.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=Te();c<o&&(a=d),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=vi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ia).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;Ue(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let o=[];return a?.length?(a.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(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 Wd,filter as Ru,fromEvent as qd,interval as Gd,isHigher as Yd,isInvariantQuality as Kd,isLower as Xd,merge as Jd,Subject as Du,Subscription as Zd}from"@vkontakte/videoplayer-shared/evergreen";var Tn=class{constructor(){this.onDroopedVideoFramesLimit$=new Du;this.subscription=new Zd;this.playing=!1;this.tracks=[];this.forceChecker$=new Du;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&&!Kd(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=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(qd(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Gd(this.droppedFramesChecker.checkTime).pipe(Ru(()=>this.playing),Ru(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Wd(this.droppedFramesChecker.checkTime)),i=Jd(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])=>Xd(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}},yi=Tn;import{map as ep,Observable as tp}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as ip}from"@vkontakte/videoplayer-shared/evergreen";var Xi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var rp=(n,e)=>new tp(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,o)=>{a.forEach(u=>t.next(u.isIntersecting||Xi()))},{...i,...e});r.observe(n);let s=ip(document,"visibilitychange").pipe(ep(a=>!document.hidden||Xi())).subscribe(a=>t.next(a));return()=>{r.unobserve(n),s.unsubscribe()}}),it=rp;var dp=["paused","playing","ready"],pp=["paused","playing","ready"],Ji=class{constructor(e){this.subscription=new lp;this.videoState=new _("stopped");this.representations$=new xn([]);this.droppedFramesManager=new yi;this.maxSeekBackTime$=new xn(1/0);this.zeroTime$=new xn(void 0);this.liveOffset=new Zt;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:Ou.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=Ft(r.name)??cp(r.video),o=r.bitrate/1e3,u={...r.video};if(!a)continue;let l={id:s,quality:a,bitrate:o,size:u};i.push({track:l,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),In(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(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),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 a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(pp.includes(e)&&(a||o)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&dp.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(pe(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(pe(this.params.source.url,u))}return;default:return Vu(e)}};this.textTracksManager=new tt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ou.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(_u(this.videoState.stateChangeStarted$.pipe(ra(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ra(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),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(Ee(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ne(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ra(r=>r.map(({track:s})=>s)),Fu(r=>!!r.length),up()).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(np(),ra(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(sp({zeroTime:this.zeroTime$.pipe(Fu(In)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(_e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(et(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(it(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Nu(r),min:s&&Nu(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).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 Vu(r.to)}},t)).add(_u(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,op(["init"])).pipe(ap(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),Fe(this.video)}createLiveDashPlayer(){let e=new Ki({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,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&&In(t)?t:mt(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput: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}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),a||u||s!==o){let l=e.find(({track:p})=>p.id===s)?.representation;Cu(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Cu(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",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(pe(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var Uu=Ji;var Ie=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,s=n.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as hh,assertNonNullable as mh,debounce as fh,ErrorCategory as xl,filter as Wn,filterChanged as ka,fromEvent as bh,isNonNullable as El,isNullable as gh,map as qn,merge as wa,observableFrom as Gn,once as kl,Subscription as Sh}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Zi}from"@vkontakte/videoplayer-shared/evergreen";var sa=n=>{if(!n)return{id:"EmptyResponse",category:Zi.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:Zi.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:Zi.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:Zi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Zi.PARSER,message:"Response is valid XML, but parser failed"}};var ke=(n,e,t=0)=>{for(let i=0;i<n.length;i++)if(n.start(i)*1e3-t<=e&&n.end(i)*1e3+t>e)return!0;return!1};import{abortable as Fn,assertNonNullable as Ai,combine as Pi,ErrorCategory as ut,filter as ga,filterChanged as Br,flattenObject as $r,fromEvent as $t,getTraceSubscriptionMethod as Yp,interval as _n,isNonNullable as Rr,isNullable as gl,map as Mi,merge as ri,now as Nn,Subject as Sa,Subscription as Sl,tap as Kp,throttle as Xp,ValueSubject as ue}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as hp,ErrorCategory as Hu,Subject as ju}from"@vkontakte/videoplayer-shared/evergreen";var mp=18,zu=!1;try{zu=O.browser.isSafari&&!!O.browser.safariVersion&&O.browser.safariVersion<=mp}catch(n){console.error(n)}var En=class{constructor(e){this.bufferFull$=new ju;this.error$=new ju;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!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:Hu.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 s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};zu&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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)&&!this.abortRequested)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:Hu.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:hp(t)}}},Qu=En;var Ti=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 Ut,assertNonNullable as He,ErrorCategory as Mt,fromEvent as $n,getExponentialDelay as Rn,isNonNullable as Ei,isNullable as we,now as na,once as Op,Subject as Fp,Subscription as _p,ValueSubject as ii}from"@vkontakte/videoplayer-shared/evergreen";var j=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,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}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 Ii=class extends j{};var er=class extends j{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,a=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(a);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var tr=class extends j{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 ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends j{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var rr=class extends te{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var sr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ar=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var ei=class extends te{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(),s=r>>>31,a=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var nr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var or=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ur=class extends te{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 lr=class extends te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var cr=class extends te{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var dr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pr=class extends te{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 hr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var mr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fr=class extends te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var br=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gr=class extends te{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 Sr=class extends te{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 vr=class extends te{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 yr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Tr=class extends te{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var bp={ftyp:tr,moov:ir,mvhd:rr,moof:sr,mdat:ar,sidx:ei,trak:nr,mdia:dr,mfhd:fr,tkhd:pr,traf:br,tfhd:gr,tfdt:Sr,trun:vr,minf:hr,sv3d:or,st3d:ur,prhd:lr,proj:mr,equi:cr,uuid:er,stbl:yr,stsd:Tr,avc1:Ir,unknown:Ii},At=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!a.size)break;t.push(a),i+=a.size}catch{break}return t}createBox(e,t){let i=bp[e];return i?new i(t,new n):new Ii(t,new n)}};var Nt=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 Sp=new TextDecoder("ascii"),vp=n=>Sp.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",yp=n=>{let e=new ei(n,new At),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,o})},Tp=(n,e)=>{let i=new At().parse(n),r=new Nt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let o=s[0],u=a[a.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,c)},Ip=n=>{let t=new At().parse(n),i=new Nt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},xp=n=>{let t=new At().parse(n);return new Nt(t).find("sidx")?.timescale},Ep=(n,e)=>{let i=new At().parse(n),s=new Nt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=a.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},kp=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new At().parse(n),r=new Nt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.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},Wu={validateData:vp,parseInit:kp,getIndexRange:()=>{},parseSegments:yp,parseFeedableSegmentChunk:Tp,getChunkEndTime:Ep,getServerLatencyTimestamps:Ip,getTimescaleFromIndex:xp};import{assertNonNullable as wn,isNonNullable as Ku,isNullable as Ap}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as wp}from"@vkontakte/videoplayer-shared/evergreen";var qu={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"}},Gu=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=xr(n,t),r=i in qu,s=r?qu[i].type:"binary",a=n.getUint8(t),o=0;a&128?o=1:a&64?o=2:a&32?o=3:a&16?o=4:a&8?o=5:a&4?o=6:a&2?o=7:a&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),l=a&255>>o,p=xr(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+d):h=new DataView(n.buffer,n.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},xr=(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},ot=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return xr(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:wp(e)}},ti=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Gu(i);if(!e(r))return;r.type==="master"&&ti(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Yu=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Gu(n);return ti(r.value,({tag:s,type:a,value:o})=>(s===17143?e=ot(o,a):s===17026?t=ot(o,a):s===17029&&(i=ot(o,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Xu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Pp=[231,22612,22743,167,171,163,160,175],Mp=n=>{let e,t,i,r,s=!1,a=!1,o=!1,u,l,p=!1,c=0;return ti(n,({tag:d,type:h,value:m,valueSize:f})=>{if(d===21419){let b=ot(m,h);l=xr(b)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+f):d===357149030?s=!0:d===290298740?a=!0:d===2807729?i=ot(m,h):d===17545?r=ot(m,h):d===21420&&l===475249515?u=ot(m,h):d===374648427?ti(m,({tag:b,type:S,value:x})=>b===30321?(p=ot(x,S)===1,!1):!0):s&&a&&Xu.includes(d)&&(o=!0),!o}),wn(e,"Failed to parse webm Segment start"),wn(t,"Failed to parse webm Segment end"),wn(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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Lp=n=>{if(Ap(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Bp=(n,e)=>{let t=!1,i=!1,r=o=>Ku(o.time)&&Ku(o.position),s=[],a;return ti(n,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=ot(l,u));break;case 183:break;case 241:a&&(a.position=ot(l,u));break;default:t&&Xu.includes(o)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((o,u)=>{let{time:l,position:p}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},$p=n=>{let e=0,t=!1;try{ti(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Pp.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},Ju={validateData:Yu,parseInit:Mp,getIndexRange:Lp,parseSegments:Bp,parseFeedableSegmentChunk:$p};var Er=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ju;case"mp4":return Wu}}throw new ReferenceError(`Unsupported mime type ${n}`)};var xi=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),o=s+a;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Vp,isNullable as sl}from"@vkontakte/videoplayer-shared/evergreen";var aa=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var Zu=n=>{try{let e=Rp(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(o=>{let u=a[o];(typeof u>"u"||u==="")&&delete a[o]}),a}return null}catch{return null}};function Rp(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
117
117
  (?<language>${`(?:[a-z]{2,3}(?:-${n})?|[a-z]{4}|[a-z]{5,8})`})
118
118
  (-(?<script>[a-z]{4}))?
119
119
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
120
120
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
121
121
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
122
122
  (?:-(?<privateuse>(?:${e})))?
123
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}import{videoSizeToQuality as Dp}from"@vkontakte/videoplayer-shared/evergreen";var el=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let o=(s?Ft(s):void 0)??Dp({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},tl=({id:n,bitrate:e})=>({id:n,bitrate:e}),il=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),rl=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Pn=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Mn=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Ln=n=>"url"in n,De=n=>n.type==="template",kr=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var al=n=>{if(!n?.startsWith("P"))return;let e=(a,o)=>{let u=a?parseFloat(a.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,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Pt=(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,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(o,u)=>sl(s)?o:sl(u)?s:s.padStart(parseInt(u,10),"0"))}return t},nl=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(w=>w.textContent?.trim()??""),o=a.at(0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,E=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((w,g)=>({...w,[g.id]:g.children}),{}),x=v.reduce((w,g)=>({...w,[g.id]:g.getAttribute("duration")}),{});E?S=al(E):Object.values(x).filter(w=>w).length&&!u?S=Object.values(x).reduce((w,g)=>w+(al(g)??0),0):f&&(S=parseInt(f,10));let L=0,C=s.getAttribute("profiles")?.split(",")??[];for(let w of v.map(g=>g.id))for(let g of I[w]){let R=g.getAttribute("id")??"id"+(L++).toString(10),y=g.getAttribute("mimeType")??"",T=g.getAttribute("codecs")??"",A=g.getAttribute("contentType")??y?.split("/")[0],ee=g.getAttribute("profiles")?.split(",")??[],$=Zu(g.getAttribute("lang")??"")??{},N=g.querySelector("Label")?.textContent?.trim()??void 0,G=g.querySelectorAll("Representation"),re=g.querySelector("SegmentTemplate"),he=g.querySelector("Role")?.getAttribute("value")??void 0,se=A,X={id:R,language:$.language,isDefault:he==="main",label:N,codecs:T,hdr:se==="video"&&xi(T),mime:y,representations:[]};for(let P of G){let D=P.getAttribute("lang")??void 0,Se=N??g.getAttribute("label")??P.getAttribute("label")??void 0,me=P.querySelector("BaseURL")?.textContent?.trim()??"",J=new URL(me||o,e).toString(),fe=P.getAttribute("mimeType")??y,ze=P.getAttribute("codecs")??T??"",Pe;if(A==="text"){let oe=P.getAttribute("id")||"",Qe=$.privateuse?.includes("x-auto")||oe.includes("_auto"),ge=P.querySelector("SegmentTemplate");if(ge){let rt={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},bt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(ge.getAttribute("startNumber")??"",10)??1,We=parseInt(ge.getAttribute("timescale")??"",10),Yt=ge.querySelectorAll("SegmentTimeline S")??[],qe=ge.getAttribute("media");if(!qe)continue;let St=[],vt=0,yt="",Ge=0,st=gt,W=0;for(let ae of Yt){let Me=parseInt(ae.getAttribute("d")??"",10),Z=parseInt(ae.getAttribute("r")??"",10)||0,ve=parseInt(ae.getAttribute("t")??"",10);W=Number.isFinite(ve)?ve:W;let Le=Me/We*1e3,Ye=W/We*1e3;for(let ce=0;ce<Z+1;ce++){let ye=Pt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:(W+ce*Me).toString(10)}),Ke=(Ye??0)+ce*Le,nt=Ke+Le;st++,St.push({time:{from:Ke,to:nt},url:ye})}W+=(Z+1)*Me,vt+=(Z+1)*Le}Ge=W/We*1e3,yt=Pt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:W.toString(10)});let at={time:{from:Ge,to:1/0},url:yt},be={type:"template",baseUrl:J,segmentTemplateUrl:qe,initUrl:"",totalSegmentsDurationMs:vt,segments:St,nextSegmentBeyondManifest:at,timescale:We};Pe={id:oe,kind:"text",segmentReference:be,profiles:[],duration:S,bitrate:bt,mime:"",codecs:"",width:0,height:0,isAuto:Qe}}else Pe={id:oe,isAuto:Qe,kind:"text",url:J}}else{let oe=P.getAttribute("contentType")??fe?.split("/")[0]??A,Qe=g.getAttribute("profiles")?.split(",")??[],ge=parseInt(P.getAttribute("width")??"",10),rt=parseInt(P.getAttribute("height")??"",10),bt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,gt=P.getAttribute("frameRate")??"",We=P.getAttribute("quality")??void 0,Yt=gt?aa(gt):void 0,qe=P.getAttribute("id")??"id"+(L++).toString(10),St=oe==="video"?`${rt}p`:oe==="audio"?`${bt}Kbps`:ze,vt=`${qe}@${St}`,yt=[...C,...ee,...Qe],Ge,st=P.querySelector("SegmentBase"),W=P.querySelector("SegmentTemplate")??re;if(st){let be=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ae,Me]=be.split("-").map(ye=>parseInt(ye,10)),Z={from:ae,to:Me},ve=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[Le,Ye]=ve?ve.split("-").map(ye=>parseInt(ye,10)):[],ce=ve?{from:Le,to:Ye}:void 0;Ge={type:"byteRange",url:J,initRange:Z,indexRange:ce}}else if(W){let be={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},ae=parseInt(W.getAttribute("timescale")??"",10),Me=W.getAttribute("initialization")??"",Z=W.getAttribute("media"),ve=parseInt(W.getAttribute("startNumber")??"",10)??1,Le=Pt(Me,be);if(!Z)throw new ReferenceError("No media attribute in SegmentTemplate");let Ye=W.querySelectorAll("SegmentTimeline S")??[],ce=[],ye=0,Ke="",nt=0;if(Ye.length){let Tt=ve,ne=0;for(let Xe of Ye){let de=parseInt(Xe.getAttribute("d")??"",10),Be=parseInt(Xe.getAttribute("r")??"",10)||0,It=parseInt(Xe.getAttribute("t")??"",10);ne=Number.isFinite(It)?It:ne;let Kt=de/ae*1e3,Ja=ne/ae*1e3;for(let xt=0;xt<Be+1;xt++){let Za=Pt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:(ne+xt*de).toString(10)}),Fi=(Ja??0)+xt*Kt,en=Fi+Kt;Tt++,ce.push({time:{from:Fi,to:en},url:Za})}ne+=(Be+1)*de,ye+=(Be+1)*Kt}nt=ne/ae*1e3,Ke=Pt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:ne.toString(10)})}else if(Cp(S)){let ne=parseInt(W.getAttribute("duration")??"",10)/ae*1e3,Xe=Math.ceil(S/ne),de=0;for(let Be=1;Be<Xe;Be++){let It=Pt(Z,{...be,segmentNumber:Be.toString(10),segmentTime:de.toString(10)});ce.push({time:{from:de,to:de+ne},url:It}),de+=ne}nt=de,Ke=Pt(Z,{...be,segmentNumber:Xe.toString(10),segmentTime:de.toString(10)})}let Xa={time:{from:nt,to:1/0},url:Ke};Ge={type:"template",baseUrl:J,segmentTemplateUrl:Z,initUrl:Le,totalSegmentsDurationMs:ye,segments:ce,nextSegmentBeyondManifest:Xa,timescale:ae}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oe||!fe)continue;let at={video:"video",audio:"audio",text:"text"}[oe];if(!at)continue;se||=at,Pe={id:vt,kind:at,segmentReference:Ge,profiles:yt,duration:S,bitrate:bt,mime:fe,codecs:ze,width:ge,height:rt,fps:Yt,quality:We}}X.language||=D,X.label||=Se,X.mime||=fe,X.codecs||=ze,X.hdr||=se==="video"&&xi(ze),X.representations.push(Pe)}if(se){let P=r[se].find(D=>D.id===X.id);if(P&&X.representations.every(D=>De(D.segmentReference)))for(let D of P.representations){let me=X.representations.find(fe=>fe.id===D.id)?.segmentReference,J=D.segmentReference;J.segments.push(...me.segments),J.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else r[se].push(X)}}return{duration:S,streams:r,baseUrls:a,live:b}};import{isNonNullable as ol}from"@vkontakte/videoplayer-shared/evergreen";var V=(n,e)=>ol(n)&&ol(e)&&n.readyState==="open"&&Vp(n,e);function Vp(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}var wr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ii(0);this.currentLowLatencySegmentLength$=new ii(0);this.currentSegmentLength$=new ii(0);this.onLastSegment$=new ii(!1);this.fullyBuffered$=new ii(!1);this.playingRepresentation$=new ii(void 0);this.playingRepresentationInit$=new ii(void 0);this.error$=new Fp;this.gaps=[];this.subscription=new _p;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ut(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Qu(this.sourceBuffer),this.subscription.add($n(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),o??={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(o)})),this.subscription.add($n(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,a*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(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(s))}.bind(this));this.switchTo=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(we(s)||we(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),He(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();Ei(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(we(s)||we(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),He(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();Ei(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ut(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 l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!De(p.segmentReference))return;let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);He(r);let s=this.segments.get(i);He(s,"No segments for starting representation");let a=this.initData.get(i);if(He(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Ut(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);He(s,`No such representation ${i}`);let a=this.segments.get(i),o=this.initData.get(i);if(we(o)||we(a)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),a=this.segments.get(i),He(a,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ei(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!we(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(we(e)||we(this.downloadingRepresentationId)||we(this.playingRepresentationId)||we(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Ei(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(p=>e>=p.time.from&&e<p.time.to);Ei(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&Ti(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))p="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(u,t,p).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<a),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Ei(t.duration)&&t.duration-i>0&&!this.isLive&&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=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-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)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!De(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],o=a.at(-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!De(r))return;let s=this.segments.get(i.id)??[],a=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Pt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.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)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:d,to:h}},m)=>{let f=d<=i&&h>=i,b=d>i||f||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&d<=i+S||h<=i+S;return(c==="none"||c==="partially_ejected"&&b&&E&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(ke(this.sourceBuffer.buffered,d)&&ke(this.sourceBuffer.buffered,h)))&&b&&E});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,a=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<s.length&&(a<=l||o<=p);c++){let d=s[c];if(a+=d.byte.to+1-d.byte.from,o+=d.time.to+1-d.time.from,d.status==="none"||d.status==="partially_ejected")u.push(d);else break}return u}async loadSegments(e,t,i="auto"){De(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ut(o,async function*(){let p=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(a,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=na(),!p)return;let c=new DataView(p),d=Er(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),kr(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())De(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}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:s,signal:a,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Ut(a,async function*(){let u=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),$n(window,"online").pipe(Op()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:a,priority:i}),this.lastDataObtainedTimestampMs=na(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),kr(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(De(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:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=na(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!De(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:s}=this.downloadAbortController,a=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=na();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:a}}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:s}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Er(a.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await a();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(!h)continue;let f=Er(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?b:f.parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(we(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&O.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ke(this.sourceBuffer.buffered,e.segment.time.from,100)&&ke(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ln(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===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",a=(!i&&this.failedDownloads>0?Ut(this.destroyAbortController.signal,async function*(){let o=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Er(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&De(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:Mt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,a),a}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){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||we(e))return!1;let r=[],s=0,a=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(s>=t)return r;r.push({...u.time}),r=a(r);let l=Ln(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||we(e)?0:Ie(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let a=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),a<i.time.to&&a>i.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(we(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||we(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=a&&p.to+t>=o),l=e.filter(p=>a>=p.from&&a<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ht=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var oa=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 Ar,assertNever as ul,fromEvent as ll,merge as Np,now as Pr,Subscription as Up,Subject as cl,ValueSubject as Dn,flattenObject as ki,ErrorCategory as Mr}from"@vkontakte/videoplayer-shared/evergreen";var ua=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ca=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Dn(void 0);this.lastConnectionReused$=new Dn(void 0);this.lastRequestFirstBytes$=new Dn(void 0);this.recoverableError$=new cl;this.error$=new cl;this.abortAllController=new AbortController;this.subscription=new Up;this.fetchManifest=Ar(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ht(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ua(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(la);return r?(t.log("success",ki({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ki({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ar(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),l=R.toString();break}default:ul(t)}this.requestQuic&&(l=Ht(l));let d=this.abortAllController.signal,h;if(a){let R=new AbortController;if(h=Np(ll(this.abortAllController.signal,"abort"),ll(a,"abort")).subscribe(()=>{try{R.abort()}catch(y){la(y)}}),this.subscription.add(h),this.abortAllController.signal.aborted||a.aborted)try{R.abort()}catch(y){la(y)}d=R.signal}let m=Pr();c.log("startRequest",ki({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:p,signal:d}),b=Pr();if(!f)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){h?.unsubscribe();let R=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:R}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let R=Pr(),y={requestStartedAt:m,requestEndedAt:R,duration:R-m};return c.log("endRequest",ki(y)),c.end(),f.arrayBuffer()}let[S,E]=f.body.tee(),v=S.getReader();o&&this.throughputEstimator?.trackStream(E,u);let I=0,x=new Uint8Array(0),L=!1,C=R=>{h?.unsubscribe(),L=!0,la(R)},k=Ar(d,async function*({done:R,value:y}){if(I===0&&this.lastRequestFirstBytes$.next(Pr()-m),d.aborted){h?.unsubscribe();return}if(!R&&y){let T=new Uint8Array(x.length+y.length);T.set(x),T.set(y,x.length),x=T,I+=y.byteLength,r?.(new DataView(x.buffer),I),yield v?.read().then(k,C)}}.bind(this));yield v?.read().then(k,C),h?.unsubscribe();let w=Pr(),g={failed:L,requestStartedAt:m,requestEndedAt:w,duration:w-m};return L?(c.error("endRequest",ki(g)),c.end(),null):(c.log("endRequest",ki(g)),c.end(),x.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ar(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,o=s,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),o=Math.max(p,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-a,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=Ar(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(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oa(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:ul(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Mr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Mr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Mr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Mr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Mr.FATAL})}}},la=n=>{if(!kr(n))throw n};var Lt=(n,e,t)=>t*e+(1-t)*n,Cn=(n,e)=>n.reduce((t,i)=>t+i,0)/e,dl=(n,e,t,i)=>{let r=0,s=t,a=Cn(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[s]>a?r++:r--,s=(n.length+s-1)%n.length;return Math.abs(r)===o};import{isNullable as Hp,ValueSubject as pl}from"@vkontakte/videoplayer-shared/evergreen";var jt=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 pl(e.initial),this.debounced$=new pl(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Re(`raw_${t}`),this.smoothedSeries$=new Re(`smoothed_${t}`),this.reportedSeries$=new Re(`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),s=this.smoothed+this.params.deviationFactor*r,a=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>s||this.smoothed<a)&&(Hp(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 da=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Lt(this.slow,e,this.params.emaAlphaSlow),this.fast=Lt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var pa=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Cn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Lt(this.emaSmoothed,e,this.params.emaAlpha);let i=dl(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ha=class extends jt{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?Lt(this.smoothed,t,this.params.emaAlpha):t}};var Bt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new da({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new pa({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new ha({initial:e,label:"liveEdgeDelay",...t})}};var wi=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as jp,ValueSubject as zp}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class n{constructor(e,t){this.currentRepresentation$=new zp(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!jp(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,o=r.segments[s-1].time.to;if(e<a||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&De(t.segmentReference))}};import{assertNever as fa}from"@vkontakte/videoplayer-shared/evergreen";var hl=(n,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:a}=O.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return n.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return a;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return fa(l)}})},ma=n=>{let{webmDecodingInfo:e}=O.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(n){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:fa(n)}return[t,i]},ml=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ma(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(O.device.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",...ma(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ma(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ma(n),...r,"HLS","HLS_ONDEMAND"];default:fa(e)}return O.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},fl=({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"],s=[...i,...r],a=[...r,...i],o,u=O.device.isMac&&O.browser.isSafari;if(O.device.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=a;break}default:fa(n)}else O.video.nativeHlsSupported&&!u?o=a:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Vn=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ba=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)};var Jp=["timeupdate","progress","play","seeked","stalled","waiting"],Zp=["timeupdate","progress","loadeddata","playing","seeked"];var va=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Sl;this.representationSubscription=new Sl;this.state$=new _("none");this.currentVideoRepresentation$=new ue(void 0);this.currentVideoRepresentationInit$=new ue(void 0);this.currentAudioRepresentation$=new ue(void 0);this.currentVideoSegmentLength$=new ue(0);this.currentAudioSegmentLength$=new ue(0);this.error$=new Sa;this.lastConnectionType$=new ue(void 0);this.lastConnectionReused$=new ue(void 0);this.lastRequestFirstBytes$=new ue(void 0);this.currentLiveTextRepresentation$=new ue(null);this.isLive$=new ue(!1);this.isActiveLive$=new ue(!1);this.isLowLatency$=new ue(!1);this.liveDuration$=new ue(0);this.liveSeekableDuration$=new ue(0);this.liveAvailabilityStartTime$=new ue(0);this.liveStreamStatus$=new ue(void 0);this.bufferLength$=new ue(0);this.liveLatency$=new ue(void 0);this.liveLoadBufferLength$=new ue(0);this.livePositionFromPlayer$=new ue(0);this.currentStallDuration$=new ue(0);this.videoLastDataObtainedTimestamp$=new ue(0);this.fetcherRecoverableError$=new Sa;this.fetcherError$=new Sa;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Sa;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Fn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(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:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Fn(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=nl(e??"",this.manifestUrlString)}catch(a){let o=sa(e)??{id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(o)}if(!t)return null;let i=(a,o,u)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((o-a)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let u=t.streams[a].filter(({mime:c,codecs:d})=>i(a,c,d)),l=new Set(u.map(({codecs:c})=>c)),p=ba(l);if(p&&(r[a]=u.filter(({codecs:c})=>c.startsWith(p))),a==="video"){let c=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);O.display.isHDR&&c&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",$r(s)),s}.bind(this));this.initRepresentations=Fn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",$r({initialVideo:e,initialAudio:t,sourceHls:i})),Ai(this.manifest),Ai(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add($t(d,"error").pipe(ga(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Vs():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&mi())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new wr("video",this.source,o,a),this.bufferManagers=[this.videoBufferManager],Rr(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new wr("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}Lr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Lr(this.manifest.streams.text,a)),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$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ri(...Zp.map(d=>$t(this.element,d))).pipe(Mi(d=>this.element?Ie(this.element.buffered,this.element.currentTime*1e3):0),Br(),Kp(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ri($t(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Br()).subscribe(h=>this.liveStreamEndTimestamp=Nn())),this.subscription.add($t(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=_n(1e3).subscribe(h=>{let m=Vt(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add($t(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Pi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mi(({isActiveLive:h,isLowLatency:m})=>h&&m),Br()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||wi(this.element,1)})),this.representationSubscription.add(Pi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ga(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Pi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ga(({isLive:h})=>h),Br((h,m)=>m.bufferLength<h.bufferLength),Mi(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=Vt(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Pi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(v)>S&&(I=1+Math.sign(v)*E),wi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add(Pi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Xp(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=Vt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,x=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),C=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(C);let k="none";if(L?k="active_low_latency":this.isLowLatency$.getValue()&&C?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&x<E?k="live_forward_buffering":x<E+I&&(k="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),k==="live_forward_buffering"||k==="live_with_target_offset"){let w=d-(E+v),g=this.normolizeLiveOffset(Math.trunc(b+w/f)),R=Math.abs(g-b),y=0;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?y=b:g>0&&R>this.tuning.dashCmafLive.offsetCalculationError&&(y=g),this.manifestUrlString=pe(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ri(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Mi(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=ri(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Mi(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=Pi({allBuffersFull:l,someBufferEnded:p}).pipe(Br(),Mi(({allBuffersFull:d,someBufferEnded:h})=>d&&h),ga(d=>d));if(this.representationSubscription.add(ri(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ri(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),De(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Rr(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=_n(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ut.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ca({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Bt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Ai(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Nn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=pe(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Ai(this.element),this.state$.setState("running"),this.subscription.add(ri(...Jp.map(e=>$t(this.element,e)),$t(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add($t(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add($t(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ke(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Nn(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,p=u<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",$r(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=_n(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ut.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Ai(this.element),Ai(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),this.warmUpMediaSourceIfNeeded(i),ke(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(gl(this.element)||gl(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",$r({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Rr(this.element)&&Rr(this.source)&&Rr(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Yp(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-a<=r&&u.to+a>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",$r(i)))}}};var ya=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ta=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,s=t-this.camera.orientation.y,a=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:s,z:a},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 yl=`attribute vec2 a_vertex;
123
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}import{videoSizeToQuality as Dp}from"@vkontakte/videoplayer-shared/evergreen";var el=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let o=(s?Ft(s):void 0)??Dp({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},tl=({id:n,bitrate:e})=>({id:n,bitrate:e}),il=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),rl=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Pn=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Mn=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Ln=n=>"url"in n,De=n=>n.type==="template",kr=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var al=n=>{if(!n?.startsWith("P"))return;let e=(a,o)=>{let u=a?parseFloat(a.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,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Pt=(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,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(o,u)=>sl(s)?o:sl(u)?s:s.padStart(parseInt(u,10),"0"))}return t},nl=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(w=>w.textContent?.trim()??""),o=a.at(0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,x=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((w,g)=>({...w,[g.id]:g.children}),{}),E=v.reduce((w,g)=>({...w,[g.id]:g.getAttribute("duration")}),{});x?S=al(x):Object.values(E).filter(w=>w).length&&!u?S=Object.values(E).reduce((w,g)=>w+(al(g)??0),0):f&&(S=parseInt(f,10));let L=0,V=s.getAttribute("profiles")?.split(",")??[];for(let w of v.map(g=>g.id))for(let g of I[w]){let R=g.getAttribute("id")??"id"+(L++).toString(10),y=g.getAttribute("mimeType")??"",T=g.getAttribute("codecs")??"",A=g.getAttribute("contentType")??y?.split("/")[0],ee=g.getAttribute("profiles")?.split(",")??[],$=Zu(g.getAttribute("lang")??"")??{},N=g.querySelector("Label")?.textContent?.trim()??void 0,Y=g.querySelectorAll("Representation"),re=g.querySelector("SegmentTemplate"),he=g.querySelector("Role")?.getAttribute("value")??void 0,se=A,X={id:R,language:$.language,isDefault:he==="main",label:N,codecs:T,hdr:se==="video"&&xi(T),mime:y,representations:[]};for(let P of Y){let D=P.getAttribute("lang")??void 0,Se=N??g.getAttribute("label")??P.getAttribute("label")??void 0,me=P.querySelector("BaseURL")?.textContent?.trim()??"",J=new URL(me||o,e).toString(),fe=P.getAttribute("mimeType")??y,ze=P.getAttribute("codecs")??T??"",Pe;if(A==="text"){let oe=P.getAttribute("id")||"",Qe=$.privateuse?.includes("x-auto")||oe.includes("_auto"),ge=P.querySelector("SegmentTemplate");if(ge){let rt={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},bt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(ge.getAttribute("startNumber")??"",10)??1,We=parseInt(ge.getAttribute("timescale")??"",10),Yt=ge.querySelectorAll("SegmentTimeline S")??[],qe=ge.getAttribute("media");if(!qe)continue;let St=[],vt=0,yt="",Ge=0,st=gt,W=0;for(let ae of Yt){let Me=parseInt(ae.getAttribute("d")??"",10),Z=parseInt(ae.getAttribute("r")??"",10)||0,ve=parseInt(ae.getAttribute("t")??"",10);W=Number.isFinite(ve)?ve:W;let Le=Me/We*1e3,Ye=W/We*1e3;for(let ce=0;ce<Z+1;ce++){let ye=Pt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:(W+ce*Me).toString(10)}),Ke=(Ye??0)+ce*Le,nt=Ke+Le;st++,St.push({time:{from:Ke,to:nt},url:ye})}W+=(Z+1)*Me,vt+=(Z+1)*Le}Ge=W/We*1e3,yt=Pt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:W.toString(10)});let at={time:{from:Ge,to:1/0},url:yt},be={type:"template",baseUrl:J,segmentTemplateUrl:qe,initUrl:"",totalSegmentsDurationMs:vt,segments:St,nextSegmentBeyondManifest:at,timescale:We};Pe={id:oe,kind:"text",segmentReference:be,profiles:[],duration:S,bitrate:bt,mime:"",codecs:"",width:0,height:0,isAuto:Qe}}else Pe={id:oe,isAuto:Qe,kind:"text",url:J}}else{let oe=P.getAttribute("contentType")??fe?.split("/")[0]??A,Qe=g.getAttribute("profiles")?.split(",")??[],ge=parseInt(P.getAttribute("width")??"",10),rt=parseInt(P.getAttribute("height")??"",10),bt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,gt=P.getAttribute("frameRate")??"",We=P.getAttribute("quality")??void 0,Yt=gt?aa(gt):void 0,qe=P.getAttribute("id")??"id"+(L++).toString(10),St=oe==="video"?`${rt}p`:oe==="audio"?`${bt}Kbps`:ze,vt=`${qe}@${St}`,yt=[...V,...ee,...Qe],Ge,st=P.querySelector("SegmentBase"),W=P.querySelector("SegmentTemplate")??re;if(st){let be=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ae,Me]=be.split("-").map(ye=>parseInt(ye,10)),Z={from:ae,to:Me},ve=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[Le,Ye]=ve?ve.split("-").map(ye=>parseInt(ye,10)):[],ce=ve?{from:Le,to:Ye}:void 0;Ge={type:"byteRange",url:J,initRange:Z,indexRange:ce}}else if(W){let be={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},ae=parseInt(W.getAttribute("timescale")??"",10),Me=W.getAttribute("initialization")??"",Z=W.getAttribute("media"),ve=parseInt(W.getAttribute("startNumber")??"",10)??1,Le=Pt(Me,be);if(!Z)throw new ReferenceError("No media attribute in SegmentTemplate");let Ye=W.querySelectorAll("SegmentTimeline S")??[],ce=[],ye=0,Ke="",nt=0;if(Ye.length){let Tt=ve,ne=0;for(let Xe of Ye){let de=parseInt(Xe.getAttribute("d")??"",10),Be=parseInt(Xe.getAttribute("r")??"",10)||0,It=parseInt(Xe.getAttribute("t")??"",10);ne=Number.isFinite(It)?It:ne;let Kt=de/ae*1e3,Ja=ne/ae*1e3;for(let xt=0;xt<Be+1;xt++){let Za=Pt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:(ne+xt*de).toString(10)}),Fi=(Ja??0)+xt*Kt,en=Fi+Kt;Tt++,ce.push({time:{from:Fi,to:en},url:Za})}ne+=(Be+1)*de,ye+=(Be+1)*Kt}nt=ne/ae*1e3,Ke=Pt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:ne.toString(10)})}else if(Vp(S)){let ne=parseInt(W.getAttribute("duration")??"",10)/ae*1e3,Xe=Math.ceil(S/ne),de=0;for(let Be=1;Be<Xe;Be++){let It=Pt(Z,{...be,segmentNumber:Be.toString(10),segmentTime:de.toString(10)});ce.push({time:{from:de,to:de+ne},url:It}),de+=ne}nt=de,Ke=Pt(Z,{...be,segmentNumber:Xe.toString(10),segmentTime:de.toString(10)})}let Xa={time:{from:nt,to:1/0},url:Ke};Ge={type:"template",baseUrl:J,segmentTemplateUrl:Z,initUrl:Le,totalSegmentsDurationMs:ye,segments:ce,nextSegmentBeyondManifest:Xa,timescale:ae}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oe||!fe)continue;let at={video:"video",audio:"audio",text:"text"}[oe];if(!at)continue;se||=at,Pe={id:vt,kind:at,segmentReference:Ge,profiles:yt,duration:S,bitrate:bt,mime:fe,codecs:ze,width:ge,height:rt,fps:Yt,quality:We}}X.language||=D,X.label||=Se,X.mime||=fe,X.codecs||=ze,X.hdr||=se==="video"&&xi(ze),X.representations.push(Pe)}if(se){let P=r[se].find(D=>D.id===X.id);if(P&&X.representations.every(D=>De(D.segmentReference)))for(let D of P.representations){let me=X.representations.find(fe=>fe.id===D.id)?.segmentReference,J=D.segmentReference;J.segments.push(...me.segments),J.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else r[se].push(X)}}return{duration:S,streams:r,baseUrls:a,live:b}};import{isNonNullable as ol}from"@vkontakte/videoplayer-shared/evergreen";var C=(n,e)=>ol(n)&&ol(e)&&n.readyState==="open"&&Cp(n,e);function Cp(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}var wr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ii(0);this.currentLowLatencySegmentLength$=new ii(0);this.currentSegmentLength$=new ii(0);this.onLastSegment$=new ii(!1);this.fullyBuffered$=new ii(!1);this.playingRepresentation$=new ii(void 0);this.playingRepresentationInit$=new ii(void 0);this.error$=new Fp;this.gaps=[];this.subscription=new _p;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ut(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Qu(this.sourceBuffer),this.subscription.add($n(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),o??={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(o)})),this.subscription.add($n(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!C(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,a*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(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(s))}.bind(this));this.switchTo=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(we(s)||we(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),He(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();Ei(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ut(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(we(s)||we(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),He(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();Ei(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ut(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 l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!De(p.segmentReference))return;let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);He(r);let s=this.segments.get(i);He(s,"No segments for starting representation");let a=this.initData.get(i);if(He(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Ut(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);He(s,`No such representation ${i}`);let a=this.segments.get(i),o=this.initData.get(i);if(we(o)||we(a)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),a=this.segments.get(i),He(a,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ei(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!we(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(we(e)||we(this.downloadingRepresentationId)||we(this.playingRepresentationId)||we(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||Ei(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(p=>e>=p.time.from&&e<p.time.to);Ei(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=this.getForwardBufferDuration(e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&Ti(this.sourceBuffer.buffered)>=this.bufferLimit){let p=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))p="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(u,t,p).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<a),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Ei(t.duration)&&t.duration-i>0&&!this.isLive&&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=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-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)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!De(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],o=a.at(-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!De(r))return;let s=this.segments.get(i.id)??[],a=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Pt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.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)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.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=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,S=h>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+x||r<x&&m-h>=x||m<=i+x;return(d==="none"||d==="partially_ejected"&&S&&v&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(ke(this.sourceBuffer.buffered,h)&&ke(this.sourceBuffer.buffered,m)))&&S&&v});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<a.length&&(o<=p||u<=c);d++){let h=a[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){De(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ut(o,async function*(){let p=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(a,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=na(),!p)return;let c=new DataView(p),d=Er(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),kr(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())De(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}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:s,signal:a,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Ut(a,async function*(){let u=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),$n(window,"online").pipe(Op()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:a,priority:i}),this.lastDataObtainedTimestampMs=na(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),kr(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(De(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:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=na(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!De(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:s}=this.downloadAbortController,a=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=na();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:a}}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:s}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=Er(a.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await a();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(!h)continue;let f=Er(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?b:f.parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(we(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&O.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ke(this.sourceBuffer.buffered,e.segment.time.from,100)&&ke(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ln(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===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",a=(!i&&this.failedDownloads>0?Ut(this.destroyAbortController.signal,async function*(){let o=Rn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Er(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&De(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:Mt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,a),a}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){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||we(e))return!1;let r=[],s=0,a=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(s>=t)return r;r.push({...u.time}),r=a(r);let l=Ln(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||we(e)?0:Ie(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let a=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),a<i.time.to&&a>i.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(we(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||we(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=a&&p.to+t>=o),l=e.filter(p=>a>=p.from&&a<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ht=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var oa=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 Ar,assertNever as ul,fromEvent as ll,merge as Np,now as Pr,Subscription as Up,Subject as cl,ValueSubject as Dn,flattenObject as ki,ErrorCategory as Mr}from"@vkontakte/videoplayer-shared/evergreen";var ua=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ca=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Dn(void 0);this.lastConnectionReused$=new Dn(void 0);this.lastRequestFirstBytes$=new Dn(void 0);this.recoverableError$=new cl;this.error$=new cl;this.abortAllController=new AbortController;this.subscription=new Up;this.fetchManifest=Ar(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ht(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ua(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(la);return r?(t.log("success",ki({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ki({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ar(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),l=R.toString();break}default:ul(t)}this.requestQuic&&(l=Ht(l));let d=this.abortAllController.signal,h;if(a){let R=new AbortController;if(h=Np(ll(this.abortAllController.signal,"abort"),ll(a,"abort")).subscribe(()=>{try{R.abort()}catch(y){la(y)}}),this.subscription.add(h),this.abortAllController.signal.aborted||a.aborted)try{R.abort()}catch(y){la(y)}d=R.signal}let m=Pr();c.log("startRequest",ki({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:p,signal:d}),b=Pr();if(!f)return c.error("error",{message:"No response in request"}),c.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){h?.unsubscribe();let R=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:R}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){h?.unsubscribe();let R=Pr(),y={requestStartedAt:m,requestEndedAt:R,duration:R-m};return c.log("endRequest",ki(y)),c.end(),f.arrayBuffer()}let[S,x]=f.body.tee(),v=S.getReader();o&&this.throughputEstimator?.trackStream(x,u);let I=0,E=new Uint8Array(0),L=!1,V=R=>{h?.unsubscribe(),L=!0,la(R)},k=Ar(d,async function*({done:R,value:y}){if(I===0&&this.lastRequestFirstBytes$.next(Pr()-m),d.aborted){h?.unsubscribe();return}if(!R&&y){let T=new Uint8Array(E.length+y.length);T.set(E),T.set(y,E.length),E=T,I+=y.byteLength,r?.(new DataView(E.buffer),I),yield v?.read().then(k,V)}}.bind(this));yield v?.read().then(k,V),h?.unsubscribe();let w=Pr(),g={failed:L,requestStartedAt:m,requestEndedAt:w,duration:w-m};return L?(c.error("endRequest",ki(g)),c.end(),null):(c.log("endRequest",ki(g)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ar(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,o=s,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),o=Math.max(p,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-a,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=Ar(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(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oa(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:ul(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Mr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Mr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Mr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Mr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Mr.FATAL})}}},la=n=>{if(!kr(n))throw n};var Lt=(n,e,t)=>t*e+(1-t)*n,Vn=(n,e)=>n.reduce((t,i)=>t+i,0)/e,dl=(n,e,t,i)=>{let r=0,s=t,a=Vn(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[s]>a?r++:r--,s=(n.length+s-1)%n.length;return Math.abs(r)===o};import{isNullable as Hp,ValueSubject as pl}from"@vkontakte/videoplayer-shared/evergreen";var jt=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 pl(e.initial),this.debounced$=new pl(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Re(`raw_${t}`),this.smoothedSeries$=new Re(`smoothed_${t}`),this.reportedSeries$=new Re(`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),s=this.smoothed+this.params.deviationFactor*r,a=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>s||this.smoothed<a)&&(Hp(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 da=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Lt(this.slow,e,this.params.emaAlphaSlow),this.fast=Lt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var pa=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Vn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Lt(this.emaSmoothed,e,this.params.emaAlpha);let i=dl(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ha=class extends jt{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?Lt(this.smoothed,t,this.params.emaAlpha):t}};var Bt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new da({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new pa({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new ha({initial:e,label:"liveEdgeDelay",...t})}};var wi=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as jp,ValueSubject as zp}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class n{constructor(e,t){this.currentRepresentation$=new zp(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!jp(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,o=r.segments[s-1].time.to;if(e<a||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&De(t.segmentReference))}};import{assertNever as fa}from"@vkontakte/videoplayer-shared/evergreen";var hl=(n,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:a}=O.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return n.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return a;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return fa(l)}})},ma=n=>{let{webmDecodingInfo:e}=O.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(n){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:fa(n)}return[t,i]},ml=({webmCodec:n,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...ma(n),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(O.device.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",...ma(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ma(n),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ma(n),...r,"HLS","HLS_ONDEMAND"];default:fa(e)}return O.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},fl=({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"],s=[...i,...r],a=[...r,...i],o,u=O.device.isMac&&O.browser.isSafari;if(O.device.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=a;break}default:fa(n)}else O.video.nativeHlsSupported&&!u?o=a:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Cn=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ba=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)};var Jp=["timeupdate","progress","play","seeked","stalled","waiting"],Zp=["timeupdate","progress","loadeddata","playing","seeked"];var va=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Sl;this.representationSubscription=new Sl;this.state$=new _("none");this.currentVideoRepresentation$=new ue(void 0);this.currentVideoRepresentationInit$=new ue(void 0);this.currentAudioRepresentation$=new ue(void 0);this.currentVideoSegmentLength$=new ue(0);this.currentAudioSegmentLength$=new ue(0);this.error$=new Sa;this.lastConnectionType$=new ue(void 0);this.lastConnectionReused$=new ue(void 0);this.lastRequestFirstBytes$=new ue(void 0);this.currentLiveTextRepresentation$=new ue(null);this.isLive$=new ue(!1);this.isActiveLive$=new ue(!1);this.isLowLatency$=new ue(!1);this.liveDuration$=new ue(0);this.liveSeekableDuration$=new ue(0);this.liveAvailabilityStartTime$=new ue(0);this.liveStreamStatus$=new ue(void 0);this.bufferLength$=new ue(0);this.liveLatency$=new ue(void 0);this.liveLoadBufferLength$=new ue(0);this.livePositionFromPlayer$=new ue(0);this.currentStallDuration$=new ue(0);this.videoLastDataObtainedTimestamp$=new ue(0);this.fetcherRecoverableError$=new Sa;this.fetcherError$=new Sa;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Sa;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Fn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(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:ut.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Fn(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ut.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=nl(e??"",this.manifestUrlString)}catch(a){let o=sa(e)??{id:"ManifestParsing",category:ut.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(o)}if(!t)return null;let i=(a,o,u)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((o-a)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let u=t.streams[a].filter(({mime:c,codecs:d})=>i(a,c,d)),l=new Set(u.map(({codecs:c})=>c)),p=ba(l);if(p&&(r[a]=u.filter(({codecs:c})=>c.startsWith(p))),a==="video"){let c=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);O.display.isHDR&&c&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",$r(s)),s}.bind(this));this.initRepresentations=Fn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",$r({initialVideo:e,initialAudio:t,sourceHls:i})),Ai(this.manifest),Ai(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add($t(d,"error").pipe(ga(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Cs():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&mi())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new wr("video",this.source,o,a),this.bufferManagers=[this.videoBufferManager],Rr(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new wr("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}Lr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Lr(this.manifest.streams.text,a)),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$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ri(...Zp.map(d=>$t(this.element,d))).pipe(Mi(d=>this.element?Ie(this.element.buffered,this.element.currentTime*1e3):0),Br(),Kp(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ri($t(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Br()).subscribe(h=>this.liveStreamEndTimestamp=Nn())),this.subscription.add($t(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=_n(1e3).subscribe(h=>{let m=Ct(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add($t(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Pi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mi(({isActiveLive:h,isLowLatency:m})=>h&&m),Br()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||wi(this.element,1)})),this.representationSubscription.add(Pi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ga(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Pi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ga(({isLive:h})=>h),Br((h,m)=>m.bufferLength<h.bufferLength),Mi(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=Ct(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Pi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(v)>S&&(I=1+Math.sign(v)*x),wi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add(Pi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Xp(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=Ct(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(V);let k="none";if(L?k="active_low_latency":this.isLowLatency$.getValue()&&V?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&E<x?k="live_forward_buffering":E<x+I&&(k="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),k==="live_forward_buffering"||k==="live_with_target_offset"){let w=d-(x+v),g=this.normolizeLiveOffset(Math.trunc(b+w/f)),R=Math.abs(g-b),y=0;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?y=b:g>0&&R>this.tuning.dashCmafLive.offsetCalculationError&&(y=g),this.manifestUrlString=pe(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ut.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ri(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Mi(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=ri(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Mi(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=Pi({allBuffersFull:l,someBufferEnded:p}).pipe(Br(),Mi(({allBuffersFull:d,someBufferEnded:h})=>d&&h),ga(d=>d));if(this.representationSubscription.add(ri(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ri(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ut.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),De(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Rr(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=_n(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ut.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ca({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Bt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Ai(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Nn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=pe(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Ai(this.element),this.state$.setState("running"),this.subscription.add(ri(...Jp.map(e=>$t(this.element,e)),$t(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ut.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add($t(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add($t(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ke(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=Nn(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,p=u<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:ut.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",$r(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=_n(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:ut.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Ai(this.element),Ai(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),this.warmUpMediaSourceIfNeeded(i),ke(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(gl(this.element)||gl(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",$r({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Rr(this.element)&&Rr(this.source)&&Rr(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Yp(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-a<=r&&u.to+a>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",$r(i)))}}};var ya=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ta=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,s=t-this.camera.orientation.y,a=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:s,z:a},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 yl=`attribute vec2 a_vertex;
124
124
  attribute vec2 a_texel;
125
125
 
126
126
  varying vec2 v_texel;
@@ -174,13 +174,13 @@ void main(void) {
174
174
  // sample using new coordinates
175
175
  gl_FragColor = texture2D(u_texture, tc);
176
176
  }
177
- `;var Li=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 ya(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ta(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"),s=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(s,-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(yl,this.gl.VERTEX_SHADER),i=this.createShader(Tl,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,s=e-i,a=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[s,a,o,u,l,p,c,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as ih,now as Dr,once as rh,Subscription as sh,ValueSubject as Un,isNonNullable as ah,safeStorage as Hn,filterChanged as nh}from"@vkontakte/videoplayer-shared/evergreen";var Ia="stalls_manager_metrics",jn="stalls_manager_abr_params",Il="stalls_manager_default_tuning_abr_params",zn=class{constructor(){this.isSeeked$=new Un(!1);this.isBuffering$=new Un(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new sh;this.severeStallOccurred$=new Un(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(jn):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Dr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Dr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Il)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(jn),this.setStoredData(Il,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ia,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((o,u)=>o+u.tvt,0),a=t.reduce((o,u)=>o+u.stallsDuration,0)/r;e.push(this.calculateOptimalAbrParams(a))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((s,a)=>s+a.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed));let i={bitrateFactorAtEmptyBuffer:Math.max(...e.map(r=>r.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(r=>r.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(r=>r.containerSizeFactor))};this.setStoredData(Ia,[]),this.setStoredData(jn,i)}calculateOptimalAbrParams(e){let{targetStallsDurationPerTvt:t,deviationStallsDurationPerTvt:i,criticalStallsDurationPerTvt:r,abrAdjustingSpeed:s}=this.tuning,a=this.abrTuningParams;return e<t-i?a={bitrateFactorAtEmptyBuffer:Math.max(a.bitrateFactorAtEmptyBuffer-s,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(a.bitrateFactorAtFullBuffer-s,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(a.containerSizeFactor+s,this.abrParams.maxContainerSizeFactor)}:e>t+i&&(a={bitrateFactorAtEmptyBuffer:Math.min(a.bitrateFactorAtEmptyBuffer+s,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(a.bitrateFactorAtFullBuffer+s,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(a.containerSizeFactor-s,this.abrParams.minContainerSizeFactor)}),e>r&&(a={bitrateFactorAtEmptyBuffer:Math.max(a.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(a.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(a.containerSizeFactor,this.abrParams.containerSizeFactor)}),a}getStoredData(e,t="{}"){return JSON.parse(Hn.get(e)??t)}setStoredData(e,t){Hn.set(e,JSON.stringify(t))}removeStoredData(e){Hn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ia,"[]"),r=t/e,s=i.length?Lt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ia,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(rh()).subscribe(t=>this.providerStartWatchingTimestamp=Dr())),this.subscription.add(this.currentStallDuration$.pipe(nh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(ih(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=Dr(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,ah(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Dr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},xa=zn;import{combine as oh,map as uh,observeElementSize as lh,Subscription as ch,ValueSubject as Qn,noop as dh}from"@vkontakte/videoplayer-shared/evergreen";var Ea=class{constructor(){this.subscription=new ch;this.pipSize$=new Qn(void 0);this.videoSize$=new Qn(void 0);this.elementSize$=new Qn(void 0);this.pictureInPictureWindowRemoveEventListener=dh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(lh(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(oh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(uh(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var si=class{constructor(e){this.subscription=new gh;this.videoState=new _("stopped");this.droppedFramesManager=new yi;this.stallsManager=new xa;this.elementSizeManager=new Ea;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _t;this.audioTrackSwitchHistory=new _t;this.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"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),M(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"),M(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&M(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return hh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Li(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ee(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new va({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Ne(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:xl.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Wn(l=>!!l.length),kl()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(qn(l=>l.to.state!=="none"),ka());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Wn(El),kl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(qn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(dt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(it(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if(mh(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of p.audio){d.push(Pn(h));let m=[];for(let f of h.representations){let b=tl(f);m.push(b),this.audioTracksMap.set(b,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(d)}let c=[];for(let d of p.video){c.push(Mn(d));let h=[];for(let m of d.representations){let f=el({...m,streamId:d.id});f&&(h.push(f),this.videoTracksMap.set(f,{stream:d,representation:m}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(c);for(let d of p.text)for(let h of d.representations){let m=il(d,h);this.textTracksMap.set(m,{stream:d,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(wa(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bh(this.video,"progress")).pipe(Wn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[d,h]=c,m=[...this.videoTracksMap.keys()].find(b=>this.videoTracksMap.get(b)?.representation.id===d.id);El(m)&&(this.stallsManager.lastVideoTrackSelected=m);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(d.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),h){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,b)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ka()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:d}]=p,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Mn(d))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ka()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[c,{stream:d}]=p,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Pn(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}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(qn(({to:l})=>l==="ready"),ka());this.subscription.add(wa(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Gn(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(wa(o,this.player.state$.stateChangeEnded$,Gn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=wa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Gn(["init"])).pipe(fh(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Wi:Qi,t=this.params.tuning.useNewAutoSelectVideoTrack?Zs:Js,i=this.params.tuning.useNewAutoSelectVideoTrack?mt:Xs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:g})=>g===o),p=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=[...this.videoStreamsMap.keys()].find(({id:g})=>g===c.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let m=Ie(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(m/Math.min(f,b||1/0),1),E=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:g})=>g===E?.id)??this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!a){let g=e(l,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,g?.bitrate??-1/0)}if(p){let g=e(p,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,g?.bitrate??-1/0)}}let x=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:p,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),L=a?x??l:l??x,C=v&&t(L,h,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=this.videoTracksMap.get(L)?.representation,w=C&&this.audioTracksMap.get(C)?.representation;if(k&&w)return[k,w];if(k&&!w&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Fe(this.video),this.tracer.end()}};var Cr=class extends si{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 Yn,merge as wl,filter as Al,filterChanged as Sh,isNullable as Kn,map as Pl,ValueSubject as Xn,isNonNullable as vh}from"@vkontakte/videoplayer-shared/evergreen";var Vr=class extends si{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let a=new Xn(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Pl(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Yn({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Pl(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Al(o=>vh(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Yn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:wl(i.playbackRateState$,new Xn(1))}).pipe(Al(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||u<1-c||this.video.paused||Kn(l)||(e=o-l)})).add(Yn({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:wl(i.playbackRateState$,new Xn(1))}).pipe(Sh((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||Kn(o)||Kn(u))return;let d=-1*(u-o-e);t.position$.next(Math.min(d,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=rl(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as dm,assertNonNullable as pm,debounce as hm,ErrorCategory as ic,filter as bo,filterChanged as Va,fromEvent as mm,isNonNullable as rc,map as go,merge as Oa,observableFrom as So,once as sc,Subscription as fm}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as co,assertNonNullable as Di,combine as Ci,ErrorCategory as ct,filter as $a,filterChanged as ms,flattenObject as fs,fromEvent as ft,getTraceSubscriptionMethod as tm,interval as po,isNonNullable as bs,isNullable as ec,map as Vi,merge as ci,now as ho,Subject as Ra,Subscription as mo,tap as im,throttle as tc,ValueSubject as le}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as yh,ErrorCategory as Ml,Subject as Ll}from"@vkontakte/videoplayer-shared/evergreen";var Th=18,Bl=!1;try{Bl=O.browser.isSafari&&!!O.browser.safariVersion&&O.browser.safariVersion<=Th}catch(n){console.error(n)}var Jn=class{constructor(e){this.bufferFull$=new Ll;this.error$=new Ll;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!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:Ml.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 s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Bl&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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)&&!this.abortRequested)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:Ml.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:yh(t)}}},$l=Jn;import{abortable as Qt,assertNonNullable as je,ErrorCategory as ui,fromEvent as no,getExponentialDelay as oo,isNonNullable as $i,isNullable as Ae,now as Ma,once as Wh,Subject as qh,Subscription as Gh,ValueSubject as li}from"@vkontakte/videoplayer-shared/evergreen";var z=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}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 Bi=class extends z{};var Or=class extends z{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,a=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(a);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Fr=class extends z{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 _r=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends z{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Nr=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ur=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hr=class extends z{constructor(e,t){super(e,t),this.data=this.content}};var ai=class extends ie{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(),s=r>>>31,a=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var jr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qr=class extends ie{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 Wr=class extends ie{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var qr=class extends ie{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Gr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yr=class extends ie{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 Kr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Jr=class extends ie{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var es=class extends ie{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 ts=class extends ie{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 is=class extends ie{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 rs=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends ie{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var as=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var xh={ftyp:Fr,moov:_r,mvhd:Nr,moof:Ur,mdat:Hr,sidx:ai,trak:jr,mdia:Gr,mfhd:Jr,tkhd:Yr,traf:Zr,tfhd:es,tfdt:ts,trun:is,minf:Kr,sv3d:zr,st3d:Qr,prhd:Wr,proj:Xr,equi:qr,uuid:Or,stbl:rs,stsd:ss,avc1:as,unknown:Bi},Rt=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!a.size)break;t.push(a),i+=a.size}catch{break}return t}createBox(e,t){let i=xh[e];return i?new i(t,new n):new Bi(t,new n)}};var zt=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 kh=new TextDecoder("ascii"),wh=n=>kh.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Ah=n=>{let e=new ai(n,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,o})},Ph=(n,e)=>{let i=new Rt().parse(n),r=new zt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let o=s[0],u=a[a.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,c)},Mh=n=>{let t=new Rt().parse(n),i=new zt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},Lh=n=>{let t=new Rt().parse(n);return new zt(t).find("sidx")?.timescale},Bh=(n,e)=>{let i=new Rt().parse(n),s=new zt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=a.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},$h=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 Rt().parse(n),r=new zt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.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},Rl={validateData:wh,parseInit:$h,getIndexRange:()=>{},parseSegments:Ah,parseFeedableSegmentChunk:Ph,getChunkEndTime:Bh,getServerLatencyTimestamps:Mh,getTimescaleFromIndex:Lh};import{assertNonNullable as eo,isNonNullable as Ol,isNullable as Dh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Rh}from"@vkontakte/videoplayer-shared/evergreen";var Dl={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"}},Cl=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=ns(n,t),r=i in Dl,s=r?Dl[i].type:"binary",a=n.getUint8(t),o=0;a&128?o=1:a&64?o=2:a&32?o=3:a&16?o=4:a&8?o=5:a&4?o=6:a&2?o=7:a&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),l=a&255>>o,p=ns(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+d):h=new DataView(n.buffer,n.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},ns=(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},lt=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ns(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:Rh(e)}},ni=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Cl(i);if(!e(r))return;r.type==="master"&&ni(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Vl=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Cl(n);return ni(r.value,({tag:s,type:a,value:o})=>(s===17143?e=lt(o,a):s===17026?t=lt(o,a):s===17029&&(i=lt(o,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Fl=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ch=[231,22612,22743,167,171,163,160,175],Vh=n=>{let e,t,i,r,s=!1,a=!1,o=!1,u,l,p=!1,c=0;return ni(n,({tag:d,type:h,value:m,valueSize:f})=>{if(d===21419){let b=lt(m,h);l=ns(b)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+f):d===357149030?s=!0:d===290298740?a=!0:d===2807729?i=lt(m,h):d===17545?r=lt(m,h):d===21420&&l===475249515?u=lt(m,h):d===374648427?ni(m,({tag:b,type:S,value:E})=>b===30321?(p=lt(E,S)===1,!1):!0):s&&a&&Fl.includes(d)&&(o=!0),!o}),eo(e,"Failed to parse webm Segment start"),eo(t,"Failed to parse webm Segment end"),eo(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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Oh=n=>{if(Dh(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Fh=(n,e)=>{let t=!1,i=!1,r=o=>Ol(o.time)&&Ol(o.position),s=[],a;return ni(n,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=lt(l,u));break;case 183:break;case 241:a&&(a.position=lt(l,u));break;default:t&&Fl.includes(o)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((o,u)=>{let{time:l,position:p}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},_h=n=>{let e=0,t=!1;try{ni(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ch.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},_l={validateData:Vl,parseInit:Vh,getIndexRange:Oh,parseSegments:Fh,parseFeedableSegmentChunk:_h};var os=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return _l;case"mp4":return Rl}}throw new ReferenceError(`Unsupported mime type ${n}`)};import{isNonNullable as jh,isNullable as ql}from"@vkontakte/videoplayer-shared/evergreen";var Nl=n=>{try{let e=Nh(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(o=>{let u=a[o];(typeof u>"u"||u==="")&&delete a[o]}),a}return null}catch{return null}};function Nh(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
177
+ `;var Li=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 ya(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ta(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"),s=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(s,-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(yl,this.gl.VERTEX_SHADER),i=this.createShader(Tl,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,s=e-i,a=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[s,a,o,u,l,p,c,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as ih,now as Dr,once as rh,Subscription as sh,ValueSubject as Un,isNonNullable as ah,safeStorage as Hn,filterChanged as nh}from"@vkontakte/videoplayer-shared/evergreen";var Ia="stalls_manager_metrics",jn="stalls_manager_abr_params",Il="stalls_manager_default_tuning_abr_params",zn=class{constructor(){this.isSeeked$=new Un(!1);this.isBuffering$=new Un(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new sh;this.severeStallOccurred$=new Un(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(jn):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Dr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Dr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Il)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(jn),this.setStoredData(Il,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ia,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,o)=>a+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ia,[]),this.setStoredData(jn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=a*Math.min(t/(o*u),1),p=this.abrTuningParams;return e<i-r?p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(p={bitrateFactorAtEmptyBuffer:Math.min(p.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(p.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(p.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor,this.abrParams.containerSizeFactor)}),p}getStoredData(e,t="{}"){return JSON.parse(Hn.get(e)??t)}setStoredData(e,t){Hn.set(e,JSON.stringify(t))}removeStoredData(e){Hn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ia,"[]"),r=t/e,s=i.length?Lt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ia,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(rh()).subscribe(t=>this.providerStartWatchingTimestamp=Dr())),this.subscription.add(this.currentStallDuration$.pipe(nh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(ih(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=Dr(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,ah(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Dr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},xa=zn;import{combine as oh,map as uh,observeElementSize as lh,Subscription as ch,ValueSubject as Qn,noop as dh}from"@vkontakte/videoplayer-shared/evergreen";var Ea=class{constructor(){this.subscription=new ch;this.pipSize$=new Qn(void 0);this.videoSize$=new Qn(void 0);this.elementSize$=new Qn(void 0);this.pictureInPictureWindowRemoveEventListener=dh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(lh(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(oh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(uh(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var si=class{constructor(e){this.subscription=new Sh;this.videoState=new _("stopped");this.observableVideo=null;this.droppedFramesManager=new yi;this.stallsManager=new xa;this.elementSizeManager=new Ea;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _t;this.audioTrackSwitchHistory=new _t;this.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"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),M(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"),M(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&M(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return hh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Li(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ee(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new va({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;gh(this.observableVideo)&&(this.observableVideo=Ne(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:xl.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,o)=>this.subscription.add(a.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Wn(l=>!!l.length),kl()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(qn(l=>l.to.state!=="none"),ka());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Wn(El),kl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(qn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(dt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(it(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if(mh(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of p.audio){d.push(Pn(h));let m=[];for(let f of h.representations){let b=tl(f);m.push(b),this.audioTracksMap.set(b,{stream:h,representation:f})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(d)}let c=[];for(let d of p.video){c.push(Mn(d));let h=[];for(let m of d.representations){let f=el({...m,streamId:d.id});f&&(h.push(f),this.videoTracksMap.set(f,{stream:d,representation:m}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(c);for(let d of p.text)for(let h of d.representations){let m=il(d,h);this.textTracksMap.set(m,{stream:d,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(wa(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bh(this.video,"progress")).pipe(Wn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[d,h]=c,m=[...this.videoTracksMap.keys()].find(b=>this.videoTracksMap.get(b)?.representation.id===d.id);El(m)&&(this.stallsManager.lastVideoTrackSelected=m);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(d.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),h){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,b)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ka()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:d}]=p,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Mn(d))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ka()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[c,{stream:d}]=p,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Pn(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}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(qn(({to:l})=>l==="ready"),ka());this.subscription.add(wa(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Gn(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(wa(o,this.player.state$.stateChangeEnded$,Gn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=wa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Gn(["init"])).pipe(fh(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Wi:Qi,t=this.params.tuning.useNewAutoSelectVideoTrack?Zs:Js,i=this.params.tuning.useNewAutoSelectVideoTrack?mt:Xs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:g})=>g===o),p=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=[...this.videoStreamsMap.keys()].find(({id:g})=>g===c.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let m=Ie(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(m/Math.min(f,b||1/0),1),x=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:g})=>g===x?.id)??this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!a){let g=e(l,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,g?.bitrate??-1/0)}if(p){let g=e(p,h,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,g?.bitrate??-1/0)}}let E=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:p,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),L=a?E??l:l??E,V=v&&t(L,h,this.audioStreamsMap.get(v)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=this.videoTracksMap.get(L)?.representation,w=V&&this.audioTracksMap.get(V)?.representation;if(k&&w)return[k,w];if(k&&!w&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Fe(this.video),this.tracer.end()}};var Vr=class extends si{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 Yn,merge as wl,filter as Al,filterChanged as vh,isNullable as Kn,map as Pl,ValueSubject as Xn,isNonNullable as yh}from"@vkontakte/videoplayer-shared/evergreen";var Cr=class extends si{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let a=new Xn(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Pl(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Yn({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Pl(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Al(o=>yh(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Yn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:wl(i.playbackRateState$,new Xn(1))}).pipe(Al(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||u<1-c||this.video.paused||Kn(l)||(e=o-l)})).add(Yn({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:wl(i.playbackRateState$,new Xn(1))}).pipe(vh((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||Kn(o)||Kn(u))return;let d=-1*(u-o-e);t.position$.next(Math.min(d,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=rl(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as pm,assertNonNullable as hm,debounce as mm,ErrorCategory as ic,filter as bo,filterChanged as Ca,fromEvent as fm,isNonNullable as rc,isNullable as bm,map as go,merge as Oa,observableFrom as So,once as sc,Subscription as gm}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as co,assertNonNullable as Di,combine as Vi,ErrorCategory as ct,filter as $a,filterChanged as ms,flattenObject as fs,fromEvent as ft,getTraceSubscriptionMethod as im,interval as po,isNonNullable as bs,isNullable as ec,map as Ci,merge as ci,now as ho,Subject as Ra,Subscription as mo,tap as rm,throttle as tc,ValueSubject as le}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Th,ErrorCategory as Ml,Subject as Ll}from"@vkontakte/videoplayer-shared/evergreen";var Ih=18,Bl=!1;try{Bl=O.browser.isSafari&&!!O.browser.safariVersion&&O.browser.safariVersion<=Ih}catch(n){console.error(n)}var Jn=class{constructor(e){this.bufferFull$=new Ll;this.error$=new Ll;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!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:Ml.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 s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Bl&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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)&&!this.abortRequested)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:Ml.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:Th(t)}}},$l=Jn;import{abortable as Qt,assertNonNullable as je,ErrorCategory as ui,fromEvent as no,getExponentialDelay as oo,isNonNullable as $i,isNullable as Ae,now as Ma,once as qh,Subject as Gh,Subscription as Yh,ValueSubject as li}from"@vkontakte/videoplayer-shared/evergreen";var z=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}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 Bi=class extends z{};var Or=class extends z{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,a=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(a);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Fr=class extends z{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 _r=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends z{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Nr=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ur=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hr=class extends z{constructor(e,t){super(e,t),this.data=this.content}};var ai=class extends ie{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(),s=r>>>31,a=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var jr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Qr=class extends ie{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 Wr=class extends ie{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var qr=class extends ie{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Gr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yr=class extends ie{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 Kr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Jr=class extends ie{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zr=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var es=class extends ie{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 ts=class extends ie{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 is=class extends ie{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 rs=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends ie{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var as=class extends z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Eh={ftyp:Fr,moov:_r,mvhd:Nr,moof:Ur,mdat:Hr,sidx:ai,trak:jr,mdia:Gr,mfhd:Jr,tkhd:Yr,traf:Zr,tfhd:es,tfdt:ts,trun:is,minf:Kr,sv3d:zr,st3d:Qr,prhd:Wr,proj:Xr,equi:qr,uuid:Or,stbl:rs,stsd:ss,avc1:as,unknown:Bi},Rt=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!a.size)break;t.push(a),i+=a.size}catch{break}return t}createBox(e,t){let i=Eh[e];return i?new i(t,new n):new Bi(t,new n)}};var zt=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 wh=new TextDecoder("ascii"),Ah=n=>wh.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Ph=n=>{let e=new ai(n,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,o})},Mh=(n,e)=>{let i=new Rt().parse(n),r=new zt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let o=s[0],u=a[a.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,l,c)},Lh=n=>{let t=new Rt().parse(n),i=new zt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},Bh=n=>{let t=new Rt().parse(n);return new zt(t).find("sidx")?.timescale},$h=(n,e)=>{let i=new Rt().parse(n),s=new zt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=a.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Rh=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 Rt().parse(n),r=new zt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.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},Rl={validateData:Ah,parseInit:Rh,getIndexRange:()=>{},parseSegments:Ph,parseFeedableSegmentChunk:Mh,getChunkEndTime:$h,getServerLatencyTimestamps:Lh,getTimescaleFromIndex:Bh};import{assertNonNullable as eo,isNonNullable as Ol,isNullable as Vh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Dh}from"@vkontakte/videoplayer-shared/evergreen";var Dl={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"}},Vl=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=ns(n,t),r=i in Dl,s=r?Dl[i].type:"binary",a=n.getUint8(t),o=0;a&128?o=1:a&64?o=2:a&32?o=3:a&16?o=4:a&8?o=5:a&4?o=6:a&2?o=7:a&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),l=a&255>>o,p=ns(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>n.byteLength?h=new DataView(n.buffer,n.byteOffset+d):h=new DataView(n.buffer,n.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},ns=(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},lt=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return ns(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:Dh(e)}},ni=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Vl(i);if(!e(r))return;r.type==="master"&&ni(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Cl=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Vl(n);return ni(r.value,({tag:s,type:a,value:o})=>(s===17143?e=lt(o,a):s===17026?t=lt(o,a):s===17029&&(i=lt(o,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Fl=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ch=[231,22612,22743,167,171,163,160,175],Oh=n=>{let e,t,i,r,s=!1,a=!1,o=!1,u,l,p=!1,c=0;return ni(n,({tag:d,type:h,value:m,valueSize:f})=>{if(d===21419){let b=lt(m,h);l=ns(b)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+f):d===357149030?s=!0:d===290298740?a=!0:d===2807729?i=lt(m,h):d===17545?r=lt(m,h):d===21420&&l===475249515?u=lt(m,h):d===374648427?ni(m,({tag:b,type:S,value:x})=>b===30321?(p=lt(x,S)===1,!1):!0):s&&a&&Fl.includes(d)&&(o=!0),!o}),eo(e,"Failed to parse webm Segment start"),eo(t,"Failed to parse webm Segment end"),eo(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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Fh=n=>{if(Vh(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_h=(n,e)=>{let t=!1,i=!1,r=o=>Ol(o.time)&&Ol(o.position),s=[],a;return ni(n,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=lt(l,u));break;case 183:break;case 241:a&&(a.position=lt(l,u));break;default:t&&Fl.includes(o)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((o,u)=>{let{time:l,position:p}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Nh=n=>{let e=0,t=!1;try{ni(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ch.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},_l={validateData:Cl,parseInit:Oh,getIndexRange:Fh,parseSegments:_h,parseFeedableSegmentChunk:Nh};var os=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return _l;case"mp4":return Rl}}throw new ReferenceError(`Unsupported mime type ${n}`)};import{isNonNullable as zh,isNullable as ql}from"@vkontakte/videoplayer-shared/evergreen";var Nl=n=>{try{let e=Uh(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(o=>{let u=a[o];(typeof u>"u"||u==="")&&delete a[o]}),a}return null}catch{return null}};function Uh(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
178
178
  (?<language>${`(?:[a-z]{2,3}(?:-${n})?|[a-z]{4}|[a-z]{5,8})`})
179
179
  (-(?<script>[a-z]{4}))?
180
180
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
181
181
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
182
182
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
183
183
  (?:-(?<privateuse>(?:${e})))?
184
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}import{videoSizeToQuality as Uh,throttleFn as Hh}from"@vkontakte/videoplayer-shared/evergreen";var Ul=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let o=(s?Ft(s):void 0)??Uh({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Hl=({id:n,bitrate:e})=>({id:n,bitrate:e}),jl=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),zl=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),io=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),ro=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),so=n=>"url"in n,Ce=n=>n.type==="template",us=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Ql=n=>{n.sort((t,i)=>t.from-i.from);let e=[n[0]];for(let t=1;t<n.length;t++){let{from:i,to:r}=n[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(n[t])}return e},oi=(n,e)=>{for(let t of n)if(e(t))return t;return null},Wl=n=>{let e=!1,t=Hh(()=>{e=!0},n);return()=>{try{return t(),e}finally{e=!1}}};var Gl=n=>{if(!n?.startsWith("P"))return;let e=(a,o)=>{let u=a?parseFloat(a.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,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Dt=(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,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(o,u)=>ql(s)?o:ql(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Yl=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(w=>w.textContent?.trim()??""),o=a.at(0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,E=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((w,g)=>({...w,[g.id]:g.children}),{}),x=v.reduce((w,g)=>({...w,[g.id]:g.getAttribute("duration")}),{});E?S=Gl(E):Object.values(x).filter(w=>w).length&&!u?S=Object.values(x).reduce((w,g)=>w+(Gl(g)??0),0):f&&(S=parseInt(f,10));let L=0,C=s.getAttribute("profiles")?.split(",")??[];for(let w of v.map(g=>g.id))for(let g of I[w]){let R=g.getAttribute("id")??"id"+(L++).toString(10),y=g.getAttribute("mimeType")??"",T=g.getAttribute("codecs")??"",A=g.getAttribute("contentType")??y?.split("/")[0],ee=g.getAttribute("profiles")?.split(",")??[],$=Nl(g.getAttribute("lang")??"")??{},N=g.querySelector("Label")?.textContent?.trim()??void 0,G=g.querySelectorAll("Representation"),re=g.querySelector("SegmentTemplate"),he=g.querySelector("Role")?.getAttribute("value")??void 0,se=A,X={id:R,language:$.language,isDefault:he==="main",label:N,codecs:T,hdr:se==="video"&&xi(T),mime:y,representations:[]};for(let P of G){let D=P.getAttribute("lang")??void 0,Se=N??g.getAttribute("label")??P.getAttribute("label")??void 0,me=P.querySelector("BaseURL")?.textContent?.trim()??"",J=new URL(me||o,e).toString(),fe=P.getAttribute("mimeType")??y,ze=P.getAttribute("codecs")??T??"",Pe;if(A==="text"){let oe=P.getAttribute("id")||"",Qe=$.privateuse?.includes("x-auto")||oe.includes("_auto"),ge=P.querySelector("SegmentTemplate");if(ge){let rt={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},bt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(ge.getAttribute("startNumber")??"",10)??1,We=parseInt(ge.getAttribute("timescale")??"",10),Yt=ge.querySelectorAll("SegmentTimeline S")??[],qe=ge.getAttribute("media");if(!qe)continue;let St=[],vt=0,yt="",Ge=0,st=gt,W=0;for(let ae of Yt){let Me=parseInt(ae.getAttribute("d")??"",10),Z=parseInt(ae.getAttribute("r")??"",10)||0,ve=parseInt(ae.getAttribute("t")??"",10);W=Number.isFinite(ve)?ve:W;let Le=Me/We*1e3,Ye=W/We*1e3;for(let ce=0;ce<Z+1;ce++){let ye=Dt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:(W+ce*Me).toString(10)}),Ke=(Ye??0)+ce*Le,nt=Ke+Le;st++,St.push({time:{from:Ke,to:nt},url:ye})}W+=(Z+1)*Me,vt+=(Z+1)*Le}Ge=W/We*1e3,yt=Dt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:W.toString(10)});let at={time:{from:Ge,to:1/0},url:yt},be={type:"template",baseUrl:J,segmentTemplateUrl:qe,initUrl:"",totalSegmentsDurationMs:vt,segments:St,nextSegmentBeyondManifest:at,timescale:We};Pe={id:oe,kind:"text",segmentReference:be,profiles:[],duration:S,bitrate:bt,mime:"",codecs:"",width:0,height:0,isAuto:Qe}}else Pe={id:oe,isAuto:Qe,kind:"text",url:J}}else{let oe=P.getAttribute("contentType")??fe?.split("/")[0]??A,Qe=g.getAttribute("profiles")?.split(",")??[],ge=parseInt(P.getAttribute("width")??"",10),rt=parseInt(P.getAttribute("height")??"",10),bt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,gt=P.getAttribute("frameRate")??"",We=P.getAttribute("quality")??void 0,Yt=gt?aa(gt):void 0,qe=P.getAttribute("id")??"id"+(L++).toString(10),St=oe==="video"?`${rt}p`:oe==="audio"?`${bt}Kbps`:ze,vt=`${qe}@${St}`,yt=[...C,...ee,...Qe],Ge,st=P.querySelector("SegmentBase"),W=P.querySelector("SegmentTemplate")??re;if(st){let be=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ae,Me]=be.split("-").map(ye=>parseInt(ye,10)),Z={from:ae,to:Me},ve=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[Le,Ye]=ve?ve.split("-").map(ye=>parseInt(ye,10)):[],ce=ve?{from:Le,to:Ye}:void 0;Ge={type:"byteRange",url:J,initRange:Z,indexRange:ce}}else if(W){let be={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},ae=parseInt(W.getAttribute("timescale")??"",10),Me=W.getAttribute("initialization")??"",Z=W.getAttribute("media"),ve=parseInt(W.getAttribute("startNumber")??"",10)??1,Le=Dt(Me,be);if(!Z)throw new ReferenceError("No media attribute in SegmentTemplate");let Ye=W.querySelectorAll("SegmentTimeline S")??[],ce=[],ye=0,Ke="",nt=0;if(Ye.length){let Tt=ve,ne=0;for(let Xe of Ye){let de=parseInt(Xe.getAttribute("d")??"",10),Be=parseInt(Xe.getAttribute("r")??"",10)||0,It=parseInt(Xe.getAttribute("t")??"",10);ne=Number.isFinite(It)?It:ne;let Kt=de/ae*1e3,Ja=ne/ae*1e3;for(let xt=0;xt<Be+1;xt++){let Za=Dt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:(ne+xt*de).toString(10)}),Fi=(Ja??0)+xt*Kt,en=Fi+Kt;Tt++,ce.push({time:{from:Fi,to:en},url:Za})}ne+=(Be+1)*de,ye+=(Be+1)*Kt}nt=ne/ae*1e3,Ke=Dt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:ne.toString(10)})}else if(jh(S)){let ne=parseInt(W.getAttribute("duration")??"",10)/ae*1e3,Xe=Math.ceil(S/ne),de=0;for(let Be=1;Be<Xe;Be++){let It=Dt(Z,{...be,segmentNumber:Be.toString(10),segmentTime:de.toString(10)});ce.push({time:{from:de,to:de+ne},url:It}),de+=ne}nt=de,Ke=Dt(Z,{...be,segmentNumber:Xe.toString(10),segmentTime:de.toString(10)})}let Xa={time:{from:nt,to:1/0},url:Ke};Ge={type:"template",baseUrl:J,segmentTemplateUrl:Z,initUrl:Le,totalSegmentsDurationMs:ye,segments:ce,nextSegmentBeyondManifest:Xa,timescale:ae}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oe||!fe)continue;let at={video:"video",audio:"audio",text:"text"}[oe];if(!at)continue;se||=at,Pe={id:vt,kind:at,segmentReference:Ge,profiles:yt,duration:S,bitrate:bt,mime:fe,codecs:ze,width:ge,height:rt,fps:Yt,quality:We}}X.language||=D,X.label||=Se,X.mime||=fe,X.codecs||=ze,X.hdr||=se==="video"&&xi(ze),X.representations.push(Pe)}if(se){let P=r[se].find(D=>D.id===X.id);if(P&&X.representations.every(D=>Ce(D.segmentReference)))for(let D of P.representations){let me=X.representations.find(fe=>fe.id===D.id)?.segmentReference,J=D.segmentReference;J.segments.push(...me.segments),J.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else r[se].push(X)}}return{duration:S,streams:r,baseUrls:a,live:b}};import{fromEvent as zh,Subscription as Qh}from"@vkontakte/videoplayer-shared/evergreen";var Aa=n=>{let e=[];for(let t=0;t<n.length;t++){let i=Math.floor(n.start(t)*1e3),r=Math.ceil(n.end(t)*1e3);e.push(i,r)}return e};var Pa=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Qh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(zh(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Aa(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],o=t[i+1];if(a>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var ls=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new li(0);this.currentLowLatencySegmentLength$=new li(0);this.currentSegmentLength$=new li(0);this.onLastSegment$=new li(!1);this.fullyBuffered$=new li(!1);this.playingRepresentation$=new li(void 0);this.playingRepresentationInit$=new li(void 0);this.error$=new qh;this.gaps=[];this.subscription=new Gh;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Qt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new $l(this.sourceBuffer),this.sourceBufferBufferedDiff=new Pa(this.mediaSource,this.sourceBuffer),this.subscription.add(no(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(no(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ui.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ie(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,a*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);je(i,"No init buffer for starting representation"),je(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(s))}.bind(this));this.switchTo=Qt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),je(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();$i(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Qt(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),je(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();$i(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Qt(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 l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!Ce(p.segmentReference))return;let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);je(r);let s=this.segments.get(i);je(s,"No segments for starting representation");let a=this.initData.get(i);if(je(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Qt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);je(s,`No such representation ${i}`);let a=this.segments.get(i),o=this.initData.get(i);if(Ae(o)||Ae(a)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),a=this.segments.get(i),je(a,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();$i(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ae(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ae(e)||Ae(this.downloadingRepresentationId)||Ae(this.playingRepresentationId)||Ae(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||$i(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(p=>e>=p.time.from&&e<p.time.to);$i(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ie(this.sourceBuffer.buffered,e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&Ti(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Ie(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))p="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(u,t,p).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&Ie(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Ie(this.sourceBuffer.buffered,e)<a),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;$i(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-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)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Ce(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],o=a.at(-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ce(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Dt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.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.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:d,to:h}},m)=>{let f=d<=i&&h>=i,b=d>i||f||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&d<=i+S||h<=i+S;return(c==="none"||c==="partially_ejected"&&b&&E&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(ke(this.sourceBuffer.buffered,d)&&ke(this.sourceBuffer.buffered,h)))&&b&&E});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let s=e,a=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<s.length&&(a<=l||o<=p);c++){let d=s[c];if(a+=d.byte.to+1-d.byte.from,o+=d.time.to+1-d.time.from,d.status==="none"||d.status==="partially_ejected")u.push(d);else break}return u}async loadSegments(e,t,i="auto"){Ce(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Qt(o,async function*(){let p=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(a,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Ma(),!p)return;let c=new DataView(p),d=os(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),us(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ce(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}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:s,signal:a,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Qt(a,async function*(){let u=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),no(window,"online").pipe(Wh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:a,priority:i}),this.lastDataObtainedTimestampMs=Ma(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),us(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ce(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:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ma(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ui.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ce(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:s}=this.downloadAbortController,a=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ma();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:ui.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:a}}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:s}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=os(a.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===d?f:os(o.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(Ae(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&O.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ke(this.sourceBuffer.buffered,e.segment.time.from,100)&&ke(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ui.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",so(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===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",a=(!i&&this.failedDownloads>0?Qt(this.destroyAbortController.signal,async function*(){let o=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,os(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&Ce(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:ui.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,a),a}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){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ae(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=o=>{if(s>=t)return;r.push({...o.time});let u=so(o)?o.size??0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&u.status==="fed"&&a(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let d of c)["none","partially_ejected"].includes(d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};a(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&a(l)}return r.length?(r=Ql(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ae(e)?0:Ie(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let a=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(a>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,o=i.end(s)*1e3;if(!(o<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ui.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ae(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Ae(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Aa(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=a&&d+t>=o),(a>=c&&a<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:ui.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as cs,assertNever as Kl,fromEvent as Xl,merge as Yh,now as ds,Subject as Jl,ValueSubject as uo,flattenObject as Ri,ErrorCategory as ps,SubscriptionRemovable as Kh}from"@vkontakte/videoplayer-shared/evergreen";var Ba=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new uo(void 0);this.lastConnectionReused$=new uo(void 0);this.lastRequestFirstBytes$=new uo(void 0);this.recoverableError$=new Jl;this.error$=new Jl;this.abortAllController=new AbortController;this.subscription=new Kh;this.fetchManifest=cs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ht(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ua(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(La);return r?(t.log("success",Ri({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Ri({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=cs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let y=new URL(l,location.href);y.searchParams.append("bytes",`${i.from}-${i.to}`),l=y.toString();break}default:Kl(t)}this.requestQuic&&(l=Ht(l));let d=this.abortAllController.signal,h;if(a){let y=new AbortController;if(h=Yh(Xl(this.abortAllController.signal,"abort"),Xl(a,"abort")).subscribe(()=>{try{y.abort()}catch(T){La(T)}}),this.subscription.add(h),this.abortAllController.signal.aborted||a.aborted)try{y.abort()}catch(T){La(T)}d=y.signal}let m=ds();c.log("startRequest",Ri({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:p,signal:d}),b=ds();if(!f)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){this.unsubscribeAbortSubscription(h);let y=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:y}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let y=ds(),T={requestStartedAt:m,requestEndedAt:y,duration:y-m};return c.log("endRequest",Ri(T)),c.end(),f.arrayBuffer()}let S=f.body;if(o){let y;[S,y]=f.body.tee(),this.throughputEstimator?.trackStream(y,u)}let E=S.getReader(),v,I=parseInt(f.headers.get("content-length")??"",10);Number.isFinite(I)&&(v=I),!v&&i&&(v=i.to-i.from+1);let x=0,L=v?new Uint8Array(v):new Uint8Array(0),C=!1,k=y=>{this.unsubscribeAbortSubscription(h),C=!0,La(y)},w=cs(d,async function*({done:y,value:T}){if(x===0&&this.lastRequestFirstBytes$.next(ds()-m),d.aborted){this.unsubscribeAbortSubscription(h);return}if(!y&&T){if(v)L.set(T,x),x+=T.byteLength;else{let A=new Uint8Array(L.length+T.length);A.set(L),A.set(T,L.length),L=A,x+=T.byteLength}r?.(new DataView(L.buffer),x),yield E?.read().then(w,k)}}.bind(this));yield E?.read().then(w,k),this.unsubscribeAbortSubscription(h);let g=ds(),R={failed:C,requestStartedAt:m,requestEndedAt:g,duration:g-m};return C?(c.error("endRequest",Ri(R)),c.end(),null):(c.log("endRequest",Ri(R)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=cs(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,o=s,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),o=Math.max(p,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-a,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=cs(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(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oa(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:Kl(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ps.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ps.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ps.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ps.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ps.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},La=n=>{if(!us(n))throw n};import{isNullable as Xh,ValueSubject as Jh}from"@vkontakte/videoplayer-shared/evergreen";var hs=class n{constructor(e,t){this.currentRepresentation$=new Jh(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Xh(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,o=r.segments[s-1].time.to;if(e<a||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ce(t.segmentReference))}};var rm=["progress","play","seeked","stalled","waiting"],sm=["timeupdate","progress","loadeddata","playing","seeked"];var Da=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new mo;this.representationSubscription=new mo;this.state$=new _("none");this.currentVideoRepresentation$=new le(void 0);this.currentVideoRepresentationInit$=new le(void 0);this.currentAudioRepresentation$=new le(void 0);this.currentVideoSegmentLength$=new le(0);this.currentAudioSegmentLength$=new le(0);this.error$=new Ra;this.lastConnectionType$=new le(void 0);this.lastConnectionReused$=new le(void 0);this.lastRequestFirstBytes$=new le(void 0);this.currentLiveTextRepresentation$=new le(null);this.isLive$=new le(!1);this.isActiveLive$=new le(!1);this.isLowLatency$=new le(!1);this.liveDuration$=new le(0);this.liveSeekableDuration$=new le(0);this.liveAvailabilityStartTime$=new le(0);this.liveStreamStatus$=new le(void 0);this.bufferLength$=new le(0);this.liveLatency$=new le(void 0);this.liveLoadBufferLength$=new le(0);this.livePositionFromPlayer$=new le(0);this.currentStallDuration$=new le(0);this.videoLastDataObtainedTimestamp$=new le(0);this.fetcherRecoverableError$=new Ra;this.fetcherError$=new Ra;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Ra;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(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:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=co(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=Yl(e??"",this.manifestUrlString)}catch(a){let o=sa(e)??{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(o)}if(!t)return null;let i=(a,o,u)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((o-a)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let u=t.streams[a].filter(({mime:c,codecs:d})=>i(a,c,d)),l=new Set(u.map(({codecs:c})=>c)),p=ba(l);if(p&&(r[a]=u.filter(({codecs:c})=>c.startsWith(p))),a==="video"){let c=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);O.display.isHDR&&c&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",fs(s)),s}.bind(this));this.initRepresentations=co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",fs({initialVideo:e,initialAudio:t,sourceHls:i})),Di(this.manifest),Di(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new mo,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(ft(d,"error").pipe($a(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Vs():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&mi())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new ls("video",this.source,o,a),this.bufferManagers=[this.videoBufferManager],bs(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ls("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}hs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new hs(this.manifest.streams.text,a)),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$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ci(...sm.map(d=>ft(this.element,d))).pipe(Vi(d=>this.element?Ie(this.element.buffered,this.element.currentTime*1e3):0),ms(),im(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ci(ft(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ms()).subscribe(h=>this.liveStreamEndTimestamp=ho())),this.subscription.add(ft(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=po(1e3).subscribe(h=>{let m=Vt(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ft(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ci({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Vi(({isActiveLive:h,isLowLatency:m})=>h&&m),ms()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||wi(this.element,1)})),this.representationSubscription.add(Ci({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe($a(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Ci({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe($a(({isLive:h})=>h),ms((h,m)=>m.bufferLength<h.bufferLength),Vi(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=Vt(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ci({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(v)>S&&(I=1+Math.sign(v)*E),wi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add(Ci({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(tc(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=Vt(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,x=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),C=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(C);let k="none";if(L?k="active_low_latency":this.isLowLatency$.getValue()&&C?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&x<E?k="live_forward_buffering":x<E+I&&(k="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),k==="live_forward_buffering"||k==="live_with_target_offset"){let w=d-(E+v),g=this.normolizeLiveOffset(Math.trunc(b+w/f)),R=Math.abs(g-b),y=0;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?y=b:g>0&&R>this.tuning.dashCmafLive.offsetCalculationError&&(y=g),this.manifestUrlString=pe(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ci(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Vi(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=ci(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Vi(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=Ci({allBuffersFull:l,someBufferEnded:p}).pipe(ms(),Vi(({allBuffersFull:d,someBufferEnded:h})=>d&&h),$a(d=>d));if(this.representationSubscription.add(ci(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ci(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),Ce(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&bs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=po(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ba({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Bt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Di(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ho()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=pe(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Di(this.element),this.state$.setState("running");let e=ft(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(tc(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(ci(...rm.map(t=>ft(this.element,t)),ft(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ft(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ft(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&ke(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ho(),a=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<a&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",fs(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=po(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Di(this.element),Di(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),this.warmUpMediaSourceIfNeeded(i),ke(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ec(this.element)||ec(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",fs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){bs(this.element)&&bs(this.source)&&bs(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=tm(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?a=1/0:(a===null||l.to>a)&&(a=l.to));if(a!==null){let u=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",fs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as am,map as nm,observeElementSize as om,Subscription as um,ValueSubject as fo,noop as lm}from"@vkontakte/videoplayer-shared/evergreen";var Ca=class{constructor(){this.subscription=new um;this.pipSize$=new fo(void 0);this.videoSize$=new fo(void 0);this.elementSize$=new fo(void 0);this.pictureInPictureWindowRemoveEventListener=lm}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(om(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(am({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(nm(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var di=class{constructor(e){this.subscription=new fm;this.videoState=new _("stopped");this.droppedFramesManager=new yi;this.stallsManager=new xa;this.elementSizeManager=new Ca;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _t;this.audioTrackSwitchHistory=new _t;this.selectedRepresentations={audio:null,video:null};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"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),M(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"),M(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&M(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return dm(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Li(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ee(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Da({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Ne(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:ic.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(bo(c=>!!c.length),sc()).subscribe(c=>{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:c})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(go(c=>c.to.state!=="none"),Va());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(bo(rc),sc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(go(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(dt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(it(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(pm(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of d.audio){m.push(io(f));let b=[];for(let S of f.representations){let E=Hl(S);b.push(E),this.audioTracksMap.set(E,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of d.video){h.push(ro(m));let f=[];for(let b of m.representations){let S=Ul({...b,streamId:m.id});S&&(f.push(S),this.videoTracksMap.set(S,{stream:m,representation:b}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(h);for(let m of d.text)for(let f of m.representations){let b=jl(m,f);this.textTracksMap.set(b,{stream:m,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Wl(o)||null;this.subscription.add(Oa(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,mm(this.video,"progress")).pipe(bo(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let f=oi(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);rc(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Va()).subscribe(c=>{let d=oi(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ro(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Va()).subscribe(c=>{let d=oi(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(io(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}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 l=t.playbackState.stateChangeStarted$.pipe(go(({to:c})=>c==="ready"),Va());this.subscription.add(Oa(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,So(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Oa(l,this.player.state$.stateChangeEnded$,So(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=Oa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,So(["init"])).pipe(hm(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Wi:Qi,t=this.params.tuning.useNewAutoSelectVideoTrack?Zs:Js,i=this.params.tuning.useNewAutoSelectVideoTrack?mt:Xs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=oi(this.videoTracksMap.keys(),k=>k.id===o),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=oi(this.videoStreamsMap.keys(),k=>k.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=Ie(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,f||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),E=S?.id&&oi(this.audioStreamsMap.keys(),k=>k.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(E){if(u&&!a){let k=e(u,d,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,k?.bitrate??-1/0)}if(l){let k=e(l,d,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,k?.bitrate??-1/0)}}let I=u;(a||!I)&&(I=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=E&&t(I,d,this.audioStreamsMap.get(E)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=this.videoTracksMap.get(I)?.representation,C=x&&this.audioTracksMap.get(x)?.representation;L&&C?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=C):L&&!C&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ic.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Fe(this.video),this.tracer.end()}};var gs=class extends di{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 vo,merge as ac,filter as nc,filterChanged as bm,isNullable as yo,map as oc,ValueSubject as To,isNonNullable as gm}from"@vkontakte/videoplayer-shared/evergreen";var Ss=class extends di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let a=new To(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(oc(o=>o.to)).subscribe(this.player.isLowLatency$)).add(vo({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(oc(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(nc(o=>gm(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(vo({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ac(i.playbackRateState$,new To(1))}).pipe(nc(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||u<1-c||this.video.paused||yo(l)||(e=o-l)})).add(vo({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ac(i.playbackRateState$,new To(1))}).pipe(bm((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||yo(o)||yo(u))return;let d=-1*(u-o-e);t.position$.next(Math.min(d,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=zl(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var uc="X-Playback-Duration",Io=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(uc)?parseInt(e.headers.get(uc),10):void 0};import{assertNever as Pm,combine as Mm,debounce as Lm,ErrorCategory as Na,filter as Bm,filterChanged as $m,isNonNullable as dc,isNullable as Ua,map as pc,merge as Rm,observableFrom as Dm,Subscription as Cm,ValueSubject as Eo,VideoQuality as Vm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Sm,getExponentialDelay as vm}from"@vkontakte/videoplayer-shared/evergreen";var ym=n=>{let e=null;if(n.QUALITY&&(e=Ft(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Sm({width:t,height:i})}return e??null},Tm=(n,e)=>{let t=n.split(`
185
- `),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],o=a.match(/^#EXT-X-STREAM-INF:(.+)/),u=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=Object.fromEntries(o[1].split(",").map(b=>b.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=ym(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[b,S]=l.RESOLUTION.split("x").map(E=>parseInt(E,10));b&&S&&(m={width:b,height:S})}let f=new URL(t[++s],e).toString();c&&i.push({id:p,quality:c,url:f,bandwidth:d,size:m,fps:h})}if(u){let l=Object.fromEntries(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Im=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),xo=0,lc=async(n,e=n,t,i)=>{let s=await(await fetch(n,i)).text();xo+=1;try{let{qualityManifests:a,textTracks:o}=Tm(s,e);return{qualityManifests:a,textTracks:o}}catch{if(xo<=t.manifestRetryMaxCount)return await Im(vm(xo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),lc(n,e,t)}return{qualityManifests:[],textTracks:[]}},Fa=lc;import{isNonNullable as xm,Subscription as Em,throttle as km,ValueSubject as cc,Subject as wm,ErrorCategory as Am}from"@vkontakte/videoplayer-shared/evergreen";var _a=class{constructor(e,t,i,r,s){this.subscription=new Em;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new cc(null);this.getCurrentTime$=new cc(null);this.error$=new wm;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(km(1e3)).subscribe(a=>{this.processLiveTime(a)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),a=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(a,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
186
- `),s=0;for(let a=0;a<r.length;++a){let o=r[a];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++a],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+p},url:l}),s=s+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(xm(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let a of t)if(a.time.from<=e&&a.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:a.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Am.WTF,thrown:t,message:e})}};var vs=class{constructor(e){this.subscription=new Cm;this.videoState=new _("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Eo([]);this.liveOffset=new Zt;this.manifestStartTime$=new Eo(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(),s=this.params.desiredState.videoTrack.getTransition(),a=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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?M(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),M(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"&&M(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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(M(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Pm(t)}};this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Vm.INVARIANT,url:this.params.source.url};let t=(i,r)=>Fa(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new _a(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new tt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Na.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Na.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ee(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Eo(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Na.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),s(it(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe($m(),pc(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&dc(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(Ee(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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(Mm({startTime:this.manifestStartTime$.pipe(Bm(dc)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(pc(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Rm(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Dm(["init"])).pipe(Lm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.selectManifest();if(Ua(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=pe(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),Io(a).then(o=>{if(!Ua(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Ua(u)||!isFinite(u))&&fetch(a).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,a).toString();Io(c).then(d=>{Ua(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Na.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=pe(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as Om,debounce as Fm,ErrorCategory as ko,fromEvent as wo,isNonNullable as _m,isNullable as Nm,map as hc,merge as mc,observableFrom as fc,Subscription as Um,ValueSubject as Hm,VideoQuality as jm}from"@vkontakte/videoplayer-shared/evergreen";var ys=class{constructor(e){this.subscription=new Um;this.videoState=new _("stopped");this.manifests$=new Hm([]);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(),s=this.params.desiredState.videoTrack.getTransition(),a=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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?M(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),M(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"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Om(t)}};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:jm.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(Ee(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fa(pe(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:ko.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(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ko.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(hc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&_m(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Ee(m.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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(hc(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!O.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(mc(wo(o,"addtrack"),wo(o,"removetrack"),wo(o,"change"),fc(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let a=mc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fc(["init"])).pipe(Fm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.selectManifest();if(Nm(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:s,min:a}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ko.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as zm,assertNonNullable as bc,debounce as Qm,ErrorCategory as gc,isHigherOrEqual as Wm,isLowerOrEqual as qm,isNonNullable as Gm,merge as Ym,observableFrom as Km,Subscription as Xm,map as Jm}from"@vkontakte/videoplayer-shared/evergreen";var Ts=class{constructor(e){this.subscription=new Xm;this.videoState=new _("stopped");this.trackUrls={};this.textTracksManager=new tt;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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?M(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),M(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"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return zm(e)}};this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},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:gc.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Jm(o=>o.to)),this.params.output.playbackState$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),s(it(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(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&&Gm(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let a=Ym(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Km(["init"])).pipe(Qm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;bc(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];bc(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ht(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ee(t))}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=mt(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||fi(e,a[0].quality,a.at(-1)?.quality)){i();return}let o=e.max?qm(r,e.max):!0,u=e.min?Wm(r,e.min):!0;o&&u||i(e)}};import{assertNever as vc,debounce as rf,merge as yc,observableFrom as sf,Subscription as af,map as Tc,ValueSubject as nf,ErrorCategory as Po,VideoQuality as of}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Zm}from"@vkontakte/videoplayer-shared/evergreen";var Sc=["stun:videostun.mycdn.me:80"],ef=1e3,tf=3,Ao=()=>null,Ha=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=Ao;this.externalStopCallback=Ao;this.externalErrorCallback=Ao;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:Sc}]};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:Zm.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),ef)}normalizeOptions(e={}){let t={stunServerList:Sc,maxRetryNumber:tf,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Is=class{constructor(e){this.videoState=new _("stopped");this.maxSeekBackTime$=new nf(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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),M(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"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return vc(e)}};this.subscription=new af,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Oe(e.container,e.tuning),this.liveStreamClient=new Ha(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:Po.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(yc(this.videoState.stateChangeStarted$.pipe(Tc(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Tc(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(a)}`})}));let r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(a,o)=>this.subscription.add(a.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(it(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).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(_e(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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 vc(a.to)}},i)).add(yc(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,sf(["init"])).pipe(rf(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(Ee(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:of.INVARIANT}),this.video.srcObject=e,M(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:Po.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Po.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xs=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 Es,assertNonNullable as Wt,ErrorCategory as ja,filter as Ac,isNonNullable as Pc,isNullable as mf,map as ff,merge as bf,once as gf,Subject as xe,Subscription as Mc,ValueSubject as U,flattenObject as Mo}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as uf,map as Ic,Subscription as lf,Subject as cf}from"@vkontakte/videoplayer-shared/evergreen";var xc=n=>new uf(e=>{let t=new lf,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(Ic(({from:l,to:p})=>`${l}-${p}`)),r=n.desiredPlaybackState$.stateChangeEnded$,s=n.providerChanged$.pipe(Ic(({type:l})=>l!==void 0)),a=new cf,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>a.next(l),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>a.next(u),n.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as df,Subscription as pf,combine as hf,filter as kc,once as wc}from"@vkontakte/videoplayer-shared/evergreen";function Ec(){return new(window.AudioContext||window.webkitAudioContext)}var Oi=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new pf;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(kc(s=>!!s.type),wc()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){O.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(hf({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(kc(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),wc()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Ec();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:n.errorId,category:df.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var Sf={chunkDuration:5e3,maxParallelRequests:5},ks=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new xe;this.noAvailableProvidersError$=new xe;this.volumeMultiplierError$=new xe;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new xe,fetcherError$:new xe,fetcherRecoverableError$:new xe,warning$:new xe,willSeekEvent$:new xe,soundProhibitedEvent$:new xe,seekedEvent$:new xe,loopedEvent$:new xe,endedEvent$:new xe,firstBytesEvent$:new xe,loadedMetadataEvent$:new xe,firstFrameEvent$:new xe,canplay$:new xe,isLive$:new U(void 0),isLiveEnded$:new U(null),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new xe,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new Mc;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=hl([...fl(this.params.tuning),...ml(this.params.tuning)],this.params.tuning).filter(l=>Pc(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Mo(s)),this.screenFormatsIterator=new xs(s);let a=[...Vn(!0),...Vn(!1)];this.chromecastFormatsIterator=new xs(a.filter(l=>Pc(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Oi.isSupported()&&(this.volumeMultiplierManager=new Oi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(mf(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:ja.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();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 a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Es(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,o={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Wt(u),this.params.tuning.useNewDashProvider?new gs({...o,source:u,sourceHls:l}):new Cr({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wt(u),this.params.tuning.useNewDashProvider?new Ss({...o,source:u}):new Vr({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Wt(u),new ys({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wt(u),new vs({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Ts({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Uu({...o,source:u,config:{...Sf,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Is({container:i,source:u,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 Es(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Wt(o),new _i({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:a,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 Es(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Es(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 Es(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 s=new URL(r);return s.host=t,s.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,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Mc,t=!1,i=0;return e.add(bf(this.providerOutput.error$.pipe(Ac(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),xc({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(ff(r=>({id:`ProviderHangup:${r}`,category:ja.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Ac(({to:s})=>s==="playing"),gf()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,a={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===ja.NETWORK,u=r.category===ja.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),p=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!p);a={...a,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:p},p?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Mo(a)):this.tracer.error("providerError",Mo(a))})),e}};import{fromEvent as za,once as vf,combine as yf,Subscription as Lc,ValueSubject as Lo,map as Tf,filter as If,isNonNullable as Qa,now as Ze,safeStorage as Bo}from"@vkontakte/videoplayer-shared/evergreen";var xf=5e3,Bc="one_video_throughput",$c="one_video_rtt",ws=window.navigator.connection,Rc=()=>{let n=ws?.downlink;if(Qa(n)&&n!==10)return n*1e3},Dc=()=>{let n=ws?.rtt;if(Qa(n)&&n!==3e3)return n},Cc=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},$o=class n{constructor(e){this.subscription=new Lc;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Bc)||(e.useBrowserEstimation?Rc():void 0)||xf,i=n.load($c)??(e.useBrowserEstimation?Dc():void 0)??0;if(this.throughput$=new Lo(t),this.rtt$=new Lo(i),this.rttAdjustedThroughput$=new Lo(Cc(t,i,e.rttPenaltyRequestSize)),this.throughput=Bt.getSmoothedValue(t,-1,e),this.rtt=Bt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Rc();a&&this.throughput.next(a);let o=Dc();Qa(o)&&this.rtt.next(o)};ws&&"onchange"in ws&&this.subscription.add(za(ws,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Bo.set(Bc,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Bo.set($c,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(yf({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Tf(({throughput:r,rtt:s})=>Cc(r,s,e.rttPenaltyRequestSize)),If(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ze(),r=new Lc;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(za(e,"progress").pipe(vf()).subscribe(s=>{t=s.loaded,i=Ze()}));break;case 1:case 0:r.add(za(e,"loadstart").subscribe(()=>{t=0,i=Ze()}));break}r.add(za(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,o=Ze(),u=a-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ze(),a=0,o=Ze(),u=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,Ze()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=Ze();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(a,m,1,t),a=c.byteLength,s=Ze()}else a+=c.byteLength;o=Ze()}else r+=c.byteLength,a+=c.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Ze()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Ze()-o,this.concurrentDownloads.size),a=0,o=Ze());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*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=Bo.get(e);if(Qa(t))return parseInt(t,10)??void 0}},Vc=$o;import{fillWithDefault as Ef,VideoQuality as Wa}from"@vkontakte/videoplayer-shared/evergreen";var Oc={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Wa.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Wa.Q_720P,trafficSavingLimit:Wa.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Wa.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},Fc=n=>({...Ef(n,Oc),configName:[...n.configName??[],...Oc.configName]});import{assertNonNullable as qa,combine as Ct,ErrorCategory as Ga,filter as F,filterChanged as q,fromEvent as Do,isNonNullable as Hc,isNullable as Bf,Logger as $f,map as Q,mapTo as jc,merge as qt,now as Ya,once as H,Subject as K,Subscription as zc,tap as Co,ValueSubject as B,isHigher as Rf,isInvariantQuality as Qc,flattenObject as Gt,throttle as Vo,getTraceSubscriptionMethod as Wc,TracerFactory as Df,InternalsExposure as Cf}from"@vkontakte/videoplayer-shared/evergreen";import{merge as kf,map as wf,filter as _c,isNonNullable as Af}from"@vkontakte/videoplayer-shared/evergreen";var Ro=({seekState:n,position$:e})=>kf(n.stateChangeEnded$.pipe(wf(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),_c(Af)),e.pipe(_c(()=>n.getState().state==="none")));import{assertNonNullable as Pf}from"@vkontakte/videoplayer-shared/evergreen";var Nc=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return Pf(e,`Wrong container or containerId {${n.container}}`),e};import{filter as Mf,once as Lf}from"@vkontakte/videoplayer-shared/evergreen";var Uc=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Mf(r=>r.length>0),Lf()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Ka=class{constructor(e={configName:[]},t=Df.createRootTracer(!1)){this.subscription=new zc;this.logger=new $f;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new B(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new B(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new _("stopped"),seekState:new _({state:"none"}),volume:new _({volume:1,muted:!1}),videoTrack:new _(void 0),videoStream:new _(void 0),audioStream:new _(void 0),autoVideoTrackSwitching:new _(!0),autoVideoTrackLimits:new _({}),isLooped:new _(!1),isLowLatency:new _(!1),playbackRate:new _(1),externalTextTracks:new _([]),internalTextTracks:new _([]),currentTextTrack:new _(void 0),textTrackCuesSettings:new _({}),cameraOrientation:new _({x:0,y:0})};this.info={playbackState$:new B(void 0),position$:new B(0),duration$:new B(1/0),muted$:new B(!1),volume$:new B(1),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableQualities$:new B([]),availableQualitiesFps$:new B({}),currentQuality$:new B(void 0),isAutoQualityEnabled$:new B(!0),autoQualityLimitingAvailable$:new B(!1),autoQualityLimits$:new B({}),predefinedQualityLimitType$:new B("unknown"),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),isAudioAvailable$:new B(!0),currentPlaybackRate$:new B(1),currentBuffer$:new B({start:0,end:0}),isBuffering$:new B(!0),isStalled$:new B(!1),isEnded$:new B(!1),isLooped$:new B(!1),isLive$:new B(void 0),isLiveEnded$:new B(null),canChangePlaybackSpeed$:new B(void 0),atLiveEdge$:new B(void 0),atLiveDurationEdge$:new B(void 0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),currentFormat$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),throughputEstimation$:new B(void 0),rttEstimation$:new B(void 0),videoBitrate$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),surface$:new B("none"),chromecastState$:new B("NOT_AVAILABLE"),chromecastDeviceName$:new B(void 0),intrinsicVideoSize$:new B(void 0),availableSources$:new B(void 0),is3DVideo$:new B(!1),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0)};this.events={inited$:new K,ready$:new K,started$:new K,playing$:new K,paused$:new K,stopped$:new K,willStart$:new K,willResume$:new K,willPause$:new K,willStop$:new K,willDestruct$:new K,watchCoverageRecord$:new K,watchCoverageLive$:new K,managedError$:new K,fatalError$:new K,fetcherRecoverableError$:new K,ended$:new K,looped$:new K,seeked$:new K,willSeek$:new K,autoplaySoundProhibited$:new K,firstBytes$:new K,loadedMetadata$:new K,firstFrame$:new K,canplay$:new K,log$:new K,fetcherError$:new K,severeStallOccured$:new K};this.experimental={element$:new B(void 0),tuningConfigName$:new B([]),enableDebugTelemetry$:new B(!1),dumpTelemetry:Su,getCurrentTime$:new B(null)};if(this.initLogs(),this.tuning=Fc(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ls({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Vc(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Cf("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let a=Reflect.get(i,r,s);return typeof a!="function"?a:(...o)=>{try{return a.apply(i,o)}catch(u){let l=o.map(d=>JSON.stringify(d,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),p=`Player.${String(r)}`,c=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:Ga.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",Gt(a)),this.domContainer=Nc(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ks({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?O.isInited$.pipe(F(s=>!!s),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Do(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{qa(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(F(i=>i.length>0),H()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Gt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{qa(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Gt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{Uc(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(F(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Bf(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Hc(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(qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(gn(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(F(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=Ya(),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 a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Gt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:Ga.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Gt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(a=>a.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ct({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:a,currentVideoStream:o})=>a.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Qc(u)?1:Qc(l)?-1:Rf(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let o={};for(let u of a)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(F(a=>Hc(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((a,o)=>Math.round(a)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((a,o)=>Math.round(a)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).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(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(Q(a=>a?{start:a.from,end:a.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.isLiveEnded$.pipe(Co(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Ct({hasLiveOffsetByPaused:qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(a=>a.to),q(),Q(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Ct({atLiveEdge:Ct({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ro({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:a,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return a&&Math.abs(o)<l/1e3}),q(),Co(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:a,hasPausedTimeoutCase:o})=>a&&!o)).subscribe(this.info.atLiveEdge$)).add(Ct({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:a,position:o,duration:u})=>a&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),Co(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Q(a=>a.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Q(a=>a.volume),q()).subscribe(this.info.volume$)).add(Ro({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(qt(e.providerOutput.endedEvent$.pipe(jc(!0)),e.providerOutput.seekedEvent$.pipe(jc(!1))).pipe(q()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Q(a=>({id:a?`No${a}`:"NoProviders",category:Ga.VIDEO_PIPELINE,message:a?`${a} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(H(),Q(a=>a??Ya()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),Q(()=>Ya()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),Q(()=>Ya()-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 B(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new B(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(F(({to:a})=>a==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=qt(e.providerOutput.isBuffering$,t,i).pipe(Q(()=>{let a=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return a&&!o}),q());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(qt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(qt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),p=this.chromecastInitializer.castState$.getValue(),c;p==="CONNECTED"?c="second_screen":u?l?a?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new zc;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(F(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=mt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(qt(this.desiredState.videoTrack.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Q(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;qa(this.providerContainer),qa(e),gu(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>bu(t)),this.providerContainer.current$.subscribe(({type:t})=>zi("provider",t)),e.duration$.subscribe(t=>zi("duration",t)),e.availableVideoTracks$.pipe(F(t=>!!t.length),H()).subscribe(t=>zi("tracks",t)),this.events.fatalError$.subscribe(new Re("fatalError")),this.events.managedError$.subscribe(new Re("managedError")),e.position$.subscribe(new Re("position")),e.currentVideoTrack$.pipe(Q(t=>t?.quality)).subscribe(new Re("quality")),this.info.currentBuffer$.subscribe(new Re("buffer")),e.isBuffering$.subscribe(new Re("isBuffering"))].forEach(t=>this.subscription.add(t)),zi("codecs",O.video.supportedCodecs)}initTracerSubscription(){let e=Wc(this.tracer.log.bind(this.tracer)),t=Wc(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Ct({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(F(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(F(i=>i>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(F(i=>i>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Ct({currentBuffer:this.info.currentBuffer$.pipe(F(i=>i.end>0),q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(q())}).pipe(Vo(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(Ct({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(F(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Vo(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),F(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),F(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),F(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ct({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(F(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Vo(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),F(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ga.DOM,message:String(r)})})};this.subscription.add(qt(Do(document,"visibilitychange"),Do(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gt({quality:t,availableTracks:Gt(e),track:Gt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xi()}};import{Subscription as DC,Observable as CC,Subject as VC,ValueSubject as OC,VideoQuality as FC}from"@vkontakte/videoplayer-shared/evergreen";var _C=`@vkontakte/videoplayer-core@${Oo}`;export{As as ChromecastState,tn as HttpConnectionType,CC as Observable,Ve as PlaybackState,Ka as Player,Ps as PredefinedQualityLimits,_C as SDK_VERSION,VC as Subject,DC as Subscription,rn as Surface,Oo as VERSION,OC as ValueSubject,Et as VideoFormat,FC as VideoQuality,O as clientChecker,ji as isMobile};
184
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}import{videoSizeToQuality as Hh,throttleFn as jh}from"@vkontakte/videoplayer-shared/evergreen";var Ul=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let o=(s?Ft(s):void 0)??Hh({width:e,height:t});return o&&{id:n,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Hl=({id:n,bitrate:e})=>({id:n,bitrate:e}),jl=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),zl=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),io=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),ro=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),so=n=>"url"in n,Ve=n=>n.type==="template",us=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Ql=n=>{n.sort((t,i)=>t.from-i.from);let e=[n[0]];for(let t=1;t<n.length;t++){let{from:i,to:r}=n[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(n[t])}return e},oi=(n,e)=>{for(let t of n)if(e(t))return t;return null},Wl=n=>{let e=!1,t=jh(()=>{e=!0},n);return()=>{try{return t(),e}finally{e=!1}}};var Gl=n=>{if(!n?.startsWith("P"))return;let e=(a,o)=>{let u=a?parseFloat(a.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,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Dt=(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,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(o,u)=>ql(s)?o:ql(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Yl=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(w=>w.textContent?.trim()??""),o=a.at(0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let S,x=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((w,g)=>({...w,[g.id]:g.children}),{}),E=v.reduce((w,g)=>({...w,[g.id]:g.getAttribute("duration")}),{});x?S=Gl(x):Object.values(E).filter(w=>w).length&&!u?S=Object.values(E).reduce((w,g)=>w+(Gl(g)??0),0):f&&(S=parseInt(f,10));let L=0,V=s.getAttribute("profiles")?.split(",")??[];for(let w of v.map(g=>g.id))for(let g of I[w]){let R=g.getAttribute("id")??"id"+(L++).toString(10),y=g.getAttribute("mimeType")??"",T=g.getAttribute("codecs")??"",A=g.getAttribute("contentType")??y?.split("/")[0],ee=g.getAttribute("profiles")?.split(",")??[],$=Nl(g.getAttribute("lang")??"")??{},N=g.querySelector("Label")?.textContent?.trim()??void 0,Y=g.querySelectorAll("Representation"),re=g.querySelector("SegmentTemplate"),he=g.querySelector("Role")?.getAttribute("value")??void 0,se=A,X={id:R,language:$.language,isDefault:he==="main",label:N,codecs:T,hdr:se==="video"&&xi(T),mime:y,representations:[]};for(let P of Y){let D=P.getAttribute("lang")??void 0,Se=N??g.getAttribute("label")??P.getAttribute("label")??void 0,me=P.querySelector("BaseURL")?.textContent?.trim()??"",J=new URL(me||o,e).toString(),fe=P.getAttribute("mimeType")??y,ze=P.getAttribute("codecs")??T??"",Pe;if(A==="text"){let oe=P.getAttribute("id")||"",Qe=$.privateuse?.includes("x-auto")||oe.includes("_auto"),ge=P.querySelector("SegmentTemplate");if(ge){let rt={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},bt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(ge.getAttribute("startNumber")??"",10)??1,We=parseInt(ge.getAttribute("timescale")??"",10),Yt=ge.querySelectorAll("SegmentTimeline S")??[],qe=ge.getAttribute("media");if(!qe)continue;let St=[],vt=0,yt="",Ge=0,st=gt,W=0;for(let ae of Yt){let Me=parseInt(ae.getAttribute("d")??"",10),Z=parseInt(ae.getAttribute("r")??"",10)||0,ve=parseInt(ae.getAttribute("t")??"",10);W=Number.isFinite(ve)?ve:W;let Le=Me/We*1e3,Ye=W/We*1e3;for(let ce=0;ce<Z+1;ce++){let ye=Dt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:(W+ce*Me).toString(10)}),Ke=(Ye??0)+ce*Le,nt=Ke+Le;st++,St.push({time:{from:Ke,to:nt},url:ye})}W+=(Z+1)*Me,vt+=(Z+1)*Le}Ge=W/We*1e3,yt=Dt(qe,{...rt,segmentNumber:st.toString(10),segmentTime:W.toString(10)});let at={time:{from:Ge,to:1/0},url:yt},be={type:"template",baseUrl:J,segmentTemplateUrl:qe,initUrl:"",totalSegmentsDurationMs:vt,segments:St,nextSegmentBeyondManifest:at,timescale:We};Pe={id:oe,kind:"text",segmentReference:be,profiles:[],duration:S,bitrate:bt,mime:"",codecs:"",width:0,height:0,isAuto:Qe}}else Pe={id:oe,isAuto:Qe,kind:"text",url:J}}else{let oe=P.getAttribute("contentType")??fe?.split("/")[0]??A,Qe=g.getAttribute("profiles")?.split(",")??[],ge=parseInt(P.getAttribute("width")??"",10),rt=parseInt(P.getAttribute("height")??"",10),bt=parseInt(P.getAttribute("bandwidth")??"",10)/1e3,gt=P.getAttribute("frameRate")??"",We=P.getAttribute("quality")??void 0,Yt=gt?aa(gt):void 0,qe=P.getAttribute("id")??"id"+(L++).toString(10),St=oe==="video"?`${rt}p`:oe==="audio"?`${bt}Kbps`:ze,vt=`${qe}@${St}`,yt=[...V,...ee,...Qe],Ge,st=P.querySelector("SegmentBase"),W=P.querySelector("SegmentTemplate")??re;if(st){let be=P.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ae,Me]=be.split("-").map(ye=>parseInt(ye,10)),Z={from:ae,to:Me},ve=P.querySelector("SegmentBase")?.getAttribute("indexRange"),[Le,Ye]=ve?ve.split("-").map(ye=>parseInt(ye,10)):[],ce=ve?{from:Le,to:Ye}:void 0;Ge={type:"byteRange",url:J,initRange:Z,indexRange:ce}}else if(W){let be={representationId:P.getAttribute("id")??void 0,bandwidth:P.getAttribute("bandwidth")??void 0},ae=parseInt(W.getAttribute("timescale")??"",10),Me=W.getAttribute("initialization")??"",Z=W.getAttribute("media"),ve=parseInt(W.getAttribute("startNumber")??"",10)??1,Le=Dt(Me,be);if(!Z)throw new ReferenceError("No media attribute in SegmentTemplate");let Ye=W.querySelectorAll("SegmentTimeline S")??[],ce=[],ye=0,Ke="",nt=0;if(Ye.length){let Tt=ve,ne=0;for(let Xe of Ye){let de=parseInt(Xe.getAttribute("d")??"",10),Be=parseInt(Xe.getAttribute("r")??"",10)||0,It=parseInt(Xe.getAttribute("t")??"",10);ne=Number.isFinite(It)?It:ne;let Kt=de/ae*1e3,Ja=ne/ae*1e3;for(let xt=0;xt<Be+1;xt++){let Za=Dt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:(ne+xt*de).toString(10)}),Fi=(Ja??0)+xt*Kt,en=Fi+Kt;Tt++,ce.push({time:{from:Fi,to:en},url:Za})}ne+=(Be+1)*de,ye+=(Be+1)*Kt}nt=ne/ae*1e3,Ke=Dt(Z,{...be,segmentNumber:Tt.toString(10),segmentTime:ne.toString(10)})}else if(zh(S)){let ne=parseInt(W.getAttribute("duration")??"",10)/ae*1e3,Xe=Math.ceil(S/ne),de=0;for(let Be=1;Be<Xe;Be++){let It=Dt(Z,{...be,segmentNumber:Be.toString(10),segmentTime:de.toString(10)});ce.push({time:{from:de,to:de+ne},url:It}),de+=ne}nt=de,Ke=Dt(Z,{...be,segmentNumber:Xe.toString(10),segmentTime:de.toString(10)})}let Xa={time:{from:nt,to:1/0},url:Ke};Ge={type:"template",baseUrl:J,segmentTemplateUrl:Z,initUrl:Le,totalSegmentsDurationMs:ye,segments:ce,nextSegmentBeyondManifest:Xa,timescale:ae}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!oe||!fe)continue;let at={video:"video",audio:"audio",text:"text"}[oe];if(!at)continue;se||=at,Pe={id:vt,kind:at,segmentReference:Ge,profiles:yt,duration:S,bitrate:bt,mime:fe,codecs:ze,width:ge,height:rt,fps:Yt,quality:We}}X.language||=D,X.label||=Se,X.mime||=fe,X.codecs||=ze,X.hdr||=se==="video"&&xi(ze),X.representations.push(Pe)}if(se){let P=r[se].find(D=>D.id===X.id);if(P&&X.representations.every(D=>Ve(D.segmentReference)))for(let D of P.representations){let me=X.representations.find(fe=>fe.id===D.id)?.segmentReference,J=D.segmentReference;J.segments.push(...me.segments),J.nextSegmentBeyondManifest=me.nextSegmentBeyondManifest}else r[se].push(X)}}return{duration:S,streams:r,baseUrls:a,live:b}};import{fromEvent as Qh,Subscription as Wh}from"@vkontakte/videoplayer-shared/evergreen";var Aa=n=>{let e=[];for(let t=0;t<n.length;t++){let i=Math.floor(n.start(t)*1e3),r=Math.ceil(n.end(t)*1e3);e.push(i,r)}return e};var Pa=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Wh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Qh(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!C(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Aa(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],o=t[i+1];if(a>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var ls=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new li(0);this.currentLowLatencySegmentLength$=new li(0);this.currentSegmentLength$=new li(0);this.onLastSegment$=new li(!1);this.fullyBuffered$=new li(!1);this.playingRepresentation$=new li(void 0);this.playingRepresentationInit$=new li(void 0);this.error$=new Gh;this.gaps=[];this.subscription=new Yh;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Qt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new $l(this.sourceBuffer),this.sourceBufferBufferedDiff=new Pa(this.mediaSource,this.sourceBuffer),this.subscription.add(no(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(no(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ui.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!C(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ie(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,a*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);je(i,"No init buffer for starting representation"),je(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(s))}.bind(this));this.switchTo=Qt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),je(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();$i(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Qt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),je(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();$i(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Qt(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 l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!Ve(p.segmentReference))return;let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);je(r);let s=this.segments.get(i);je(s,"No segments for starting representation");let a=this.initData.get(i);if(je(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Qt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);je(s,`No such representation ${i}`);let a=this.segments.get(i),o=this.initData.get(i);if(Ae(o)||Ae(a)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),a=this.segments.get(i),je(a,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();$i(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ae(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ae(e)||Ae(this.downloadingRepresentationId)||Ae(this.playingRepresentationId)||Ae(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||$i(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(p=>e>=p.time.from&&e<p.time.to);$i(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ie(this.sourceBuffer.buffered,e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&Ti(this.sourceBuffer.buffered)>=this.bufferLimit){let p=Ie(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,p<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let p="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))p="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(p="low")}this.loadSegments(u,t,p).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&Ie(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Ie(this.sourceBuffer.buffered,e)<a),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;$i(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-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)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Ve(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],o=a.at(-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ve(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Dt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.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.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,S=h>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+x||r<x&&m-h>=x||m<=i+x;return(d==="none"||d==="partially_ejected"&&S&&v&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(ke(this.sourceBuffer.buffered,h)&&ke(this.sourceBuffer.buffered,m)))&&S&&v});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<a.length&&(o<=p||u<=c);d++){let h=a[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){Ve(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Qt(o,async function*(){let p=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(a,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Ma(),!p)return;let c=new DataView(p),d=os(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),us(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ve(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}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:s,signal:a,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Qt(a,async function*(){let u=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),no(window,"online").pipe(qh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:a,priority:i}),this.lastDataObtainedTimestampMs=Ma(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),us(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ve(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:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ma(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ui.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ve(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:s}=this.downloadAbortController,a=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ma();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:ui.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:a}}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:s}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=os(a.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!C(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,m=c<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===d?f:os(o.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(Ae(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&O.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ke(this.sourceBuffer.buffered,e.segment.time.from,100)&&ke(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ui.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",so(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===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",a=(!i&&this.failedDownloads>0?Qt(this.destroyAbortController.signal,async function*(){let o=oo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,os(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&Ve(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:ui.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,a),a}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){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ae(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=o=>{if(s>=t)return;r.push({...o.time});let u=so(o)?o.size??0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&u.status==="fed"&&a(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let d of c)["none","partially_ejected"].includes(d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};a(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&a(l)}return r.length?(r=Ql(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ae(e)?0:Ie(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let a=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(a>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,o=i.end(s)*1e3;if(!(o<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:ui.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ae(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||Ae(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Aa(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=a&&d+t>=o),(a>=c&&a<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:ui.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as cs,assertNever as Kl,fromEvent as Xl,merge as Kh,now as ds,Subject as Jl,ValueSubject as uo,flattenObject as Ri,ErrorCategory as ps,SubscriptionRemovable as Xh}from"@vkontakte/videoplayer-shared/evergreen";var Ba=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new uo(void 0);this.lastConnectionReused$=new uo(void 0);this.lastRequestFirstBytes$=new uo(void 0);this.recoverableError$=new Jl;this.error$=new Jl;this.abortAllController=new AbortController;this.subscription=new Xh;this.fetchManifest=cs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ht(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ua(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(La);return r?(t.log("success",Ri({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Ri({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=cs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let y=new URL(l,location.href);y.searchParams.append("bytes",`${i.from}-${i.to}`),l=y.toString();break}default:Kl(t)}this.requestQuic&&(l=Ht(l));let d=this.abortAllController.signal,h;if(a){let y=new AbortController;if(h=Kh(Xl(this.abortAllController.signal,"abort"),Xl(a,"abort")).subscribe(()=>{try{y.abort()}catch(T){La(T)}}),this.subscription.add(h),this.abortAllController.signal.aborted||a.aborted)try{y.abort()}catch(T){La(T)}d=y.signal}let m=ds();c.log("startRequest",Ri({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:p,signal:d}),b=ds();if(!f)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){this.unsubscribeAbortSubscription(h);let y=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:y}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let y=ds(),T={requestStartedAt:m,requestEndedAt:y,duration:y-m};return c.log("endRequest",Ri(T)),c.end(),f.arrayBuffer()}let S=f.body;if(o){let y;[S,y]=f.body.tee(),this.throughputEstimator?.trackStream(y,u)}let x=S.getReader(),v,I=parseInt(f.headers.get("content-length")??"",10);Number.isFinite(I)&&(v=I),!v&&i&&(v=i.to-i.from+1);let E=0,L=v?new Uint8Array(v):new Uint8Array(0),V=!1,k=y=>{this.unsubscribeAbortSubscription(h),V=!0,La(y)},w=cs(d,async function*({done:y,value:T}){if(E===0&&this.lastRequestFirstBytes$.next(ds()-m),d.aborted){this.unsubscribeAbortSubscription(h);return}if(!y&&T){if(v)L.set(T,E),E+=T.byteLength;else{let A=new Uint8Array(L.length+T.length);A.set(L),A.set(T,L.length),L=A,E+=T.byteLength}r?.(new DataView(L.buffer),E),yield x?.read().then(w,k)}}.bind(this));yield x?.read().then(w,k),this.unsubscribeAbortSubscription(h);let g=ds(),R={failed:V,requestStartedAt:m,requestEndedAt:g,duration:g-m};return V?(c.error("endRequest",Ri(R)),c.end(),null):(c.log("endRequest",Ri(R)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=cs(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,o=s,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),o=Math.max(p,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-a,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let b=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=cs(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(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=oa(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:Kl(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ps.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ps.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ps.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ps.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ps.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},La=n=>{if(!us(n))throw n};import{isNullable as Jh,ValueSubject as Zh}from"@vkontakte/videoplayer-shared/evergreen";var hs=class n{constructor(e,t){this.currentRepresentation$=new Zh(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Jh(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,o=r.segments[s-1].time.to;if(e<a||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ve(t.segmentReference))}};var sm=["progress","play","seeked","stalled","waiting"],am=["timeupdate","progress","loadeddata","playing","seeked"];var Da=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new mo;this.representationSubscription=new mo;this.state$=new _("none");this.currentVideoRepresentation$=new le(void 0);this.currentVideoRepresentationInit$=new le(void 0);this.currentAudioRepresentation$=new le(void 0);this.currentVideoSegmentLength$=new le(0);this.currentAudioSegmentLength$=new le(0);this.error$=new Ra;this.lastConnectionType$=new le(void 0);this.lastConnectionReused$=new le(void 0);this.lastRequestFirstBytes$=new le(void 0);this.currentLiveTextRepresentation$=new le(null);this.isLive$=new le(!1);this.isActiveLive$=new le(!1);this.isLowLatency$=new le(!1);this.liveDuration$=new le(0);this.liveSeekableDuration$=new le(0);this.liveAvailabilityStartTime$=new le(0);this.liveStreamStatus$=new le(void 0);this.bufferLength$=new le(0);this.liveLatency$=new le(void 0);this.liveLoadBufferLength$=new le(0);this.livePositionFromPlayer$=new le(0);this.currentStallDuration$=new le(0);this.videoLastDataObtainedTimestamp$=new le(0);this.fetcherRecoverableError$=new Ra;this.fetcherError$=new Ra;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Ra;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(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:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=co(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=Yl(e??"",this.manifestUrlString)}catch(a){let o=sa(e)??{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(o)}if(!t)return null;let i=(a,o,u)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,p=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((o-a)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let c="active";l||(c=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(c)}let r={text:t.streams.text,video:[],audio:[]};for(let a of["video","audio"]){let u=t.streams[a].filter(({mime:c,codecs:d})=>i(a,c,d)),l=new Set(u.map(({codecs:c})=>c)),p=ba(l);if(p&&(r[a]=u.filter(({codecs:c})=>c.startsWith(p))),a==="video"){let c=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);O.display.isHDR&&c&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",fs(s)),s}.bind(this));this.initRepresentations=co(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",fs({initialVideo:e,initialAudio:t,sourceHls:i})),Di(this.manifest),Di(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new mo,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(ft(d,"error").pipe($a(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Cs():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&mi())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new ls("video",this.source,o,a),this.bufferManagers=[this.videoBufferManager],bs(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new ls("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}hs.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new hs(this.manifest.streams.text,a)),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$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ci(...am.map(d=>ft(this.element,d))).pipe(Ci(d=>this.element?Ie(this.element.buffered,this.element.currentTime*1e3):0),ms(),rm(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ci(ft(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ms()).subscribe(h=>this.liveStreamEndTimestamp=ho())),this.subscription.add(ft(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=po(1e3).subscribe(h=>{let m=Ct(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ft(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Vi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ci(({isActiveLive:h,isLowLatency:m})=>h&&m),ms()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||wi(this.element,1)})),this.representationSubscription.add(Vi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe($a(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Vi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe($a(({isLive:h})=>h),ms((h,m)=>m.bufferLength<h.bufferLength),Ci(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=Ct(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Vi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(v)>S&&(I=1+Math.sign(v)*x),wi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add(Vi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(tc(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=Ct(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(V);let k="none";if(L?k="active_low_latency":this.isLowLatency$.getValue()&&V?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&E<x?k="live_forward_buffering":E<x+I&&(k="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),k==="live_forward_buffering"||k==="live_with_target_offset"){let w=d-(x+v),g=this.normolizeLiveOffset(Math.trunc(b+w/f)),R=Math.abs(g-b),y=0;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?y=b:g>0&&R>this.tuning.dashCmafLive.offsetCalculationError&&(y=g),this.manifestUrlString=pe(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ci(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Ci(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=ci(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Ci(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=Vi({allBuffersFull:l,someBufferEnded:p}).pipe(ms(),Ci(({allBuffersFull:d,someBufferEnded:h})=>d&&h),$a(d=>d));if(this.representationSubscription.add(ci(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ci(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),Ve(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&bs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=po(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ba({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Bt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){Di(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ho()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=pe(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Di(this.element),this.state$.setState("running");let e=ft(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(tc(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(ci(...sm.map(t=>ft(this.element,t)),ft(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ft(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ft(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&ke(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ho(),a=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<a&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",fs(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=po(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Di(this.element),Di(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),this.warmUpMediaSourceIfNeeded(i),ke(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ec(this.element)||ec(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",fs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){bs(this.element)&&bs(this.source)&&bs(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=im(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?a=1/0:(a===null||l.to>a)&&(a=l.to));if(a!==null){let u=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",fs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as nm,map as om,observeElementSize as um,Subscription as lm,ValueSubject as fo,noop as cm}from"@vkontakte/videoplayer-shared/evergreen";var Va=class{constructor(){this.subscription=new lm;this.pipSize$=new fo(void 0);this.videoSize$=new fo(void 0);this.elementSize$=new fo(void 0);this.pictureInPictureWindowRemoveEventListener=cm}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(um(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(nm({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(om(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var di=class{constructor(e){this.subscription=new gm;this.videoState=new _("stopped");this.observableVideo=null;this.droppedFramesManager=new yi;this.stallsManager=new xa;this.elementSizeManager=new Va;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _t;this.audioTrackSwitchHistory=new _t;this.selectedRepresentations={audio:null,video:null};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"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),M(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"),M(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&M(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return pm(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Li(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ee(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Da({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;bm(this.observableVideo)&&(this.observableVideo=Ne(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:ic.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,o)=>this.subscription.add(a.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(bo(c=>!!c.length),sc()).subscribe(c=>{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:c})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(go(c=>c.to.state!=="none"),Ca());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(bo(rc),sc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(go(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(dt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(it(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(hm(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of d.audio){m.push(io(f));let b=[];for(let S of f.representations){let x=Hl(S);b.push(x),this.audioTracksMap.set(x,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of d.video){h.push(ro(m));let f=[];for(let b of m.representations){let S=Ul({...b,streamId:m.id});S&&(f.push(S),this.videoTracksMap.set(S,{stream:m,representation:b}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(h);for(let m of d.text)for(let f of m.representations){let b=jl(m,f);this.textTracksMap.set(b,{stream:m,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Wl(o)||null;this.subscription.add(Oa(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,fm(this.video,"progress")).pipe(bo(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let f=oi(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);rc(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ca()).subscribe(c=>{let d=oi(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ro(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ca()).subscribe(c=>{let d=oi(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(io(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}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 l=t.playbackState.stateChangeStarted$.pipe(go(({to:c})=>c==="ready"),Ca());this.subscription.add(Oa(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,So(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Oa(l,this.player.state$.stateChangeEnded$,So(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=Oa(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,So(["init"])).pipe(mm(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Wi:Qi,t=this.params.tuning.useNewAutoSelectVideoTrack?Zs:Js,i=this.params.tuning.useNewAutoSelectVideoTrack?mt:Xs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=oi(this.videoTracksMap.keys(),k=>k.id===o),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=oi(this.videoStreamsMap.keys(),k=>k.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=Ie(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,f||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=S?.id&&oi(this.audioStreamsMap.keys(),k=>k.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(x){if(u&&!a){let k=e(u,d,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,k?.bitrate??-1/0)}if(l){let k=e(l,d,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,k?.bitrate??-1/0)}}let I=u;(a||!I)&&(I=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=x&&t(I,d,this.audioStreamsMap.get(x)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=this.videoTracksMap.get(I)?.representation,V=E&&this.audioTracksMap.get(E)?.representation;L&&V?(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=V):L&&!V&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=L,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ic.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Fe(this.video),this.tracer.end()}};var gs=class extends di{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 vo,merge as ac,filter as nc,filterChanged as Sm,isNullable as yo,map as oc,ValueSubject as To,isNonNullable as vm}from"@vkontakte/videoplayer-shared/evergreen";var Ss=class extends di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let a=new To(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(oc(o=>o.to)).subscribe(this.player.isLowLatency$)).add(vo({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(oc(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(nc(o=>vm(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(vo({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ac(i.playbackRateState$,new To(1))}).pipe(nc(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||u<1-c||this.video.paused||yo(l)||(e=o-l)})).add(vo({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ac(i.playbackRateState$,new To(1))}).pipe(Sm((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let p=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||yo(o)||yo(u))return;let d=-1*(u-o-e);t.position$.next(Math.min(d,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=zl(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var uc="X-Playback-Duration",Io=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(uc)?parseInt(e.headers.get(uc),10):void 0};import{assertNever as Lm,combine as Bm,debounce as $m,ErrorCategory as Na,filter as Rm,filterChanged as Dm,isNonNullable as dc,isNullable as Ua,map as pc,merge as Vm,observableFrom as Cm,Subscription as Om,ValueSubject as Eo,VideoQuality as Fm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as ym,getExponentialDelay as Tm}from"@vkontakte/videoplayer-shared/evergreen";var Im=n=>{let e=null;if(n.QUALITY&&(e=Ft(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ym({width:t,height:i})}return e??null},xm=(n,e)=>{let t=n.split(`
185
+ `),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],o=a.match(/^#EXT-X-STREAM-INF:(.+)/),u=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=Object.fromEntries(o[1].split(",").map(b=>b.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=Im(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[b,S]=l.RESOLUTION.split("x").map(x=>parseInt(x,10));b&&S&&(m={width:b,height:S})}let f=new URL(t[++s],e).toString();c&&i.push({id:p,quality:c,url:f,bandwidth:d,size:m,fps:h})}if(u){let l=Object.fromEntries(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Em=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),xo=0,lc=async(n,e=n,t,i)=>{let s=await(await fetch(n,i)).text();xo+=1;try{let{qualityManifests:a,textTracks:o}=xm(s,e);return{qualityManifests:a,textTracks:o}}catch{if(xo<=t.manifestRetryMaxCount)return await Em(Tm(xo-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),lc(n,e,t)}return{qualityManifests:[],textTracks:[]}},Fa=lc;import{isNonNullable as km,Subscription as wm,throttle as Am,ValueSubject as cc,Subject as Pm,ErrorCategory as Mm}from"@vkontakte/videoplayer-shared/evergreen";var _a=class{constructor(e,t,i,r,s){this.subscription=new wm;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new cc(null);this.getCurrentTime$=new cc(null);this.error$=new Pm;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(Am(1e3)).subscribe(a=>{this.processLiveTime(a)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),a=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(a,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
186
+ `),s=0;for(let a=0;a<r.length;++a){let o=r[a];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++a],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+p},url:l}),s=s+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(km(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let a of t)if(a.time.from<=e&&a.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:a.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Mm.WTF,thrown:t,message:e})}};var vs=class{constructor(e){this.subscription=new Om;this.videoState=new _("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Eo([]);this.liveOffset=new Zt;this.manifestStartTime$=new Eo(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(),s=this.params.desiredState.videoTrack.getTransition(),a=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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?M(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),M(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"&&M(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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(M(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Lm(t)}};this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Fm.INVARIANT,url:this.params.source.url};let t=(i,r)=>Fa(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new _a(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new tt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Na.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Na.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ee(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Eo(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Na.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),s(it(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(Dm(),pc(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&dc(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(Ee(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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(Bm({startTime:this.manifestStartTime$.pipe(Rm(dc)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(pc(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Vm(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Cm(["init"])).pipe($m(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.selectManifest();if(Ua(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=pe(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),Io(a).then(o=>{if(!Ua(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Ua(u)||!isFinite(u))&&fetch(a).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,a).toString();Io(c).then(d=>{Ua(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Na.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=pe(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as _m,debounce as Nm,ErrorCategory as ko,fromEvent as wo,isNonNullable as Um,isNullable as Hm,map as hc,merge as mc,observableFrom as fc,Subscription as jm,ValueSubject as zm,VideoQuality as Qm}from"@vkontakte/videoplayer-shared/evergreen";var ys=class{constructor(e){this.subscription=new jm;this.videoState=new _("stopped");this.manifests$=new zm([]);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(),s=this.params.desiredState.videoTrack.getTransition(),a=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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?M(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),M(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"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return _m(t)}};this.textTracksManager=new tt(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Qm.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(Ee(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fa(pe(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:ko.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(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ko.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(hc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Um(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Ee(m.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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(hc(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!O.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(mc(wo(o,"addtrack"),wo(o,"removetrack"),wo(o,"change"),fc(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let a=mc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fc(["init"])).pipe(Nm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.selectManifest();if(Hm(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:s,min:a}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ko.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Wm,assertNonNullable as bc,debounce as qm,ErrorCategory as gc,isHigherOrEqual as Gm,isLowerOrEqual as Ym,isNonNullable as Km,merge as Xm,observableFrom as Jm,Subscription as Zm,map as ef}from"@vkontakte/videoplayer-shared/evergreen";var Ts=class{constructor(e){this.subscription=new Zm;this.videoState=new _("stopped");this.trackUrls={};this.textTracksManager=new tt;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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?M(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),M(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"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return Wm(e)}};this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},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:gc.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ef(o=>o.to)),this.params.output.playbackState$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,i)),s(it(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),M(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),M(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&&Km(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let a=Xm(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Jm(["init"])).pipe(qm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Fe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;bc(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];bc(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ht(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ee(t))}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=mt(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||fi(e,a[0].quality,a.at(-1)?.quality)){i();return}let o=e.max?Ym(r,e.max):!0,u=e.min?Gm(r,e.min):!0;o&&u||i(e)}};import{assertNever as vc,debounce as af,merge as yc,observableFrom as nf,Subscription as of,map as Tc,ValueSubject as uf,ErrorCategory as Po,VideoQuality as lf}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as tf}from"@vkontakte/videoplayer-shared/evergreen";var Sc=["stun:videostun.mycdn.me:80"],rf=1e3,sf=3,Ao=()=>null,Ha=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=Ao;this.externalStopCallback=Ao;this.externalErrorCallback=Ao;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:Sc}]};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:tf.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),rf)}normalizeOptions(e={}){let t={stunServerList:Sc,maxRetryNumber:sf,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Is=class{constructor(e){this.videoState=new _("stopped");this.maxSeekBackTime$=new uf(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"),M(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),M(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"&&M(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&M(this.params.desiredState.playbackState,"paused");return;default:return vc(e)}};this.subscription=new of,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Oe(e.container,e.tuning),this.liveStreamClient=new Ha(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:Po.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(yc(this.videoState.stateChangeStarted$.pipe(Tc(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Tc(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(a)}`})}));let r=Ne(this.video);this.subscription.add(()=>r.destroy());let s=(a,o)=>this.subscription.add(a.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(it(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).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(_e(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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 vc(a.to)}},i)).add(yc(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,nf(["init"])).pipe(af(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(Ee(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:lf.INVARIANT}),this.video.srcObject=e,M(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:Po.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ue(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),M(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Po.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xs=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 Es,assertNonNullable as Wt,ErrorCategory as ja,filter as Ac,isNonNullable as Pc,isNullable as bf,map as gf,merge as Sf,once as vf,Subject as xe,Subscription as Mc,ValueSubject as U,flattenObject as Mo}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as cf,map as Ic,Subscription as df,Subject as pf}from"@vkontakte/videoplayer-shared/evergreen";var xc=n=>new cf(e=>{let t=new df,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(Ic(({from:l,to:p})=>`${l}-${p}`)),r=n.desiredPlaybackState$.stateChangeEnded$,s=n.providerChanged$.pipe(Ic(({type:l})=>l!==void 0)),a=new pf,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>a.next(l),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>a.next(u),n.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as hf,Subscription as mf,combine as ff,filter as kc,once as wc}from"@vkontakte/videoplayer-shared/evergreen";function Ec(){return new(window.AudioContext||window.webkitAudioContext)}var Oi=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new mf;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(kc(s=>!!s.type),wc()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){O.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ff({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(kc(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),wc()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Ec();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:n.errorId,category:hf.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var yf={chunkDuration:5e3,maxParallelRequests:5},ks=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new xe;this.noAvailableProvidersError$=new xe;this.volumeMultiplierError$=new xe;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new xe,fetcherError$:new xe,fetcherRecoverableError$:new xe,warning$:new xe,willSeekEvent$:new xe,soundProhibitedEvent$:new xe,seekedEvent$:new xe,loopedEvent$:new xe,endedEvent$:new xe,firstBytesEvent$:new xe,loadedMetadataEvent$:new xe,firstFrameEvent$:new xe,canplay$:new xe,isLive$:new U(void 0),isLiveEnded$:new U(null),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new xe,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new Mc;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=hl([...fl(this.params.tuning),...ml(this.params.tuning)],this.params.tuning).filter(l=>Pc(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Mo(s)),this.screenFormatsIterator=new xs(s);let a=[...Cn(!0),...Cn(!1)];this.chromecastFormatsIterator=new xs(a.filter(l=>Pc(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Oi.isSupported()&&(this.volumeMultiplierManager=new Oi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(bf(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:ja.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();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 a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Es(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,o={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Wt(u),this.params.tuning.useNewDashProvider?new gs({...o,source:u,sourceHls:l}):new Vr({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wt(u),this.params.tuning.useNewDashProvider?new Ss({...o,source:u}):new Cr({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Wt(u),new ys({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wt(u),new vs({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Ts({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Uu({...o,source:u,config:{...yf,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Wt(u),new Is({container:i,source:u,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 Es(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Wt(o),new _i({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:a,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 Es(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Es(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 Es(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 s=new URL(r);return s.host=t,s.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,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Mc,t=!1,i=0;return e.add(Sf(this.providerOutput.error$.pipe(Ac(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),xc({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(gf(r=>({id:`ProviderHangup:${r}`,category:ja.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Ac(({to:s})=>s==="playing"),vf()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,a={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===ja.NETWORK,u=r.category===ja.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),p=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!p);a={...a,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:p},p?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Mo(a)):this.tracer.error("providerError",Mo(a))})),e}};import{fromEvent as za,once as Tf,combine as If,Subscription as Lc,ValueSubject as Lo,map as xf,filter as Ef,isNonNullable as Qa,now as Ze,safeStorage as Bo}from"@vkontakte/videoplayer-shared/evergreen";var kf=5e3,Bc="one_video_throughput",$c="one_video_rtt",ws=window.navigator.connection,Rc=()=>{let n=ws?.downlink;if(Qa(n)&&n!==10)return n*1e3},Dc=()=>{let n=ws?.rtt;if(Qa(n)&&n!==3e3)return n},Vc=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},$o=class n{constructor(e){this.subscription=new Lc;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(Bc)||(e.useBrowserEstimation?Rc():void 0)||kf,i=n.load($c)??(e.useBrowserEstimation?Dc():void 0)??0;if(this.throughput$=new Lo(t),this.rtt$=new Lo(i),this.rttAdjustedThroughput$=new Lo(Vc(t,i,e.rttPenaltyRequestSize)),this.throughput=Bt.getSmoothedValue(t,-1,e),this.rtt=Bt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Rc();a&&this.throughput.next(a);let o=Dc();Qa(o)&&this.rtt.next(o)};ws&&"onchange"in ws&&this.subscription.add(za(ws,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Bo.set(Bc,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Bo.set($c,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(If({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(xf(({throughput:r,rtt:s})=>Vc(r,s,e.rttPenaltyRequestSize)),Ef(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ze(),r=new Lc;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(za(e,"progress").pipe(Tf()).subscribe(s=>{t=s.loaded,i=Ze()}));break;case 1:case 0:r.add(za(e,"loadstart").subscribe(()=>{t=0,i=Ze()}));break}r.add(za(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,o=Ze(),u=a-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ze(),a=0,o=Ze(),u=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,Ze()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=Ze();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(a,m,1,t),a=c.byteLength,s=Ze()}else a+=c.byteLength;o=Ze()}else r+=c.byteLength,a+=c.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Ze()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Ze()-o,this.concurrentDownloads.size),a=0,o=Ze());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*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=Bo.get(e);if(Qa(t))return parseInt(t,10)??void 0}},Cc=$o;import{fillWithDefault as wf,VideoQuality as Wa}from"@vkontakte/videoplayer-shared/evergreen";var Oc={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Wa.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Wa.Q_720P,trafficSavingLimit:Wa.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Wa.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},Fc=n=>({...wf(n,Oc),configName:[...n.configName??[],...Oc.configName]});import{assertNonNullable as qa,combine as Vt,ErrorCategory as Ga,filter as F,filterChanged as q,fromEvent as Do,isNonNullable as Hc,isNullable as Rf,Logger as Df,map as Q,mapTo as jc,merge as qt,now as Ya,once as H,Subject as G,Subscription as zc,tap as Vo,ValueSubject as B,isHigher as Vf,isInvariantQuality as Qc,flattenObject as Gt,throttle as Co,getTraceSubscriptionMethod as Wc,TracerFactory as Cf,InternalsExposure as Of}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Af,map as Pf,filter as _c,isNonNullable as Mf}from"@vkontakte/videoplayer-shared/evergreen";var Ro=({seekState:n,position$:e})=>Af(n.stateChangeEnded$.pipe(Pf(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),_c(Mf)),e.pipe(_c(()=>n.getState().state==="none")));import{assertNonNullable as Lf}from"@vkontakte/videoplayer-shared/evergreen";var Nc=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return Lf(e,`Wrong container or containerId {${n.container}}`),e};import{filter as Bf,once as $f}from"@vkontakte/videoplayer-shared/evergreen";var Uc=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Bf(r=>r.length>0),$f()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Ka=class{constructor(e={configName:[]},t=Cf.createRootTracer(!1)){this.subscription=new zc;this.logger=new Df;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new B(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new B(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new _("stopped"),seekState:new _({state:"none"}),volume:new _({volume:1,muted:!1}),videoTrack:new _(void 0),videoStream:new _(void 0),audioStream:new _(void 0),autoVideoTrackSwitching:new _(!0),autoVideoTrackLimits:new _({}),isLooped:new _(!1),isLowLatency:new _(!1),playbackRate:new _(1),externalTextTracks:new _([]),internalTextTracks:new _([]),currentTextTrack:new _(void 0),textTrackCuesSettings:new _({}),cameraOrientation:new _({x:0,y:0})};this.info={playbackState$:new B(void 0),position$:new B(0),duration$:new B(1/0),muted$:new B(!1),volume$:new B(1),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableQualities$:new B([]),availableQualitiesFps$:new B({}),currentQuality$:new B(void 0),isAutoQualityEnabled$:new B(!0),autoQualityLimitingAvailable$:new B(!1),autoQualityLimits$:new B({}),predefinedQualityLimitType$:new B("unknown"),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),isAudioAvailable$:new B(!0),currentPlaybackRate$:new B(1),currentBuffer$:new B({start:0,end:0}),isBuffering$:new B(!0),isStalled$:new B(!1),isEnded$:new B(!1),isLooped$:new B(!1),isLive$:new B(void 0),isLiveEnded$:new B(null),canChangePlaybackSpeed$:new B(void 0),atLiveEdge$:new B(void 0),atLiveDurationEdge$:new B(void 0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),currentFormat$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),throughputEstimation$:new B(void 0),rttEstimation$:new B(void 0),videoBitrate$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),surface$:new B("none"),chromecastState$:new B("NOT_AVAILABLE"),chromecastDeviceName$:new B(void 0),intrinsicVideoSize$:new B(void 0),availableSources$:new B(void 0),is3DVideo$:new B(!1),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0)};this.events={inited$:new G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willReady$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,fetcherRecoverableError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G,fetcherError$:new G,severeStallOccured$:new G};this.experimental={element$:new B(void 0),tuningConfigName$:new B([]),enableDebugTelemetry$:new B(!1),dumpTelemetry:Su,getCurrentTime$:new B(null)};if(this.initLogs(),this.tuning=Fc(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ls({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Cc(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Of("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let a=Reflect.get(i,r,s);return typeof a!="function"?a:(...o)=>{try{return a.apply(i,o)}catch(u){let l=o.map(d=>JSON.stringify(d,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),p=`Player.${String(r)}`,c=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:Ga.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",Gt(a)),this.domContainer=Nc(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new ks({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?O.isInited$.pipe(F(s=>!!s),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Do(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{qa(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(F(i=>i.length>0),H()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Gt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{qa(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Gt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{Uc(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(F(t=>!!t),H()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(F(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(F(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(F(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Rf(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Hc(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(qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(gn(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(F(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=Ya(),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"ready":this.events.willReady$.next();break;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 a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Gt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:Ga.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Gt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(a=>a.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:a,currentVideoStream:o})=>a.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>Qc(u)?1:Qc(l)?-1:Vf(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let o={};for(let u of a)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(F(a=>Hc(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((a,o)=>Math.round(a)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((a,o)=>Math.round(a)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).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(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(Q(a=>a?{start:a.from,end:a.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.isLiveEnded$.pipe(Vo(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Vt({hasLiveOffsetByPaused:qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(a=>a.to),q(),Q(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Vt({atLiveEdge:Vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ro({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:a,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return a&&Math.abs(o)<l/1e3}),q(),Vo(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:a,hasPausedTimeoutCase:o})=>a&&!o)).subscribe(this.info.atLiveEdge$)).add(Vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:a,position:o,duration:u})=>a&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),Vo(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Q(a=>a.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Q(a=>a.volume),q()).subscribe(this.info.volume$)).add(Ro({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(qt(e.providerOutput.endedEvent$.pipe(jc(!0)),e.providerOutput.seekedEvent$.pipe(jc(!1))).pipe(q()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Q(a=>({id:a?`No${a}`:"NoProviders",category:Ga.VIDEO_PIPELINE,message:a?`${a} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(H(),Q(a=>a??Ya()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),Q(()=>Ya()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),Q(()=>Ya()-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 B(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new B(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(F(({to:a})=>a==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=qt(e.providerOutput.isBuffering$,t,i).pipe(Q(()=>{let a=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return a&&!o}),q());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(qt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(qt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),p=this.chromecastInitializer.castState$.getValue(),c;p==="CONNECTED"?c="second_screen":u?l?a?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new zc;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(F(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=mt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(qt(this.desiredState.videoTrack.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Q(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;qa(this.providerContainer),qa(e),gu(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>bu(t)),this.providerContainer.current$.subscribe(({type:t})=>zi("provider",t)),e.duration$.subscribe(t=>zi("duration",t)),e.availableVideoTracks$.pipe(F(t=>!!t.length),H()).subscribe(t=>zi("tracks",t)),this.events.fatalError$.subscribe(new Re("fatalError")),this.events.managedError$.subscribe(new Re("managedError")),e.position$.subscribe(new Re("position")),e.currentVideoTrack$.pipe(Q(t=>t?.quality)).subscribe(new Re("quality")),this.info.currentBuffer$.subscribe(new Re("buffer")),e.isBuffering$.subscribe(new Re("isBuffering"))].forEach(t=>this.subscription.add(t)),zi("codecs",O.video.supportedCodecs)}initTracerSubscription(){let e=Wc(this.tracer.log.bind(this.tracer)),t=Wc(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(F(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(F(i=>i>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(F(i=>i>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Vt({currentBuffer:this.info.currentBuffer$.pipe(F(i=>i.end>0),q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(q())}).pipe(Co(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(Vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(F(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Co(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),F(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),F(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),F(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(F(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Co(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),F(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ga.DOM,message:String(r)})})};this.subscription.add(qt(Do(document,"visibilitychange"),Do(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gt({quality:t,availableTracks:Gt(e),track:Gt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xi()}};import{Subscription as FV,Observable as _V,Subject as NV,ValueSubject as UV,VideoQuality as HV}from"@vkontakte/videoplayer-shared/evergreen";var jV=`@vkontakte/videoplayer-core@${Oo}`;export{As as ChromecastState,tn as HttpConnectionType,_V as Observable,Ce as PlaybackState,Ka as Player,Ps as PredefinedQualityLimits,jV as SDK_VERSION,NV as Subject,FV as Subscription,rn as Surface,Oo as VERSION,UV as ValueSubject,Et as VideoFormat,HV as VideoQuality,O as clientChecker,ji as isMobile};