@vkontakte/videoplayer-core 2.0.136-dev.3c83a8ac.0 → 2.0.136-dev.65dd5a4b.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +23 -23
- package/es2015.esm.js +16 -16
- package/es2018.cjs.js +19 -19
- package/es2018.esm.js +17 -17
- package/es2024.cjs.js +19 -19
- package/es2024.esm.js +16 -16
- package/esnext.cjs.js +19 -19
- package/esnext.esm.js +16 -16
- package/evergreen.esm.js +18 -18
- package/package.json +2 -2
- package/types/index.d.ts +1 -0
- package/types/providers/DashProvider/lib/player.d.ts +1 -1
- package/types/utils/videoFormat.d.ts +2 -1
package/evergreen.esm.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.136-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.136-dev.65dd5a4b.0
|
|
3
|
+
* Wed, 09 Jul 2025 08:27:14 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
|
|
5
5
|
*/
|
|
6
|
-
var qn="2.0.136-dev.3c83a8ac.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ge||{}),Ze=(g=>(g.MPEG="MPEG",g.DASH="DASH",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_STREAMS="DASH_STREAMS",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(Ze||{});var zr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(zr||{}),ga=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ga||{});var Sa=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(Sa||{}),Wr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Wr||{});import{assertNever as Zn,assertNonNullable as Xl,isNonNullable as qr,ValueSubject as va,Subject as Jl,Subscription as Zl,merge as ec,observableFrom as tc,fromEvent as Yn,map as Kn,tap as Xn,filterChanged as ic,isNullable as ya,ErrorCategory as Jn}from"@vkontakte/videoplayer-shared/evergreen";var Gn=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Gr=class{constructor(e){this.connection$=new va(void 0);this.castState$=new va("NOT_AVAILABLE");this.errorEvent$=new Jl;this.realCastState$=new va("NOT_AVAILABLE");this.subscription=new Zl;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=qr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Gn("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Jn.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(){qr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ya(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ya(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(Yn(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 Zn(r.sessionState)}})).add(ec(Yn(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Xn(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Kn(r=>r.castState)),tc([i.getCastState()])).pipe(ic(),Kn(rc),Xn(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=qr(this.connection$.getValue());if(s&&!a){let n=i.getCurrentSession();Xl(n);let u=n.getCastDevice(),l=n.getMediaSession()?.media?.contentId;(ya(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:n,castDevice:u}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?qr(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:Jn.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},rc=o=>{switch(o){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Zn(o)}};import{assertNever as eo}from"@vkontakte/videoplayer-shared/evergreen";var ee=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:eo(t)}return o},ht=(o,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(o);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(o);return Number(t.searchParams.get("offset_p")??0)}default:eo(e)}};var A=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as sc,Subject as Yr,merge as to}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new Yr;this.transitionEnded$=new Yr;this.transitionUpdated$=new Yr;this.forceChanged$=new Yr;this.stateChangeStarted$=to(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=to(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||sc(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 ac}from"@vkontakte/videoplayer-shared/evergreen";var io=o=>{switch(o){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return ac(o)}};import{assertNever as Wt,assertNonNullable as At,debounce as ro,ErrorCategory as so,fromEvent as Lt,isNonNullable as ao,map as no,merge as oo,observableFrom as nc,Subject as oc,Subscription as Ta,timeout as uc,getHighestQuality as lc}from"@vkontakte/videoplayer-shared/evergreen";var cc=5,dc=5,hc=500,uo=7e3,Ii=class{constructor(e){this.subscription=new Ta;this.loadMediaTimeoutSubscription=new Ta;this.videoState=new O("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:Wt(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:Wt(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:Wt(e)}break}default:Wt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(io(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 Ta;this.subscription.add(e),this.subscription.add(oo(this.videoState.stateChangeStarted$.pipe(no(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(no(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 oc;e.add(r.pipe(ro(hc)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let n=a.value;this.params.output.position$.next(n),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(n-s)>cc)&&r.next(n),s=n})),e.add(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,n=this.params.output.isBuffering$.getValue(),u=a===chrome.cast.media.PlayerState.BUFFERING;switch(n!==u&&this.params.output.isBuffering$.next(u),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<dc&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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:Wt(a)}}),t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=oo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nc(["init"])).pipe(ro(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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(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"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&A(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];At(l);let d=lc(Object.keys(l));At(d);let c=l[d];At(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];At(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];At(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];At(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];At(l),i=ee(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",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:so.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Wt(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:n,subtitle:u}=this.params.meta;return ao(n)&&(a.metadata.title=n),ao(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(uc(uo).subscribe(()=>s(`timeout(${uo})`)))});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:so.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as co}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as pc}from"@vkontakte/videoplayer-shared/evergreen";var lo=o=>{try{o.pause(),o.playbackRate=0,pc(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as mc,Subscription as fc}from"@vkontakte/videoplayer-shared/evergreen";var Ia=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)}},Ea=window.WeakMap?new WeakMap:new Ia,xa=window.WeakMap?new WeakMap:new Map,bc=(o,e=20)=>{let t=0;return mc(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},Se=(o,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=o.querySelector("video"),r=!!i;i?co(i):(i=document.createElement("video"),o.appendChild(i)),Ea.set(i,r);let s=new fc;return s.add(bc(i,e)),xa.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},ve=o=>{xa.get(o)?.unsubscribe(),xa.delete(o);let t=Ea.get(o);Ea.delete(o),t?co(o):lo(o)};import{assertNonNullable as xi,isNonNullable as We,isNullable as vc,fromEvent as qt,merge as ho,observableFrom as po,filterChanged as mo,map as ki,Subject as fo,Subscription as yc,ValueSubject as Tc,ErrorCategory as Ic}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as ka,isNullable as gc,Subscription as Sc}from"@vkontakte/videoplayer-shared/evergreen";var Kr=(o,e,t,{equal:i=(a,n)=>a===n,changed$:r,onError:s}={})=>{let a=o.getState(),n=e(),u=gc(r),l=new Sc;return r&&l.add(r.subscribe(d=>{let c=o.getState();i(d,c)&&o.setState(d)},s)),i(n,a)||(t(a),u&&o.setState(a)),l.add(o.stateChangeStarted$.subscribe(d=>{t(d.to),u&&o.setState(d.to)},s)),l},ze=(o,e,t)=>Kr(e,()=>o.loop,i=>{ka(i)&&(o.loop=i)},{onError:t}),ye=(o,e,t,i)=>Kr(e,()=>({muted:o.muted,volume:o.volume}),r=>{ka(r)&&(o.muted=r.muted,o.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),Re=(o,e,t,i)=>Kr(e,()=>o.playbackRate,r=>{ka(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Ei=Kr;var Ec=o=>["__",o.language,o.label].join("|"),xc=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},wa=class o{constructor(e){this.available$=new fo;this.current$=new Tc(void 0);this.error$=new fo;this.subscription=new yc;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:Ic.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(Ei(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:n},u)=>n===a[u].id),changed$:this.available$.pipe(ki(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Ei(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:n},u)=>n===a[u].id),changed$:this.available$.pipe(ki(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Ei(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(Ei(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){xi(this.video);let{textTracks:e}=this.video;this.subscription.add(qt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ho(qt(e,"addtrack"),qt(e,"removetrack"),po(["init"])).pipe(ki(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),mo((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(ho(qt(e,"change"),po(["init"])).pipe(ki(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ki(i=>i&&this.htmlTextTrackToITextTrack(i).id),mo()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(qt(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(qt(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;We(t.align)&&(r.align=t.align),We(t.position)&&(r.position=t.position),We(t.size)&&(r.size=t.size),We(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){xi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(o.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Ec(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){xi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(vc(e)||!xc(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){xi(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){xi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},De=wa;var Pt=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 bo=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Aa=o=>{let e=bo(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},go=o=>{let e=bo(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as me,map as qe,merge as rs,filterChanged as xo,isNonNullable as ko,Subject as Dc,filter as Pa,mapTo as $a,combine as Bc,once as Vc,throttle as Cc,ErrorCategory as Oc,ValueSubject as wo,Subscription as Fc}from"@vkontakte/videoplayer-shared/evergreen";var kc=3,So=(o,e,t=kc)=>{let i=0,r=0;for(let s=0;s<o.length;s++){let a=o.start(s),n=o.end(s);if(a<=e&&e<=n){if(i=a,r=n,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)o.end(u)+t>=i&&(i=o.start(u));for(let u=s+1;u<o.length;u++)o.start(u)-t<=r&&(r=o.end(u))}}return{from:i,to:r}};var Xr=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,n=/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||n||"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 wi=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Jr=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=wi()}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,n=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||n||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 Zr=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 we=()=>window.ManagedMediaSource||window.MediaSource,Gt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),vo=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),es=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var wc=document.createElement("video"),Ac='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Lc='video/mp4; codecs="hev1.1.6.L93.B0"',yo='video/webm; codecs="vp09.00.10.08"',To='video/webm; codecs="av01.0.00M.08"',Pc='audio/mp4; codecs="mp4a.40.2"',$c='audio/webm; codecs="opus"',Io,Mc=async()=>{if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:To}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:yo}})]);Io={DASH_WEBM_AV1:e,DASH_WEBM:t}};Mc().catch(o=>{console.log(wc),console.error(o)});var ts=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 Io}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:Gt(),mse:vo(),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=!!we()?.isTypeSupported?.(Ac),t=!!we()?.isTypeSupported?.(Lc),i=!!we()?.isTypeSupported?.(Pc);this._codecs={h264:e,h265:t,vp9:!!we()?.isTypeSupported?.(yo),av1:!!we()?.isTypeSupported?.(To),aac:i,opus:!!we()?.isTypeSupported?.($c),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 Eo="audio/mpeg",is=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Eo)},this._codecs={mp3:!!we()?.isTypeSupported?.(Eo)}}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 Rc}from"@vkontakte/videoplayer-shared/evergreen";var La=class{constructor(){this.isInited$=new Rc(!1);this._displayChecker=new Zr,this._deviceChecker=new Jr(this._displayChecker),this._browserChecker=new Xr,this._videoChecker=new ts(this._deviceChecker,this._browserChecker),this._audioChecker=new is,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)}},V=new La;var Te=o=>{let e=v=>me(o,v).pipe($a(void 0)),t=new Fc,i=()=>t.unsubscribe(),r=rs(me(o,"progress"),me(o,"timeupdate")).pipe(qe(()=>So(o.buffered,o.currentTime))),s=V.browser.isSafari?Bc({play:e("play").pipe(Vc()),playing:e("playing")}).pipe($a(void 0)):e("playing"),a=me(o,"volumechange").pipe(qe(()=>({muted:o.muted,volume:o.volume}))),n=me(o,"ratechange").pipe(qe(()=>o.playbackRate)),u=me(o,"error").pipe(Pa(()=>!!(o.error||o.played.length)),qe(()=>{let v=o.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:Oc.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:o.error??void 0}})),l=me(o,"timeupdate").pipe(qe(()=>o.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new Dc,h=.3,p;t.add(rs(...d.map(v=>me(o,v))).subscribe(v=>{let M=o.currentTime;o.loop&&ko(p)&&ko(M)&&p>=o.duration-h&&M<=h&&c.next(p),p=M}));let m=e("pause").pipe(Pa(()=>!o.error&&p!==o.duration)),f=me(o,"enterpictureinpicture"),b=me(o,"leavepictureinpicture"),S=new wo(go(o));t.add(f.subscribe(()=>S.next(!0))),t.add(b.subscribe(()=>S.next(!1)));let x=new wo(Aa(o)),g=me(o,"fullscreenchange");t.add(g.pipe(qe(()=>Aa(o))).subscribe(x));let I=.1,E=1e3,P=me(o,"timeupdate").pipe(qe(v=>o.duration-o.currentTime<I),xo()),B=rs(P.pipe(Pa(v=>!o.loop&&v)),me(o,"ended")).pipe(Cc(E),$a(void 0)),$=rs(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>me(o,v)),P.pipe(qe(v=>({type:v?"ended":"unknown"})))).pipe(qe(v=>V.browser.isFirefox&&v.type==="ended"?o.readyState<2:o.readyState<3),xo());return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:B,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$:me(o,"durationchange").pipe(qe(()=>o.duration)),isBuffering$:$,currentBuffer$:r,volumeState$:a,playbackRateState$:n,inPiP$:S,inFullscreen$:x,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as pt}from"@vkontakte/videoplayer-shared/evergreen";var mt=o=>{switch(o){case"mobile":return pt.Q_144P;case"lowest":return pt.Q_240P;case"low":return pt.Q_360P;case"sd":case"medium":return pt.Q_480P;case"hd":case"high":return pt.Q_720P;case"fullhd":case"full":return pt.Q_1080P;case"quadhd":case"quad":return pt.Q_1440P;case"ultrahd":case"ultra":return pt.Q_2160P}};import{isNonNullable as q,isNullable as us,now as Co,isHigher as ls,isHigherOrEqual as Kt,isInvariantQuality as cs,isLowerOrEqual as Xt,videoSizeToQuality as Oo,assertNotEmptyArray as ds,assertNonNullable as Fo}from"@vkontakte/videoplayer-shared/evergreen";var Ma=!1,tt={},Ao=o=>{Ma=o},Lo=()=>{tt={}},Po=o=>{o(tt)},Ai=(o,e)=>{Ma&&(tt.meta=tt.meta??{},tt.meta[o]=e)},fe=class{constructor(e){this.name=e}next(e){if(!Ma)return;tt.series=tt.series??{};let t=tt.series[this.name]??[];t.push([Date.now(),e]),tt.series[this.name]=t}};import{isHigher as _c,isHigherOrEqual as Ab,isLower as $o,isLowerOrEqual as Lb,isNonNullable as ss,isNullable as Nc,videoHeightToQuality as as}from"@vkontakte/videoplayer-shared/evergreen";function Ra(o,e,t){return!o.max&&o.min===e?"high_quality":!o.min&&o.max===t?"traffic_saving":"unknown"}function ns(o,e,t){return!!o&&Ra(o,e,t)==="high_quality"}function Yt(o,e,t){return Nc(o)||ss(o.min)&&ss(o.max)&&$o(o.max,o.min)||ss(o.min)&&e&&_c(o.min,e)||ss(o.max)&&t&&$o(o.max,t)}function Mo({limits:o,highestAvailableHeight:e,lowestAvailableHeight:t}){return Yt({max:o?.max?as(o.max):void 0,min:o?.min?as(o.min):void 0},e?as(e):void 0,t?as(t):void 0)}var _o=new fe("best_bitrate"),hs=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t;var Jt=o=>(e,t)=>o*(Number(e.bitrate)-Number(t.bitrate)),ft=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Co()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ps='Assertion "ABR Tracks is empty array" failed',os=new WeakMap,Ro=new WeakMap,Do=new WeakMap,Li=(o,e,t,i)=>{let r=[...e].sort(Jt(1)),s=[...t].sort(Jt(1)),a=s.filter(u=>q(u.bitrate)&&q(o.bitrate)?o.bitrate/u.bitrate>i:!0),n=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Pi=(o,e,t,i)=>{let r=os.get(e);r||(r=[...e].sort(Jt(1)),os.set(e,r));let s=os.get(t);s||(s=[...t].sort(Jt(1)),os.set(t,s));let a=Do.get(o);a||(a=s.filter(u=>q(u.bitrate)&&q(o.bitrate)?o.bitrate/u.bitrate>i:!0),Do.set(o,a));let n=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Bo=o=>"quality"in o,ms=(o,e,t,i)=>{let r=q(i?.last?.bitrate)&&q(t?.bitrate)&&i.last.bitrate<t.bitrate?o.trackCooldownIncreaseQuality:o.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Co()-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 n=Bo(a)?"video":"audio",u=Bo(a)?a.quality:a.bitrate;return e({message:`
|
|
6
|
+
var qn="2.0.136-dev.65dd5a4b.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ge||{}),Ze=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(Ze||{});var zr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(zr||{}),ga=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ga||{});var Sa=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(Sa||{}),Wr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Wr||{});import{assertNever as Zn,assertNonNullable as Xl,isNonNullable as qr,ValueSubject as va,Subject as Jl,Subscription as Zl,merge as ec,observableFrom as tc,fromEvent as Yn,map as Kn,tap as Xn,filterChanged as ic,isNullable as ya,ErrorCategory as Jn}from"@vkontakte/videoplayer-shared/evergreen";var Gn=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Gr=class{constructor(e){this.connection$=new va(void 0);this.castState$=new va("NOT_AVAILABLE");this.errorEvent$=new Jl;this.realCastState$=new va("NOT_AVAILABLE");this.subscription=new Zl;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=qr(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Gn("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Jn.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(){qr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ya(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ya(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(Yn(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 Zn(r.sessionState)}})).add(ec(Yn(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Xn(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Kn(r=>r.castState)),tc([i.getCastState()])).pipe(ic(),Kn(rc),Xn(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=qr(this.connection$.getValue());if(s&&!a){let n=i.getCurrentSession();Xl(n);let u=n.getCastDevice(),l=n.getMediaSession()?.media?.contentId;(ya(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:n,castDevice:u}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?qr(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:Jn.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},rc=o=>{switch(o){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Zn(o)}};import{assertNever as eo}from"@vkontakte/videoplayer-shared/evergreen";var ee=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:eo(t)}return o},ht=(o,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(o);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(o);return Number(t.searchParams.get("offset_p")??0)}default:eo(e)}};var A=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as sc,Subject as Yr,merge as to}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new Yr;this.transitionEnded$=new Yr;this.transitionUpdated$=new Yr;this.forceChanged$=new Yr;this.stateChangeStarted$=to(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=to(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||sc(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 ac}from"@vkontakte/videoplayer-shared/evergreen";var io=o=>{switch(o){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return ac(o)}},nc=o=>!!(o.DASH_ONDEMAND||o.HLS_ONDEMAND);import{assertNever as Wt,assertNonNullable as At,debounce as ro,ErrorCategory as so,fromEvent as Lt,isNonNullable as ao,map as no,merge as oo,observableFrom as oc,Subject as uc,Subscription as Ta,timeout as lc,getHighestQuality as cc}from"@vkontakte/videoplayer-shared/evergreen";var dc=5,hc=5,pc=500,uo=7e3,Ii=class{constructor(e){this.subscription=new Ta;this.loadMediaTimeoutSubscription=new Ta;this.videoState=new O("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:Wt(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:Wt(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:Wt(e)}break}default:Wt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(io(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 Ta;this.subscription.add(e),this.subscription.add(oo(this.videoState.stateChangeStarted$.pipe(no(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(no(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 uc;e.add(r.pipe(ro(pc)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let n=a.value;this.params.output.position$.next(n),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(n-s)>dc)&&r.next(n),s=n})),e.add(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,n=this.params.output.isBuffering$.getValue(),u=a===chrome.cast.media.PlayerState.BUFFERING;switch(n!==u&&this.params.output.isBuffering$.next(u),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<hc&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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:Wt(a)}}),t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Lt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=oo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,oc(["init"])).pipe(ro(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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(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"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&A(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];At(l);let d=cc(Object.keys(l));At(d);let c=l[d];At(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];At(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];At(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];At(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];At(l),i=ee(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",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:so.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Wt(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:n,subtitle:u}=this.params.meta;return ao(n)&&(a.metadata.title=n),ao(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(lc(uo).subscribe(()=>s(`timeout(${uo})`)))});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:so.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as co}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as mc}from"@vkontakte/videoplayer-shared/evergreen";var lo=o=>{try{o.pause(),o.playbackRate=0,mc(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as fc,Subscription as bc}from"@vkontakte/videoplayer-shared/evergreen";var Ia=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)}},Ea=window.WeakMap?new WeakMap:new Ia,xa=window.WeakMap?new WeakMap:new Map,gc=(o,e=20)=>{let t=0;return fc(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},Se=(o,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=o.querySelector("video"),r=!!i;i?co(i):(i=document.createElement("video"),o.appendChild(i)),Ea.set(i,r);let s=new bc;return s.add(gc(i,e)),xa.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},ve=o=>{xa.get(o)?.unsubscribe(),xa.delete(o);let t=Ea.get(o);Ea.delete(o),t?co(o):lo(o)};import{assertNonNullable as xi,isNonNullable as We,isNullable as yc,fromEvent as qt,merge as ho,observableFrom as po,filterChanged as mo,map as ki,Subject as fo,Subscription as Tc,ValueSubject as Ic,ErrorCategory as Ec}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as ka,isNullable as Sc,Subscription as vc}from"@vkontakte/videoplayer-shared/evergreen";var Kr=(o,e,t,{equal:i=(a,n)=>a===n,changed$:r,onError:s}={})=>{let a=o.getState(),n=e(),u=Sc(r),l=new vc;return r&&l.add(r.subscribe(d=>{let c=o.getState();i(d,c)&&o.setState(d)},s)),i(n,a)||(t(a),u&&o.setState(a)),l.add(o.stateChangeStarted$.subscribe(d=>{t(d.to),u&&o.setState(d.to)},s)),l},ze=(o,e,t)=>Kr(e,()=>o.loop,i=>{ka(i)&&(o.loop=i)},{onError:t}),ye=(o,e,t,i)=>Kr(e,()=>({muted:o.muted,volume:o.volume}),r=>{ka(r)&&(o.muted=r.muted,o.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),Re=(o,e,t,i)=>Kr(e,()=>o.playbackRate,r=>{ka(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Ei=Kr;var xc=o=>["__",o.language,o.label].join("|"),kc=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},wa=class o{constructor(e){this.available$=new fo;this.current$=new Ic(void 0);this.error$=new fo;this.subscription=new Tc;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:Ec.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(Ei(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:n},u)=>n===a[u].id),changed$:this.available$.pipe(ki(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Ei(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:n},u)=>n===a[u].id),changed$:this.available$.pipe(ki(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Ei(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(Ei(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){xi(this.video);let{textTracks:e}=this.video;this.subscription.add(qt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ho(qt(e,"addtrack"),qt(e,"removetrack"),po(["init"])).pipe(ki(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),mo((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(ho(qt(e,"change"),po(["init"])).pipe(ki(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ki(i=>i&&this.htmlTextTrackToITextTrack(i).id),mo()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(qt(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(qt(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;We(t.align)&&(r.align=t.align),We(t.position)&&(r.position=t.position),We(t.size)&&(r.size=t.size),We(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){xi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(o.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:xc(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){xi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(yc(e)||!kc(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){xi(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){xi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},De=wa;var Pt=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 bo=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Aa=o=>{let e=bo(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},go=o=>{let e=bo(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as me,map as qe,merge as rs,filterChanged as xo,isNonNullable as ko,Subject as Bc,filter as Pa,mapTo as $a,combine as Vc,once as Cc,throttle as Oc,ErrorCategory as Fc,ValueSubject as wo,Subscription as _c}from"@vkontakte/videoplayer-shared/evergreen";var wc=3,So=(o,e,t=wc)=>{let i=0,r=0;for(let s=0;s<o.length;s++){let a=o.start(s),n=o.end(s);if(a<=e&&e<=n){if(i=a,r=n,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)o.end(u)+t>=i&&(i=o.start(u));for(let u=s+1;u<o.length;u++)o.start(u)-t<=r&&(r=o.end(u))}}return{from:i,to:r}};var Xr=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,n=/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||n||"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 wi=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Jr=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=wi()}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,n=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||n||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 Zr=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 we=()=>window.ManagedMediaSource||window.MediaSource,Gt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),vo=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),es=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Ac=document.createElement("video"),Lc='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Pc='video/mp4; codecs="hev1.1.6.L93.B0"',yo='video/webm; codecs="vp09.00.10.08"',To='video/webm; codecs="av01.0.00M.08"',$c='audio/mp4; codecs="mp4a.40.2"',Mc='audio/webm; codecs="opus"',Io,Rc=async()=>{if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:To}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:yo}})]);Io={DASH_WEBM_AV1:e,DASH_WEBM:t}};Rc().catch(o=>{console.log(Ac),console.error(o)});var ts=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 Io}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:Gt(),mse:vo(),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=!!we()?.isTypeSupported?.(Lc),t=!!we()?.isTypeSupported?.(Pc),i=!!we()?.isTypeSupported?.($c);this._codecs={h264:e,h265:t,vp9:!!we()?.isTypeSupported?.(yo),av1:!!we()?.isTypeSupported?.(To),aac:i,opus:!!we()?.isTypeSupported?.(Mc),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 Eo="audio/mpeg",is=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Eo)},this._codecs={mp3:!!we()?.isTypeSupported?.(Eo)}}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 Dc}from"@vkontakte/videoplayer-shared/evergreen";var La=class{constructor(){this.isInited$=new Dc(!1);this._displayChecker=new Zr,this._deviceChecker=new Jr(this._displayChecker),this._browserChecker=new Xr,this._videoChecker=new ts(this._deviceChecker,this._browserChecker),this._audioChecker=new is,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)}},V=new La;var Te=o=>{let e=v=>me(o,v).pipe($a(void 0)),t=new _c,i=()=>t.unsubscribe(),r=rs(me(o,"progress"),me(o,"timeupdate")).pipe(qe(()=>So(o.buffered,o.currentTime))),s=V.browser.isSafari?Vc({play:e("play").pipe(Cc()),playing:e("playing")}).pipe($a(void 0)):e("playing"),a=me(o,"volumechange").pipe(qe(()=>({muted:o.muted,volume:o.volume}))),n=me(o,"ratechange").pipe(qe(()=>o.playbackRate)),u=me(o,"error").pipe(Pa(()=>!!(o.error||o.played.length)),qe(()=>{let v=o.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:Fc.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:o.error??void 0}})),l=me(o,"timeupdate").pipe(qe(()=>o.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new Bc,h=.3,p;t.add(rs(...d.map(v=>me(o,v))).subscribe(v=>{let M=o.currentTime;o.loop&&ko(p)&&ko(M)&&p>=o.duration-h&&M<=h&&c.next(p),p=M}));let m=e("pause").pipe(Pa(()=>!o.error&&p!==o.duration)),f=me(o,"enterpictureinpicture"),b=me(o,"leavepictureinpicture"),g=new wo(go(o));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let x=new wo(Aa(o)),S=me(o,"fullscreenchange");t.add(S.pipe(qe(()=>Aa(o))).subscribe(x));let I=.1,E=1e3,P=me(o,"timeupdate").pipe(qe(v=>o.duration-o.currentTime<I),xo()),B=rs(P.pipe(Pa(v=>!o.loop&&v)),me(o,"ended")).pipe(Oc(E),$a(void 0)),$=rs(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>me(o,v)),P.pipe(qe(v=>({type:v?"ended":"unknown"})))).pipe(qe(v=>V.browser.isFirefox&&v.type==="ended"?o.readyState<2:o.readyState<3),xo());return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:B,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$:me(o,"durationchange").pipe(qe(()=>o.duration)),isBuffering$:$,currentBuffer$:r,volumeState$:a,playbackRateState$:n,inPiP$:g,inFullscreen$:x,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as pt}from"@vkontakte/videoplayer-shared/evergreen";var mt=o=>{switch(o){case"mobile":return pt.Q_144P;case"lowest":return pt.Q_240P;case"low":return pt.Q_360P;case"sd":case"medium":return pt.Q_480P;case"hd":case"high":return pt.Q_720P;case"fullhd":case"full":return pt.Q_1080P;case"quadhd":case"quad":return pt.Q_1440P;case"ultrahd":case"ultra":return pt.Q_2160P}};import{isNonNullable as q,isNullable as us,now as Co,isHigher as ls,isHigherOrEqual as Kt,isInvariantQuality as cs,isLowerOrEqual as Xt,videoSizeToQuality as Oo,assertNotEmptyArray as ds,assertNonNullable as Fo}from"@vkontakte/videoplayer-shared/evergreen";var Ma=!1,tt={},Ao=o=>{Ma=o},Lo=()=>{tt={}},Po=o=>{o(tt)},Ai=(o,e)=>{Ma&&(tt.meta=tt.meta??{},tt.meta[o]=e)},fe=class{constructor(e){this.name=e}next(e){if(!Ma)return;tt.series=tt.series??{};let t=tt.series[this.name]??[];t.push([Date.now(),e]),tt.series[this.name]=t}};import{isHigher as Nc,isHigherOrEqual as Lb,isLower as $o,isLowerOrEqual as Pb,isNonNullable as ss,isNullable as Uc,videoHeightToQuality as as}from"@vkontakte/videoplayer-shared/evergreen";function Ra(o,e,t){return!o.max&&o.min===e?"high_quality":!o.min&&o.max===t?"traffic_saving":"unknown"}function ns(o,e,t){return!!o&&Ra(o,e,t)==="high_quality"}function Yt(o,e,t){return Uc(o)||ss(o.min)&&ss(o.max)&&$o(o.max,o.min)||ss(o.min)&&e&&Nc(o.min,e)||ss(o.max)&&t&&$o(o.max,t)}function Mo({limits:o,highestAvailableHeight:e,lowestAvailableHeight:t}){return Yt({max:o?.max?as(o.max):void 0,min:o?.min?as(o.min):void 0},e?as(e):void 0,t?as(t):void 0)}var _o=new fe("best_bitrate"),hs=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t;var Jt=o=>(e,t)=>o*(Number(e.bitrate)-Number(t.bitrate)),ft=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Co()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ps='Assertion "ABR Tracks is empty array" failed',os=new WeakMap,Ro=new WeakMap,Do=new WeakMap,Li=(o,e,t,i)=>{let r=[...e].sort(Jt(1)),s=[...t].sort(Jt(1)),a=s.filter(u=>q(u.bitrate)&&q(o.bitrate)?o.bitrate/u.bitrate>i:!0),n=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Pi=(o,e,t,i)=>{let r=os.get(e);r||(r=[...e].sort(Jt(1)),os.set(e,r));let s=os.get(t);s||(s=[...t].sort(Jt(1)),os.set(t,s));let a=Do.get(o);a||(a=s.filter(u=>q(u.bitrate)&&q(o.bitrate)?o.bitrate/u.bitrate>i:!0),Do.set(o,a));let n=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return n&&a.includes(n)?n:a.length?a.at(-1):s.at(0)},Bo=o=>"quality"in o,ms=(o,e,t,i)=>{let r=q(i?.last?.bitrate)&&q(t?.bitrate)&&i.last.bitrate<t.bitrate?o.trackCooldownIncreaseQuality:o.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Co()-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 n=Bo(a)?"video":"audio",u=Bo(a)?a.quality:a.bitrate;return e({message:`
|
|
7
7
|
[last ${n} selected] ${u}
|
|
8
|
-
`}),a}return i?.recordSwitch(t),t},
|
|
8
|
+
`}),a}return i?.recordSwitch(t),t},Hc=(o,e)=>Math.log(e)/Math.log(o),No=({tuning:o,container:e,limits:t,panelSize:i})=>{let r=o.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(o.usePixelRatio&&V.display.pixelRatio){let s=V.display.pixelRatio;if(o.pixelRatioMultiplier)r*=o.pixelRatioMultiplier*(s-1)+1;else{let a=o.pixelRatioLogBase,[n=0,u=0,l=0]=o.pixelRatioLogCoefficients,d=Hc(a,n*s+u)+l;Number.isFinite(d)&&(r*=d)}}return ns(t,o.highQualityLimit,o.trafficSavingLimit)&&(r*=2),{containerSizeLimit:o.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Vo=new WeakMap,Ge=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{ds(o,ps);let{containerSizeFactor:b,containerSizeLimit:g}=No({container:e,tuning:i,limits:r,panelSize:f}),x=i.considerPlaybackRate&&q(n)?n:1,S=Vo.get(o);S||(S=o.filter(T=>!cs(T.quality)).sort((T,w)=>ls(T.quality,w.quality)?-1:1),Vo.set(o,S));let I=S.at(-1)?.quality,E=S.at(0)?.quality,P=Yt(r,E,I),B=x*hs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},$=null;for(let T of S){let w=!0;if(g)if(T.size)w=T.size.width<=g.width&&T.size.height<=g.height;else{let H=g&&Oo(g);w=H?Xt(T.quality,H):!0}if(!w){k[T.quality]="FitsContainer";continue}let K=p||t,R=q(K)&&isFinite(K)&&q(T.bitrate)?K-s>=T.bitrate*B:!0,N=ns(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===T.quality;if(!R&&!N){k[T.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&u&&!cs(u.quality)&&(a??0)<i.minBufferToSwitchUp&&ls(T.quality,u.quality)){k[T.quality]="Buffer";continue}if(!!c&&Kt(T.quality,c)&&!N){k[T.quality]="DroppedFramesLimit";continue}if(!!h&&Kt(T.quality,h)&&!N){k[T.quality]="StallsLimit";continue}let ne=P||(us(r?.max)||Xt(T.quality,r.max))&&(us(r?.min)||Kt(T.quality,r.min)),oe=q(d)&&!d?Xt(T.quality,i.backgroundVideoQualityLimit):!0;if(!ne||!oe){k[T.quality]="FitsQualityLimits";continue}$||($=T)}$&&$.bitrate&&_o.next($.bitrate);let v=$??S.at(-1)??o[0],M=l?.last,y=ms(i,m,v,l);return q(l)&&y.quality!==M?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
11
|
${o.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
|
|
@@ -17,7 +17,7 @@ var qn="2.0.136-dev.3c83a8ac.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
19
19
|
containerSizeFactor: ${b},
|
|
20
|
-
containerSizeLimit: ${
|
|
20
|
+
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
21
21
|
estimatedThroughput: ${t},
|
|
22
22
|
stallsPredictedThroughput: ${p},
|
|
23
23
|
reserve: ${s},
|
|
@@ -38,7 +38,7 @@ var qn="2.0.136-dev.3c83a8ac.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
38
38
|
|
|
39
39
|
[best video track] ${$?.quality}
|
|
40
40
|
[selected video track] ${y?.quality}
|
|
41
|
-
`}),y},fs=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{ds(o,ps);let{containerSizeFactor:b,containerSizeLimit:
|
|
41
|
+
`}),y},fs=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:n,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{ds(o,ps);let{containerSizeFactor:b,containerSizeLimit:g}=No({container:e,tuning:i,limits:r,panelSize:f}),x=i.considerPlaybackRate&&q(n)?n:1,S=o.filter(w=>!cs(w.quality)).sort((w,K)=>ls(w.quality,K.quality)?-1:1),I=S.at(-1)?.quality,E=S.at(0)?.quality,P=Yt(r,E,I),B=x*hs(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},v=S.filter(w=>{let K=!0;if(g)if(w.size)K=w.size.width<=g.width&&w.size.height<=g.height;else{let F=g&&Oo(g);K=F?Xt(w.quality,F):!0}if(!K)return k[w.quality]="FitsContainer",!1;let R=p||t,N=q(R)&&isFinite(R)&&q(w.bitrate)?R-s>=w.bitrate*B:!0,G=ns(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===w.quality;if(!N&&!G)return k[w.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&u&&!cs(u.quality)&&(a??0)<i.minBufferToSwitchUp&&ls(w.quality,u.quality))return k[w.quality]="Buffer",!1;if(!!c&&Kt(w.quality,c)&&!G)return k[w.quality]="DroppedFramesLimit",!1;if(!!h&&Kt(w.quality,h)&&!G)return k[w.quality]="StallsLimit",!1;let oe=P||(us(r?.max)||Xt(w.quality,r.max))&&(us(r?.min)||Kt(w.quality,r.min)),H=q(d)&&!d?Xt(w.quality,i.backgroundVideoQualityLimit):!0;return!oe||!H?(k[w.quality]="FitsQualityLimits",!1):!0})[0];v&&v.bitrate&&_o.next(v.bitrate);let M=v??S.at(-1)??o[0],y=l?.last,T=ms(i,m,M,l);return q(l)&&T.quality!==y?.quality&&m({message:`
|
|
42
42
|
[VIDEO TRACKS ABR]
|
|
43
43
|
[available video tracks]
|
|
44
44
|
${o.map(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${w.size?.width}:${w.size?.height} }`).join(`
|
|
@@ -50,7 +50,7 @@ var qn="2.0.136-dev.3c83a8ac.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
50
50
|
|
|
51
51
|
[limit params]
|
|
52
52
|
containerSizeFactor: ${b},
|
|
53
|
-
containerSizeLimit: ${
|
|
53
|
+
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
54
54
|
estimatedThroughput: ${t},
|
|
55
55
|
stallsPredictedThroughput: ${p},
|
|
56
56
|
reserve: ${s},
|
|
@@ -71,14 +71,14 @@ var qn="2.0.136-dev.3c83a8ac.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
71
71
|
|
|
72
72
|
[best video track] ${v?.quality}
|
|
73
73
|
[selected video track] ${T?.quality}
|
|
74
|
-
`}),T},bs=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:u,stallsPredictedThroughput:l})=>{ds(t,ps);let d=r.considerPlaybackRate&&q(s)?s:1,c=[...t].sort(Jt(-1)),h=o.bitrate;Fo(h);let p=d*hs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Li(o,e,t,r.minVideoAudioRatio),b=l||i;q(b)&&isFinite(b)&&(m=c.find(
|
|
74
|
+
`}),T},bs=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:u,stallsPredictedThroughput:l})=>{ds(t,ps);let d=r.considerPlaybackRate&&q(s)?s:1,c=[...t].sort(Jt(-1)),h=o.bitrate;Fo(h);let p=d*hs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Li(o,e,t,r.minVideoAudioRatio),b=l||i;q(b)&&isFinite(b)&&(m=c.find(S=>q(S.bitrate)&&q(f?.bitrate)?b-h>=S.bitrate*p&&S.bitrate>=f.bitrate:!1)),m||(m=f);let g=n?.last,x=m&&ms(r,u,m,n);return q(n)&&x?.bitrate!==g?.bitrate&&u({message:`
|
|
75
75
|
[AUDIO TRACKS ABR]
|
|
76
76
|
[available audio tracks]
|
|
77
|
-
${t.map(
|
|
77
|
+
${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
|
|
78
78
|
`)}
|
|
79
79
|
|
|
80
80
|
[tuning]
|
|
81
|
-
${Object.entries(r??{}).map(([
|
|
81
|
+
${Object.entries(r??{}).map(([S,I])=>`${S}: ${I}`).join(`
|
|
82
82
|
`)}
|
|
83
83
|
|
|
84
84
|
[limit params]
|
|
@@ -92,14 +92,14 @@ var qn="2.0.136-dev.3c83a8ac.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
92
92
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
93
93
|
|
|
94
94
|
[selected audio track] ${x?.id}
|
|
95
|
-
`}),x},gs=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:u,stallsPredictedThroughput:l})=>{ds(t,ps);let d=r.considerPlaybackRate&&q(s)?s:1,c=Ro.get(t);c||(c=[...t].sort(Jt(-1)),Ro.set(t,c));let h=o.bitrate;Fo(h);let p=d*hs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Pi(o,e,t,r.minVideoAudioRatio),b=l||i;q(b)&&isFinite(b)&&(m=c.find(
|
|
95
|
+
`}),x},gs=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:n,abrLogger:u,stallsPredictedThroughput:l})=>{ds(t,ps);let d=r.considerPlaybackRate&&q(s)?s:1,c=Ro.get(t);c||(c=[...t].sort(Jt(-1)),Ro.set(t,c));let h=o.bitrate;Fo(h);let p=d*hs(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Pi(o,e,t,r.minVideoAudioRatio),b=l||i;q(b)&&isFinite(b)&&(m=c.find(S=>q(S.bitrate)&&q(f?.bitrate)?b-h>=S.bitrate*p&&S.bitrate>=f.bitrate:!1)),m||(m=f);let g=n?.last,x=m&&ms(r,u,m,n);return q(n)&&x?.bitrate!==g?.bitrate&&u({message:`
|
|
96
96
|
[AUDIO TRACKS ABR]
|
|
97
97
|
[available audio tracks]
|
|
98
|
-
${t.map(
|
|
98
|
+
${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
|
|
99
99
|
`)}
|
|
100
100
|
|
|
101
101
|
[tuning]
|
|
102
|
-
${Object.entries(r??{}).map(([
|
|
102
|
+
${Object.entries(r??{}).map(([S,I])=>`${S}: ${I}`).join(`
|
|
103
103
|
`)}
|
|
104
104
|
|
|
105
105
|
[limit params]
|
|
@@ -113,14 +113,14 @@ var qn="2.0.136-dev.3c83a8ac.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",
|
|
|
113
113
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
114
114
|
|
|
115
115
|
[selected audio track] ${x?.id}
|
|
116
|
-
`}),x};var ue=o=>new URL(o).hostname;import{assertNever as Wo,assertNonNullable as qo,combine as ud,debounce as ld,ErrorCategory as Go,filter as Yo,filterChanged as cd,isNonNullable as Oa,map as Ts,merge as Ko,observableFrom as dd,once as hd,Subscription as pd,ValueSubject as Fa,videoQualityToHeight as Xo,videoSizeToQuality as md}from"@vkontakte/videoplayer-shared/evergreen";var Uo=o=>{if(o instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(o.message))throw o;return!(o instanceof DOMException&&(o.code===20||o.name==="AbortError"))},Ie=async(o,e)=>{let t=o.muted;try{await o.play()}catch(i){if(!Uo(i))return!1;if(e&&e(),t)return console.warn(i),!1;o.muted=!0;try{await o.play()}catch(r){return Uo(r)&&(o.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as vs,isNullable as jc,assertNonNullable as Ri}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Ho,assertNonNullable as Ss,now as Hc}from"@vkontakte/videoplayer-shared/evergreen";function re(){return Hc()}function Da(o){return re()-o}function Ba(o){let e=o.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,n,u=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let l=a.indexOf("?")>-1?"&":"?";return u&&(a+=l+"lowLat=1",l="&"),n&&(a+=l+"_rnd="+Math.floor(999999999*Math.random())),a}}}function Qo(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function Zt(o,e,t,i){let r=window.XMLHttpRequest,s,a,n,u=!1,l=0,d,c,h=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;Ss(d);let y=Da(d),T;if(y<f){T=f-y,setTimeout(b,T);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,P()},S=y=>(s=y,M),x=y=>(c=y,M),g=()=>(p="json",M),I=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},E=y=>(h=y,M),P=()=>{d=re(),a=new r,a.open("get",o);let y=0,T,w=0,K=()=>(Ss(d),Math.max(d,Math.max(T||0,w||0)));if(s&&a.addEventListener("progress",R=>{let N=re();s.updateChunk&&R.loaded>y&&(s.updateChunk(K(),R.loaded-y),y=R.loaded,T=N)}),n&&(a.timeout=n,a.addEventListener("timeout",()=>I())),a.addEventListener("load",()=>{if(u)return;Ss(a);let R=a.status;if(R>=200&&R<300){let{response:N,responseType:G}=a,Z=N?.byteLength;if(typeof Z=="number"&&s){let te=Z-y;te&&s.updateChunk&&s.updateChunk(K(),te)}G==="json"&&(!N||!Object.values(N).length)?I():(c&&c(),e(N))}else I()}),a.addEventListener("error",()=>{I()}),h){let R=()=>{Ss(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(w=re(),a.removeEventListener("readystatechange",R))};a.addEventListener("readystatechange",R)}return a.responseType=p,a.send(),M},M={withBitrateReporting:S,withParallel:E,withJSONResponse:g,withRetryCount:y=>(l=y,M),withRetryInterval:(y,T)=>(Ho(y)&&(f=y),Ho(T)&&(m=T),M),withTimeout:y=>(n=y,M),withFinally:x,send:P,abort:()=>{a&&(a.abort(),a=void 0),u=!0,c&&c()}};return M}var $i=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,n=s.end-s.start;i+=a;let u=s.bytes*a/n;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 Mi=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=re(),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=re()-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()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zt(t,s,()=>r("error"),n),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=re()}_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=re();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 n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-1?"":"; removed pending"}`),this._sendRequest(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 zc}from"@vkontakte/videoplayer-shared/evergreen";var ys=1e4,Va=3;var Wc=6e4,qc=10,Gc=1,Yc=500,Di=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 zc,this.chunkRateEstimator=new $i(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ba(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=Ba(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*(V.display.pixelRatio||1)*t.offsetHeight||520;for(let n=0;n<this.manifest.length;++n){s=this.manifest[n];let{max:u,min:l}=this.autoQualityLimits||{};!Mo({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||vs(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=()=>{Qo(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 Mi(Va,ys,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,n=null,u=null,l=null,d=!1,c=()=>{let I=s&&(!d||d===this.rep);return I||t("Not running!"),I},h=(I,E,P)=>{u&&u.abort(),u=Zt(this.urlResolver.resolve(I,!1),E,P,()=>this._retryCallback()).withTimeout(ys).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Va).withFinally(()=>{u=null}).send()},p=(I,E,P)=>{Ri(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,P,()=>this._retryCallback()).withFinally(()=>{n=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 P=re()-1e4,B=0;for(let $=0;$<this.bufferStates.length;$++){let v=this.bufferStates[$];I=Math.min(I,v.buf),v.ts<P&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${I} drop=${B} jitter=${this.sourceJitter}`);let k=I-Gc;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,P=()=>E&&E.start?E.start.length:0,B=R=>E.start[R]/1e3,k=R=>E.dur[R]/1e3,$=R=>E.fragIndex+R,v=(R,N)=>({chunkIdx:$(R),startTS:B(R),dur:k(R),discontinuity:N}),M=()=>{let R=0;if(E&&E.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=N;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let te=E.dur.length-1;for(;te>=0&&(Z-=E.dur[te],!(Z<=0));--te);R=Math.min(te,E.dur.length-1-G),R=Math.max(R,0)}return v(R,!0)},y=R=>{let N=P();if(!(N<=0)){if(vs(R)){for(let G=0;G<N;G++)if(B(G)>R)return v(G)}return M()}},T=R=>{let N=P(),G=R?R.chunkIdx+1:0,Z=G-E.fragIndex;if(!(N<=0)){if(!R||Z<0||Z-N>qc)return t(`Resync: offset=${Z} bChunks=${N} chunk=`+JSON.stringify(R)),M();if(!(Z>=N))return v(G-E.fragIndex,!1)}},w=(R,N,G)=>{l&&l.abort(),l=Zt(this.urlResolver.resolve(R,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(ys).withRetryCount(Va).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,N)=>{w(I,G=>{if(!c())return;E=G;let Z=!!E.lowLatency;Z!==this.lowLatency&&f(Z);let te=0;for(let ne=0;ne<E.dur.length;++ne)te+=E.dur[ne];te>0&&(Ri(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/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,R(y(N))},()=>this._handleNetworkError())},nextChunk:T}},x=()=>{s=!1,n&&n.abort(),u&&u.abort(),l&&l.abort(),Ri(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:E,logger:P}=this.params,B=S(e.jidxUrl),k,$,v,M,y=0,T,w,K,R=()=>{T&&(clearTimeout(T),T=void 0);let F=Math.max(Yc,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=y+F,he=re(),ie=Math.min(1e4,be-he);y=he;let $e=()=>{l||c()&&B.seek(()=>{c()&&(y=re(),N(),R())})};ie>0?T=window.setTimeout(()=>{this.paused?R():$e()},ie):$e()},N=()=>{let F;for(;F=B.nextChunk(M);)M=F,oe(F);let be=B.nextChunk(v);if(be){if(v&&be.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?R():(x(),this._initPlayerWith(e));return}ne(be)}else R()},G=(F,be)=>{if(!c()||!this.sourceBuffer)return;let he,ie,$e,ut=Ue=>{window.setTimeout(()=>{c()&&G(F,be)},Ue)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),ut(100);else{let Ue=re(),ke=E.currentTime;!this.paused&&E.buffered.length>1&&w===ke&&Ue-K>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),w!==ke&&(w=ke,K=Ue);let lt=this._getBufferSizeSec();if(lt>30)P(`Buffered ${lt} seconds; delaying appendBuffer`),ut(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:Ue,buf:lt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(He){if(He.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),$e=this.sourceBuffer.buffered.length,$e!==0&&(he=this.sourceBuffer.buffered.start(0),ie=ke,ie-he>4&&this.sourceBuffer.remove(he,ie-3)),ut(1e3);else throw He}}},Z=()=>{$&&k&&(P([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(v)]),G($,function(){$=null,N()}))},te=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),ne=F=>{c()&&p(te(F),(be,he)=>{if(c()){if(he/=1e3,$=be,v=F,a=F.startTS,he){let ie=Math.min(10,F.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ie:ie}Z()}},()=>this._handleNetworkError())},oe=F=>{c()&&(Ri(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(F),!1)))},H=F=>{c()&&(e.cachedHeader=F,G(F,()=>{k=!0,Z()}))};s=!0,B.seek(F=>{if(c()){if(y=re(),!F){R();return}M=F,!jc(I)||F.startTS>I?ne(F):(v=F,N())}},I),e.cachedHeader?H(e.cachedHeader):h(e.headerUrl,H,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>a},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),vs(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,Ri(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return vs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),m=c/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(h,p)=>{let m=re();if(this.chunkRateEstimator.addInterval(h,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:b}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},a=-1/0,n,u=!0,l=()=>{let c=s.get();if(c&&n&&this.autoQuality){if(u&&c>n&&Da(a)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=s.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=re();c<n&&(a=h),n=c}}}_fetchManifest(e,t,i){this.manifestRequest=Zt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ys).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;Ie(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 n=[];return a?.length?(a.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,n.push(u))}),n.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),n):(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))},Wc))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Kc,filter as jo,fromEvent as Xc,interval as Jc,isHigher as Zc,isInvariantQuality as ed,isLower as td,merge as id,Subject as zo,Subscription as rd}from"@vkontakte/videoplayer-shared/evergreen";var Ca=class{constructor(){this.onDroopedVideoFramesLimit$=new zo;this.subscription=new rd;this.playing=!1;this.tracks=[];this.forceChecker$=new zo;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&&!ed(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&&Zc(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(Xc(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Jc(this.droppedFramesChecker.checkTime).pipe(jo(()=>this.playing),jo(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Kc(this.droppedFramesChecker.checkTime)),i=id(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])=>td(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}},ei=Ca;import{map as sd,Observable as ad}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as nd}from"@vkontakte/videoplayer-shared/evergreen";var Bi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var od=(o,e)=>new ad(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,n)=>{a.forEach(u=>t.next(u.isIntersecting||Bi()))},{...i,...e});r.observe(o);let s=nd(document,"visibilitychange").pipe(sd(a=>!document.hidden||Bi())).subscribe(a=>t.next(a));return()=>{r.unobserve(o),s.unsubscribe()}}),Be=od;var fd=["paused","playing","ready"],bd=["paused","playing","ready"],Vi=class{constructor(e){this.subscription=new pd;this.videoState=new O("stopped");this.representations$=new Fa([]);this.droppedFramesManager=new ei;this.maxSeekBackTime$=new Fa(1/0);this.zeroTime$=new Fa(void 0);this.liveOffset=new Pt;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:Go.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=mt(r.name)??md(r.video),n=r.bitrate/1e3,u={...r.video};if(!a)continue;let l={id:s,quality:a,bitrate:n,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),Oa(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(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(bd.includes(e)&&(a||n)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&fd.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(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(ee(this.params.source.url,u))}return;default:return Wo(e)}};this.textTracksManager=new De(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Go.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Ko(this.videoState.stateChangeStarted$.pipe(Ts(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ts(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Se(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(ue(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=Te(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Ts(r=>r.map(({track:s})=>s)),Yo(r=>!!r.length),hd()).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(cd(),Ts(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(ud({zeroTime:this.zeroTime$.pipe(Yo(Oa)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(ye(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Xo(r),min:s&&Xo(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 Wo(r.to)}},t)).add(Ko(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,dd(["init"])).pipe(ld(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ve(this.video)}createLiveDashPlayer(){let e=new Di({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&&Oa(t)?t:Ge(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(),n=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==n)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),a||u||s!==n){let l=e.find(({track:d})=>d.id===s)?.representation;qo(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;qo(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(ee(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var Jo=Vi;var se=(o,e)=>{let t=0;for(let i=0;i<o.length;i++){let r=o.start(i)*1e3,s=o.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as gh,assertNonNullable as Sh,debounce as vh,ErrorCategory as Bu,filter as nn,filterChanged as Qs,fromEvent as yh,isNonNullable as Vu,isNullable as Th,map as on,merge as js,observableFrom as un,once as Cu,Subscription as Ih}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Ci}from"@vkontakte/videoplayer-shared/evergreen";var Is=o=>{if(!o)return{id:"EmptyResponse",category:Ci.PARSER,message:"Empty response"};if(o.length<=2&&o.match(/^\d+$/))return{id:`UVError#${o}`,category:Ci.NETWORK,message:`UV Error ${o}`};let e=o.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ci.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(o,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ci.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ci.PARSER,message:"Response is valid XML, but parser failed"}};var le=(o,e,t=0)=>{for(let i=0;i<o.length;i++)if(o.start(i)*1e3-t<=e&&o.end(i)*1e3+t>e)return!0;return!1};import{abortable as Xa,assertNonNullable as ui,combine as li,ErrorCategory as _e,filter as Vs,filterChanged as pr,flattenObject as mr,fromEvent as nt,getTraceSubscriptionMethod as Zd,interval as Ja,isNonNullable as fr,isNullable as Lu,map as ci,merge as Dt,now as Za,Subject as Cs,Subscription as Pu,tap as eh,throttle as th,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as gd,ErrorCategory as Zo,Subject as eu}from"@vkontakte/videoplayer-shared/evergreen";var Sd=18,tu=!1;try{tu=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=Sd}catch(o){console.error(o)}var _a=class{constructor(e){this.bufferFull$=new eu;this.error$=new eu;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:Zo.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)};tu&&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:Zo.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:gd(t)}}},iu=_a;var ti=o=>{let e=0;for(let t=0;t<o.length;t++)e+=o.end(t)-o.start(t);return e*1e3};import{abortable as gt,assertNonNullable as Ee,ErrorCategory as rt,fromEvent as za,getExponentialDelay as Wa,isNonNullable as ai,isNullable as ce,now as xs,once as Ud,Subject as Hd,Subscription as Qd,ValueSubject as Rt}from"@vkontakte/videoplayer-shared/evergreen";var Q=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 Q{};var Oi=class extends Q{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],n=JSON.parse(a);this.serverDataReceivedTimestamp=n[this.ondemandDataReceivedKey],this.serverDataPreparedTime=n[this.ondemandDataPreparedKey]}};var Fi=class extends Q{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 _i=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Y=class extends Q{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ni=class extends Y{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 Ui=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hi=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var $t=class extends Y{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,n=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:u,SAPDeltaTime:l})}}};var Qi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ji=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zi=class extends Y{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 Wi=class extends Y{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var qi=class extends Y{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Gi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yi=class extends Y{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 Ki=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ji=class extends Y{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var er=class extends Y{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 tr=class extends Y{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 ir=class extends Y{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 rr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sr=class extends Y{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 ar=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var yd={ftyp:Fi,moov:_i,mvhd:Ni,moof:Ui,mdat:Hi,sidx:$t,trak:Qi,mdia:Gi,mfhd:Ji,tkhd:Yi,traf:Zi,tfhd:er,tfdt:tr,trun:ir,minf:Ki,sv3d:ji,st3d:zi,prhd:Wi,proj:Xi,equi:qi,uuid:Oi,stbl:rr,stsd:sr,avc1:ar,unknown:ii},it=class o{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=yd[e];return i?new i(t,new o):new ii(t,new o)}};var bt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Id=new TextDecoder("ascii"),Ed=o=>Id.decode(new DataView(o.buffer,o.byteOffset+4,4))==="ftyp",xd=o=>{let e=new $t(o,new it),t=e.earliestPresentationTime/e.timescale*1e3,i=o.byteOffset+o.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,n={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,n})},kd=(o,e)=>{let i=new it().parse(o),r=new bt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let n=s[0],u=a[a.length-1],l=n.source.byteOffset,c=u.source.byteOffset-n.source.byteOffset+u.size;return new DataView(o.buffer,l,c)},wd=o=>{let t=new it().parse(o),i=new bt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},Ad=o=>{let t=new it().parse(o);return new bt(t).find("sidx")?.timescale},Ld=(o,e)=>{let i=new it().parse(o),s=new bt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),n=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,h)=>c+h,0):l=a.defaultSampleDuration*u.sampleCount,(Number(n.baseMediaDecodeTime)+l)/e*1e3},Pd=o=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new it().parse(o),r=new bt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ru={validateData:Ed,parseInit:Pd,getIndexRange:()=>{},parseSegments:xd,parseFeedableSegmentChunk:kd,getChunkEndTime:Ld,getServerLatencyTimestamps:wd,getTimescaleFromIndex:Ad};import{assertNonNullable as Na,isNonNullable as ou,isNullable as Md}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as $d}from"@vkontakte/videoplayer-shared/evergreen";var su={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"}},au=o=>{let e=o.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=or(o,t),r=i in su,s=r?su[i].type:"binary",a=o.getUint8(t),n=0;a&128?n=1:a&64?n=2:a&32?n=3:a&16?n=4:a&8?n=5:a&4?n=6:a&2?n=7:a&1&&(n=8);let u=new DataView(o.buffer,o.byteOffset+t+1,n-1),l=a&255>>n,d=or(u),c=l*2**((n-1)*8)+d,h=t+n,p;return h+c>o.byteLength?p=new DataView(o.buffer,o.byteOffset+h):p=new DataView(o.buffer,o.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},or=(o,e=o.byteLength)=>{switch(e){case 1:return o.getUint8(0);case 2:return o.getUint16(0);case 3:return o.getUint8(0)*2**16+o.getUint16(1);case 4:return o.getUint32(0);case 5:return o.getUint8(0)*2**32+o.getUint32(1);case 6:return o.getUint16(0)*2**32+o.getUint32(2);case 7:{let t=o.getUint8(0)*281474976710656+o.getUint16(1)*4294967296+o.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Oe=(o,e)=>{switch(e){case"int":return o.getInt8(0);case"uint":return or(o);case"float":return o.byteLength===4?o.getFloat32(0):o.getFloat64(0);case"string":return new TextDecoder("ascii").decode(o);case"utf8":return new TextDecoder("utf-8").decode(o);case"date":return new Date(Date.UTC(2001,0)+o.getInt8(0)).getTime();case"master":return o;case"binary":return o;default:$d(e)}},Mt=(o,e)=>{let t=0;for(;t<o.byteLength;){let i=new DataView(o.buffer,o.byteOffset+t),r=au(i);if(!e(r))return;r.type==="master"&&Mt(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},nu=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=au(o);return Mt(r.value,({tag:s,type:a,value:n})=>(s===17143?e=Oe(n,a):s===17026?t=Oe(n,a):s===17029&&(i=Oe(n,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var uu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Rd=[231,22612,22743,167,171,163,160,175],Dd=o=>{let e,t,i,r,s=!1,a=!1,n=!1,u,l,d=!1,c=0;return Mt(o,({tag:h,type:p,value:m,valueSize:f})=>{if(h===21419){let b=Oe(m,p);l=or(b)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+f):h===357149030?s=!0:h===290298740?a=!0:h===2807729?i=Oe(m,p):h===17545?r=Oe(m,p):h===21420&&l===475249515?u=Oe(m,p):h===374648427?Mt(m,({tag:b,type:S,value:x})=>b===30321?(d=Oe(x,S)===1,!1):!0):s&&a&&uu.includes(h)&&(n=!0),!n}),Na(e,"Failed to parse webm Segment start"),Na(t,"Failed to parse webm Segment end"),Na(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Bd=o=>{if(Md(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Vd=(o,e)=>{let t=!1,i=!1,r=n=>ou(n.time)&&ou(n.position),s=[],a;return Mt(o,({tag:n,type:u,value:l})=>{switch(n){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=Oe(l,u));break;case 183:break;case 241:a&&(a.position=Oe(l,u));break;default:t&&uu.includes(n)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((n,u)=>{let{time:l,position:d}=n,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Cd=o=>{let e=0,t=!1;try{Mt(o,i=>i.tag===524531317?i.tagSize<=o.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Rd.includes(i.tag)?(e+i.tagSize<=o.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=o.byteLength&&t?new DataView(o.buffer,o.byteOffset,e):null},lu={validateData:nu,parseInit:Dd,getIndexRange:Bd,parseSegments:Vd,parseFeedableSegmentChunk:Cd};var Ye=o=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(o);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return lu;case"mp4":return ru}}throw new ReferenceError(`Unsupported mime type ${o}`)};var Ke=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var Ua=o=>{let e=o.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(),n=s+a;return["6E","7A","F4"].includes(n)}}return!1};import{isNonNullable as Fd,isNullable as hu}from"@vkontakte/videoplayer-shared/evergreen";var cu=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var du=o=>{try{let e=Od(),t=o.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let n=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(n||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(n=>n!==""),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(n=>{let u=a[n];(typeof u>"u"||u==="")&&delete a[n]}),a}return null}catch{return null}};function Od(){let o="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
116
|
+
`}),x};var ue=o=>new URL(o).hostname;import{assertNever as Wo,assertNonNullable as qo,combine as ld,debounce as cd,ErrorCategory as Go,filter as Yo,filterChanged as dd,isNonNullable as Oa,map as Ts,merge as Ko,observableFrom as hd,once as pd,Subscription as md,ValueSubject as Fa,videoQualityToHeight as Xo,videoSizeToQuality as fd}from"@vkontakte/videoplayer-shared/evergreen";var Uo=o=>{if(o instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(o.message))throw o;return!(o instanceof DOMException&&(o.code===20||o.name==="AbortError"))},Ie=async(o,e)=>{let t=o.muted;try{await o.play()}catch(i){if(!Uo(i))return!1;if(e&&e(),t)return console.warn(i),!1;o.muted=!0;try{await o.play()}catch(r){return Uo(r)&&(o.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as vs,isNullable as zc,assertNonNullable as Ri}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Ho,assertNonNullable as Ss,now as Qc}from"@vkontakte/videoplayer-shared/evergreen";function re(){return Qc()}function Da(o){return re()-o}function Ba(o){let e=o.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,n,u=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let l=a.indexOf("?")>-1?"&":"?";return u&&(a+=l+"lowLat=1",l="&"),n&&(a+=l+"_rnd="+Math.floor(999999999*Math.random())),a}}}function Qo(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function Zt(o,e,t,i){let r=window.XMLHttpRequest,s,a,n,u=!1,l=0,d,c,h=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(u)return;Ss(d);let y=Da(d),T;if(y<f){T=f-y,setTimeout(b,T);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,P()},g=y=>(s=y,M),x=y=>(c=y,M),S=()=>(p="json",M),I=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},E=y=>(h=y,M),P=()=>{d=re(),a=new r,a.open("get",o);let y=0,T,w=0,K=()=>(Ss(d),Math.max(d,Math.max(T||0,w||0)));if(s&&a.addEventListener("progress",R=>{let N=re();s.updateChunk&&R.loaded>y&&(s.updateChunk(K(),R.loaded-y),y=R.loaded,T=N)}),n&&(a.timeout=n,a.addEventListener("timeout",()=>I())),a.addEventListener("load",()=>{if(u)return;Ss(a);let R=a.status;if(R>=200&&R<300){let{response:N,responseType:G}=a,Z=N?.byteLength;if(typeof Z=="number"&&s){let te=Z-y;te&&s.updateChunk&&s.updateChunk(K(),te)}G==="json"&&(!N||!Object.values(N).length)?I():(c&&c(),e(N))}else I()}),a.addEventListener("error",()=>{I()}),h){let R=()=>{Ss(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(w=re(),a.removeEventListener("readystatechange",R))};a.addEventListener("readystatechange",R)}return a.responseType=p,a.send(),M},M={withBitrateReporting:g,withParallel:E,withJSONResponse:S,withRetryCount:y=>(l=y,M),withRetryInterval:(y,T)=>(Ho(y)&&(f=y),Ho(T)&&(m=T),M),withTimeout:y=>(n=y,M),withFinally:x,send:P,abort:()=>{a&&(a.abort(),a=void 0),u=!0,c&&c()}};return M}var $i=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,n=s.end-s.start;i+=a;let u=s.bytes*a/n;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 Mi=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=re(),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=re()-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()},n=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zt(t,s,()=>r("error"),n),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=re()}_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=re();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 n=this.pendingQueue.indexOf(e);n!==-1&&this.pendingQueue.splice(n,1),this.logger(`Request not prefetched, starting new request, url=${e}${n===-1?"":"; removed pending"}`),this._sendRequest(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 Wc}from"@vkontakte/videoplayer-shared/evergreen";var ys=1e4,Va=3;var qc=6e4,Gc=10,Yc=1,Kc=500,Di=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 Wc,this.chunkRateEstimator=new $i(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ba(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=Ba(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*(V.display.pixelRatio||1)*t.offsetHeight||520;for(let n=0;n<this.manifest.length;++n){s=this.manifest[n];let{max:u,min:l}=this.autoQualityLimits||{};!Mo({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||vs(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=()=>{Qo(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 Mi(Va,ys,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,n=null,u=null,l=null,d=!1,c=()=>{let I=s&&(!d||d===this.rep);return I||t("Not running!"),I},h=(I,E,P)=>{u&&u.abort(),u=Zt(this.urlResolver.resolve(I,!1),E,P,()=>this._retryCallback()).withTimeout(ys).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Va).withFinally(()=>{u=null}).send()},p=(I,E,P)=>{Ri(this.filesFetcher),n?.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,P,()=>this._retryCallback()).withFinally(()=>{n=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 P=re()-1e4,B=0;for(let $=0;$<this.bufferStates.length;$++){let v=this.bufferStates[$];I=Math.min(I,v.buf),v.ts<P&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${I} drop=${B} jitter=${this.sourceJitter}`);let k=I-Yc;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)}},g=I=>{let E,P=()=>E&&E.start?E.start.length:0,B=R=>E.start[R]/1e3,k=R=>E.dur[R]/1e3,$=R=>E.fragIndex+R,v=(R,N)=>({chunkIdx:$(R),startTS:B(R),dur:k(R),discontinuity:N}),M=()=>{let R=0;if(E&&E.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=N;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let te=E.dur.length-1;for(;te>=0&&(Z-=E.dur[te],!(Z<=0));--te);R=Math.min(te,E.dur.length-1-G),R=Math.max(R,0)}return v(R,!0)},y=R=>{let N=P();if(!(N<=0)){if(vs(R)){for(let G=0;G<N;G++)if(B(G)>R)return v(G)}return M()}},T=R=>{let N=P(),G=R?R.chunkIdx+1:0,Z=G-E.fragIndex;if(!(N<=0)){if(!R||Z<0||Z-N>Gc)return t(`Resync: offset=${Z} bChunks=${N} chunk=`+JSON.stringify(R)),M();if(!(Z>=N))return v(G-E.fragIndex,!1)}},w=(R,N,G)=>{l&&l.abort(),l=Zt(this.urlResolver.resolve(R,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(ys).withRetryCount(Va).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,N)=>{w(I,G=>{if(!c())return;E=G;let Z=!!E.lowLatency;Z!==this.lowLatency&&f(Z);let te=0;for(let ne=0;ne<E.dur.length;++ne)te+=E.dur[ne];te>0&&(Ri(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/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,R(y(N))},()=>this._handleNetworkError())},nextChunk:T}},x=()=>{s=!1,n&&n.abort(),u&&u.abort(),l&&l.abort(),Ri(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:E,logger:P}=this.params,B=g(e.jidxUrl),k,$,v,M,y=0,T,w,K,R=()=>{T&&(clearTimeout(T),T=void 0);let F=Math.max(Kc,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=y+F,he=re(),ie=Math.min(1e4,be-he);y=he;let $e=()=>{l||c()&&B.seek(()=>{c()&&(y=re(),N(),R())})};ie>0?T=window.setTimeout(()=>{this.paused?R():$e()},ie):$e()},N=()=>{let F;for(;F=B.nextChunk(M);)M=F,oe(F);let be=B.nextChunk(v);if(be){if(v&&be.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?R():(x(),this._initPlayerWith(e));return}ne(be)}else R()},G=(F,be)=>{if(!c()||!this.sourceBuffer)return;let he,ie,$e,ut=Ue=>{window.setTimeout(()=>{c()&&G(F,be)},Ue)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),ut(100);else{let Ue=re(),ke=E.currentTime;!this.paused&&E.buffered.length>1&&w===ke&&Ue-K>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),w!==ke&&(w=ke,K=Ue);let lt=this._getBufferSizeSec();if(lt>30)P(`Buffered ${lt} seconds; delaying appendBuffer`),ut(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:Ue,buf:lt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(He){if(He.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),$e=this.sourceBuffer.buffered.length,$e!==0&&(he=this.sourceBuffer.buffered.start(0),ie=ke,ie-he>4&&this.sourceBuffer.remove(he,ie-3)),ut(1e3);else throw He}}},Z=()=>{$&&k&&(P([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(v)]),G($,function(){$=null,N()}))},te=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),ne=F=>{c()&&p(te(F),(be,he)=>{if(c()){if(he/=1e3,$=be,v=F,a=F.startTS,he){let ie=Math.min(10,F.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ie:ie}Z()}},()=>this._handleNetworkError())},oe=F=>{c()&&(Ri(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(F),!1)))},H=F=>{c()&&(e.cachedHeader=F,G(F,()=>{k=!0,Z()}))};s=!0,B.seek(F=>{if(c()){if(y=re(),!F){R();return}M=F,!zc(I)||F.startTS>I?ne(F):(v=F,N())}},I),e.cachedHeader?H(e.cachedHeader):h(e.headerUrl,H,()=>this._handleNetworkError())},stop:x,getTimestampSec:()=>a},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),vs(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,Ri(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return vs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),m=c/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(h,p)=>{let m=re();if(this.chunkRateEstimator.addInterval(h,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:b}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},a=-1/0,n,u=!0,l=()=>{let c=s.get();if(c&&n&&this.autoQuality){if(u&&c>n&&Da(a)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=s.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=re();c<n&&(a=h),n=c}}}_fetchManifest(e,t,i){this.manifestRequest=Zt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ys).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;Ie(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 n=[];return a?.length?(a.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,n.push(u))}),n.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),n):(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))},qc))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Xc,filter as jo,fromEvent as Jc,interval as Zc,isHigher as ed,isInvariantQuality as td,isLower as id,merge as rd,Subject as zo,Subscription as sd}from"@vkontakte/videoplayer-shared/evergreen";var Ca=class{constructor(){this.onDroopedVideoFramesLimit$=new zo;this.subscription=new sd;this.playing=!1;this.tracks=[];this.forceChecker$=new zo;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!td(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,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&&ed(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(Jc(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Zc(this.droppedFramesChecker.checkTime).pipe(jo(()=>this.playing),jo(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Xc(this.droppedFramesChecker.checkTime)),i=rd(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>id(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ei=Ca;import{map as ad,Observable as nd}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as od}from"@vkontakte/videoplayer-shared/evergreen";var Bi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var ud=(o,e)=>new nd(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,n)=>{a.forEach(u=>t.next(u.isIntersecting||Bi()))},{...i,...e});r.observe(o);let s=od(document,"visibilitychange").pipe(ad(a=>!document.hidden||Bi())).subscribe(a=>t.next(a));return()=>{r.unobserve(o),s.unsubscribe()}}),Be=ud;var bd=["paused","playing","ready"],gd=["paused","playing","ready"],Vi=class{constructor(e){this.subscription=new md;this.videoState=new O("stopped");this.representations$=new Fa([]);this.droppedFramesManager=new ei;this.maxSeekBackTime$=new Fa(1/0);this.zeroTime$=new Fa(void 0);this.liveOffset=new Pt;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:Go.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=mt(r.name)??fd(r.video),n=r.bitrate/1e3,u={...r.video};if(!a)continue;let l={id:s,quality:a,bitrate:n,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),Oa(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(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(gd.includes(e)&&(a||n)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&bd.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(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(ee(this.params.source.url,u))}return;default:return Wo(e)}};this.textTracksManager=new De(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Go.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Ko(this.videoState.stateChangeStarted$.pipe(Ts(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ts(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Se(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(ue(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=Te(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Ts(r=>r.map(({track:s})=>s)),Yo(r=>!!r.length),pd()).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(dd(),Ts(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(ld({zeroTime:this.zeroTime$.pipe(Yo(Oa)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(ye(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Re(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Xo(r),min:s&&Xo(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 Wo(r.to)}},t)).add(Ko(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,hd(["init"])).pipe(cd(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),ve(this.video)}createLiveDashPlayer(){let e=new Di({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&&Oa(t)?t:Ge(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(),n=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==n)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),a||u||s!==n){let l=e.find(({track:d})=>d.id===s)?.representation;qo(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;qo(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(ee(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var Jo=Vi;var se=(o,e)=>{let t=0;for(let i=0;i<o.length;i++){let r=o.start(i)*1e3,s=o.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as Sh,assertNonNullable as vh,debounce as yh,ErrorCategory as Bu,filter as nn,filterChanged as Qs,fromEvent as Th,isNonNullable as Vu,isNullable as Ih,map as on,merge as js,observableFrom as un,once as Cu,Subscription as Eh}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Ci}from"@vkontakte/videoplayer-shared/evergreen";var Is=o=>{if(!o)return{id:"EmptyResponse",category:Ci.PARSER,message:"Empty response"};if(o.length<=2&&o.match(/^\d+$/))return{id:`UVError#${o}`,category:Ci.NETWORK,message:`UV Error ${o}`};let e=o.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ci.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(o,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ci.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ci.PARSER,message:"Response is valid XML, but parser failed"}};var le=(o,e,t=0)=>{for(let i=0;i<o.length;i++)if(o.start(i)*1e3-t<=e&&o.end(i)*1e3+t>e)return!0;return!1};import{abortable as Xa,assertNonNullable as ui,combine as li,ErrorCategory as _e,filter as Vs,filterChanged as pr,flattenObject as mr,fromEvent as nt,getTraceSubscriptionMethod as eh,interval as Ja,isNonNullable as fr,isNullable as Lu,map as ci,merge as Dt,now as Za,Subject as Cs,Subscription as Pu,tap as th,throttle as ih,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Sd,ErrorCategory as Zo,Subject as eu}from"@vkontakte/videoplayer-shared/evergreen";var vd=18,tu=!1;try{tu=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=vd}catch(o){console.error(o)}var _a=class{constructor(e){this.bufferFull$=new eu;this.error$=new eu;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:Zo.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)};tu&&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:Zo.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:Sd(t)}}},iu=_a;var ti=o=>{let e=0;for(let t=0;t<o.length;t++)e+=o.end(t)-o.start(t);return e*1e3};import{abortable as gt,assertNonNullable as Ee,ErrorCategory as rt,fromEvent as za,getExponentialDelay as Wa,isNonNullable as ai,isNullable as ce,now as xs,once as Hd,Subject as Qd,Subscription as jd,ValueSubject as Rt}from"@vkontakte/videoplayer-shared/evergreen";var Q=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 Q{};var Oi=class extends Q{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],n=JSON.parse(a);this.serverDataReceivedTimestamp=n[this.ondemandDataReceivedKey],this.serverDataPreparedTime=n[this.ondemandDataPreparedKey]}};var Fi=class extends Q{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 _i=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Y=class extends Q{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ni=class extends Y{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 Ui=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hi=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var $t=class extends Y{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,n=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:n,SAPType:u,SAPDeltaTime:l})}}};var Qi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ji=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zi=class extends Y{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 Wi=class extends Y{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var qi=class extends Y{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Gi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yi=class extends Y{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 Ki=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ji=class extends Y{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var er=class extends Y{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 tr=class extends Y{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 ir=class extends Y{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 rr=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sr=class extends Y{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 ar=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Td={ftyp:Fi,moov:_i,mvhd:Ni,moof:Ui,mdat:Hi,sidx:$t,trak:Qi,mdia:Gi,mfhd:Ji,tkhd:Yi,traf:Zi,tfhd:er,tfdt:tr,trun:ir,minf:Ki,sv3d:ji,st3d:zi,prhd:Wi,proj:Xi,equi:qi,uuid:Oi,stbl:rr,stsd:sr,avc1:ar,unknown:ii},it=class o{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=Td[e];return i?new i(t,new o):new ii(t,new o)}};var bt=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 Ed=new TextDecoder("ascii"),xd=o=>Ed.decode(new DataView(o.buffer,o.byteOffset+4,4))==="ftyp",kd=o=>{let e=new $t(o,new it),t=e.earliestPresentationTime/e.timescale*1e3,i=o.byteOffset+o.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,n={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,n})},wd=(o,e)=>{let i=new it().parse(o),r=new bt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let n=s[0],u=a[a.length-1],l=n.source.byteOffset,c=u.source.byteOffset-n.source.byteOffset+u.size;return new DataView(o.buffer,l,c)},Ad=o=>{let t=new it().parse(o),i=new bt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},Ld=o=>{let t=new it().parse(o);return new bt(t).find("sidx")?.timescale},Pd=(o,e)=>{let i=new it().parse(o),s=new bt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),n=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,h)=>c+h,0):l=a.defaultSampleDuration*u.sampleCount,(Number(n.baseMediaDecodeTime)+l)/e*1e3},$d=o=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new it().parse(o),r=new bt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let n=r.find("prhd");n&&(e.projectionData.pose.yaw=n.poseYawDegrees,e.projectionData.pose.pitch=n.posePitchDegrees,e.projectionData.pose.roll=n.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ru={validateData:xd,parseInit:$d,getIndexRange:()=>{},parseSegments:kd,parseFeedableSegmentChunk:wd,getChunkEndTime:Pd,getServerLatencyTimestamps:Ad,getTimescaleFromIndex:Ld};import{assertNonNullable as Na,isNonNullable as ou,isNullable as Rd}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Md}from"@vkontakte/videoplayer-shared/evergreen";var su={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"}},au=o=>{let e=o.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=or(o,t),r=i in su,s=r?su[i].type:"binary",a=o.getUint8(t),n=0;a&128?n=1:a&64?n=2:a&32?n=3:a&16?n=4:a&8?n=5:a&4?n=6:a&2?n=7:a&1&&(n=8);let u=new DataView(o.buffer,o.byteOffset+t+1,n-1),l=a&255>>n,d=or(u),c=l*2**((n-1)*8)+d,h=t+n,p;return h+c>o.byteLength?p=new DataView(o.buffer,o.byteOffset+h):p=new DataView(o.buffer,o.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},or=(o,e=o.byteLength)=>{switch(e){case 1:return o.getUint8(0);case 2:return o.getUint16(0);case 3:return o.getUint8(0)*2**16+o.getUint16(1);case 4:return o.getUint32(0);case 5:return o.getUint8(0)*2**32+o.getUint32(1);case 6:return o.getUint16(0)*2**32+o.getUint32(2);case 7:{let t=o.getUint8(0)*281474976710656+o.getUint16(1)*4294967296+o.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Oe=(o,e)=>{switch(e){case"int":return o.getInt8(0);case"uint":return or(o);case"float":return o.byteLength===4?o.getFloat32(0):o.getFloat64(0);case"string":return new TextDecoder("ascii").decode(o);case"utf8":return new TextDecoder("utf-8").decode(o);case"date":return new Date(Date.UTC(2001,0)+o.getInt8(0)).getTime();case"master":return o;case"binary":return o;default:Md(e)}},Mt=(o,e)=>{let t=0;for(;t<o.byteLength;){let i=new DataView(o.buffer,o.byteOffset+t),r=au(i);if(!e(r))return;r.type==="master"&&Mt(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},nu=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=au(o);return Mt(r.value,({tag:s,type:a,value:n})=>(s===17143?e=Oe(n,a):s===17026?t=Oe(n,a):s===17029&&(i=Oe(n,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var uu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Dd=[231,22612,22743,167,171,163,160,175],Bd=o=>{let e,t,i,r,s=!1,a=!1,n=!1,u,l,d=!1,c=0;return Mt(o,({tag:h,type:p,value:m,valueSize:f})=>{if(h===21419){let b=Oe(m,p);l=or(b)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+f):h===357149030?s=!0:h===290298740?a=!0:h===2807729?i=Oe(m,p):h===17545?r=Oe(m,p):h===21420&&l===475249515?u=Oe(m,p):h===374648427?Mt(m,({tag:b,type:g,value:x})=>b===30321?(d=Oe(x,g)===1,!1):!0):s&&a&&uu.includes(h)&&(n=!0),!n}),Na(e,"Failed to parse webm Segment start"),Na(t,"Failed to parse webm Segment end"),Na(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Vd=o=>{if(Rd(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Cd=(o,e)=>{let t=!1,i=!1,r=n=>ou(n.time)&&ou(n.position),s=[],a;return Mt(o,({tag:n,type:u,value:l})=>{switch(n){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=Oe(l,u));break;case 183:break;case 241:a&&(a.position=Oe(l,u));break;default:t&&uu.includes(n)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((n,u)=>{let{time:l,position:d}=n,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Od=o=>{let e=0,t=!1;try{Mt(o,i=>i.tag===524531317?i.tagSize<=o.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Dd.includes(i.tag)?(e+i.tagSize<=o.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=o.byteLength&&t?new DataView(o.buffer,o.byteOffset,e):null},lu={validateData:nu,parseInit:Bd,getIndexRange:Vd,parseSegments:Cd,parseFeedableSegmentChunk:Od};var Ye=o=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(o);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return lu;case"mp4":return ru}}throw new ReferenceError(`Unsupported mime type ${o}`)};var Ke=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var Ua=o=>{let e=o.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(),n=s+a;return["6E","7A","F4"].includes(n)}}return!1};import{isNonNullable as _d,isNullable as hu}from"@vkontakte/videoplayer-shared/evergreen";var cu=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var du=o=>{try{let e=Fd(),t=o.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let n=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(n||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(n=>n!==""),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(n=>{let u=a[n];(typeof u>"u"||u==="")&&delete a[n]}),a}return null}catch{return null}};function Fd(){let o="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
117
117
|
(?<language>${`(?:[a-z]{2,3}(?:-${o})?|[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(d,"i")}var pu=o=>{if(!o?.startsWith("P"))return;let e=(a,n)=>{let u=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(u)?0:u)*n},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(o),r=i?.[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},Fe=(o,e)=>{let t=o;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(n,u)=>hu(s)?n:hu(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Es=(o,e)=>{let i=new DOMParser().parseFromString(o,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map($=>$.textContent?.trim()??""),n=a.at(0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],h=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=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:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let S,x=s.getAttribute("mediaPresentationDuration"),g=[...s.getElementsByTagName("Period")],I=g.reduce(($,v)=>({...$,[v.id]:v.children}),{}),E=g.reduce(($,v)=>({...$,[v.id]:v.getAttribute("duration")}),{});x?S=pu(x):Object.values(E).filter($=>$).length&&!u?S=Object.values(E).reduce(($,v)=>$+(pu(v)??0),0):f&&(S=parseInt(f,10));let P=0,B=s.getAttribute("profiles")?.split(",")??[];for(let $ of g.map(v=>v.id))for(let v of I[$]){let M=v.getAttribute("id")??"id"+(P++).toString(10),y=v.getAttribute("mimeType")??"",T=v.getAttribute("codecs")??"",w=v.getAttribute("contentType")??y?.split("/")[0],K=v.getAttribute("profiles")?.split(",")??[],R=du(v.getAttribute("lang")??"")??{},N=v.querySelector("Label")?.textContent?.trim()??void 0,G=v.querySelectorAll("Representation"),Z=v.querySelector("SegmentTemplate"),te=v.querySelector("Role")?.getAttribute("value")??void 0,ne=w,oe={id:M,language:R.language,isDefault:te==="main",label:N,codecs:T,hdr:ne==="video"&&Ua(T),mime:y,representations:[]};for(let H of G){let F=H.getAttribute("lang")??void 0,be=N??v.getAttribute("label")??H.getAttribute("label")??void 0,he=H.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(he||n,e).toString(),$e=H.getAttribute("mimeType")??y,ut=H.getAttribute("codecs")??T??"",Ue;if(w==="text"){let ke=H.getAttribute("id")||"",lt=R.privateuse?.includes("x-auto")||ke.includes("_auto"),He=H.querySelector("SegmentTemplate");if(He){let Si={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Or=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Fr=parseInt(He.getAttribute("startNumber")??"",10)??1,Nt=parseInt(He.getAttribute("timescale")??"",10),fa=He.querySelectorAll("SegmentTimeline S")??[],Ut=He.getAttribute("media");if(!Ut)continue;let _r=[],Nr=0,Ur="",Ht=0,vi=Fr,pe=0;for(let Ve of fa){let xt=parseInt(Ve.getAttribute("d")??"",10),Me=parseInt(Ve.getAttribute("r")??"",10)||0,ct=parseInt(Ve.getAttribute("t")??"",10);pe=Number.isFinite(ct)?ct:pe;let kt=xt/Nt*1e3,Qt=pe/Nt*1e3;for(let Qe=0;Qe<Me+1;Qe++){let dt=Fe(Ut,{...Si,segmentNumber:vi.toString(10),segmentTime:(pe+Qe*xt).toString(10)}),jt=(Qt??0)+Qe*kt,Ti=jt+kt;vi++,_r.push({time:{from:jt,to:Ti},url:dt})}pe+=(Me+1)*xt,Nr+=(Me+1)*kt}Ht=pe/Nt*1e3,Ur=Fe(Ut,{...Si,segmentNumber:vi.toString(10),segmentTime:pe.toString(10)});let yi={time:{from:Ht,to:1/0},url:Ur},Je={type:"template",baseUrl:ie,segmentTemplateUrl:Ut,initUrl:"",totalSegmentsDurationMs:Nr,segments:_r,nextSegmentBeyondManifest:yi,timescale:Nt};Ue={id:ke,kind:"text",segmentReference:Je,profiles:[],duration:S,bitrate:Or,mime:"",codecs:"",width:0,height:0,isAuto:lt}}else Ue={id:ke,isAuto:lt,kind:"text",url:ie}}else{let ke=H.getAttribute("contentType")??$e?.split("/")[0]??w,lt=v.getAttribute("profiles")?.split(",")??[],He=parseInt(H.getAttribute("width")??"",10),Si=parseInt(H.getAttribute("height")??"",10),Or=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Fr=H.getAttribute("frameRate")??"",Nt=H.getAttribute("quality")??void 0,fa=Fr?cu(Fr):void 0,Ut=H.getAttribute("id")??"id"+(P++).toString(10),_r=ke==="video"?`${Si}p`:ke==="audio"?`${Or}Kbps`:ut,Nr=`${Ut}@${_r}`,Ur=[...B,...K,...lt],Ht,vi=H.querySelector("SegmentBase"),pe=H.querySelector("SegmentTemplate")??Z;if(vi){let Je=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ve,xt]=Je.split("-").map(dt=>parseInt(dt,10)),Me={from:Ve,to:xt},ct=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[kt,Qt]=ct?ct.split("-").map(dt=>parseInt(dt,10)):[],Qe=ct?{from:kt,to:Qt}:void 0;Ht={type:"byteRange",url:ie,initRange:Me,indexRange:Qe}}else if(pe){let Je={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ve=parseInt(pe.getAttribute("timescale")??"",10),xt=pe.getAttribute("initialization")??"",Me=pe.getAttribute("media"),ct=parseInt(pe.getAttribute("startNumber")??"",10)??1,kt=Fe(xt,Je);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let Qt=pe.querySelectorAll("SegmentTimeline S")??[],Qe=[],dt=0,jt="",Ti=0;if(Qt.length){let Hr=ct,Ce=0;for(let zt of Qt){let je=parseInt(zt.getAttribute("d")??"",10),wt=parseInt(zt.getAttribute("r")??"",10)||0,Qr=parseInt(zt.getAttribute("t")??"",10);Ce=Number.isFinite(Qr)?Qr:Ce;let ba=je/Ve*1e3,Gl=Ce/Ve*1e3;for(let jr=0;jr<wt+1;jr++){let Yl=Fe(Me,{...Je,segmentNumber:Hr.toString(10),segmentTime:(Ce+jr*je).toString(10)}),Wn=(Gl??0)+jr*ba,Kl=Wn+ba;Hr++,Qe.push({time:{from:Wn,to:Kl},url:Yl})}Ce+=(wt+1)*je,dt+=(wt+1)*ba}Ti=Ce/Ve*1e3,jt=Fe(Me,{...Je,segmentNumber:Hr.toString(10),segmentTime:Ce.toString(10)})}else if(Fd(S)){let Ce=parseInt(pe.getAttribute("duration")??"",10)/Ve*1e3,zt=Math.ceil(S/Ce),je=0;for(let wt=1;wt<zt;wt++){let Qr=Fe(Me,{...Je,segmentNumber:wt.toString(10),segmentTime:je.toString(10)});Qe.push({time:{from:je,to:je+Ce},url:Qr}),je+=Ce}Ti=je,jt=Fe(Me,{...Je,segmentNumber:zt.toString(10),segmentTime:je.toString(10)})}let ql={time:{from:Ti,to:1/0},url:jt};Ht={type:"template",baseUrl:ie,segmentTemplateUrl:Me,initUrl:kt,totalSegmentsDurationMs:dt,segments:Qe,nextSegmentBeyondManifest:ql,timescale:Ve}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!$e)continue;let yi={video:"video",audio:"audio",text:"text"}[ke];if(!yi)continue;ne||=yi,Ue={id:Nr,kind:yi,segmentReference:Ht,profiles:Ur,duration:S,bitrate:Or,mime:$e,codecs:ut,width:He,height:Si,fps:fa,quality:Nt}}oe.language||=F,oe.label||=be,oe.mime||=$e,oe.codecs||=ut,oe.hdr||=ne==="video"&&Ua(ut),oe.representations.push(Ue)}if(ne){let H=r[ne].find(F=>F.id===oe.id);if(H&&oe.representations.every(F=>F.segmentReference.type==="template"))for(let F of H.representations){let he=oe.representations.find($e=>$e.id===F.id)?.segmentReference,ie=F.segmentReference;ie.segments.push(...he.segments),ie.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[ne].push(oe)}}return{duration:S,streams:r,baseUrls:a,live:b}};import{videoSizeToQuality as _d}from"@vkontakte/videoplayer-shared/evergreen";var mu=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?mt(s):void 0)??_d({width:e,height:t});return n&&{id:o,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},fu=({id:o,bitrate:e})=>({id:o,bitrate:e}),bu=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),gu=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),Ha=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Qa=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),ja=o=>"url"in o,Ae=o=>o.type==="template";import{isNonNullable as Su}from"@vkontakte/videoplayer-shared/evergreen";var D=(o,e)=>Su(o)&&Su(e)&&o.readyState==="open"&&Nd(o,e);function Nd(o,e){for(let t=0;t<o.activeSourceBuffers.length;++t)if(o.activeSourceBuffers[t]===e)return!0;return!1}var ur=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Rt(0);this.currentLowLatencySegmentLength$=new Rt(0);this.currentSegmentLength$=new Rt(0);this.onLastSegment$=new Rt(!1);this.fullyBuffered$=new Rt(!1);this.playingRepresentation$=new Rt(void 0);this.playingRepresentationInit$=new Rt(void 0);this.error$=new Hd;this.gaps=[];this.subscription=new Qd;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=gt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ee(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new iu(this.sourceBuffer),this.subscription.add(za(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let n,u=this.mediaSource.readyState;u!=="open"&&(n={id:`SegmentEjection_source_${u}`,category:rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),n??={id:"SegmentEjection",category:rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(n)})),this.subscription.add(za(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:rt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!D(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(n),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,l<d).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);Ee(i,"No init buffer for starting representation"),Ee(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=gt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ee(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ee(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();ai(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=gt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ee(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ee(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();ai(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=gt(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(h=>h.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!Ae(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ee(r);let s=this.segments.get(i);Ee(s,"No segments for starting representation");let a=this.initData.get(i);if(Ee(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.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=n,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ee(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(ce(n)||ce(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),Ee(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ai(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(){!ce(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(ce(e)||ce(this.downloadingRepresentationId)||ce(this.playingRepresentationId)||ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||ai(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ee(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ai(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 d=this.getForwardBufferDuration(e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&ti(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))d="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).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;ai(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||!Ae(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,u=r?.findIndex(l=>n>=l.time.from+s&&n<=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;Ee(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return console.log("segments",this.kind,e),console.log(this.kind,e?.at(-1)?.time),e?.at(-1)?.time.to||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ae(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=Fe(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:h,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,S=p>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&p<=i+x||r<x&&m-p>=x||m<=i+x;return(h==="none"||h==="partially_ejected"&&S&&g&&this.sourceBuffer&&D(this.mediaSource,this.sourceBuffer)&&!(le(this.sourceBuffer.buffered,p)&&le(this.sourceBuffer.buffered,m)))&&S&&g});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<a.length&&(n<=d||u<=c);h++){let p=a[h];if(n+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ae(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:n,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await gt(n,async function*(){let d=Wa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=xs(),!d)return;let c=new DataView(d),h=Ye(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(c);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ke(d)||(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())Ae(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:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await gt(a,async function*(){let u=Wa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),za(window,"online").pipe(Ud()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:n,signal:a,priority:i}),this.lastDataObtainedTimestampMs=xs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ke(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(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(n,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xs(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(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,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xs();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:rt.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||!D(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:u}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),d=Ye(a.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",n.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),n.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await a();continue}let d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,m=c<=r;if(!p)continue;let f=Ye(n.mime);if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,h);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(h,r-d),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===h?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===h&&this.onSegmentFullyAppended(u,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer))){!this.isLive&&V.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(le(this.sourceBuffer.buffered,e.segment.time.from,100)&&le(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:rt.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",ja(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?gt(this.destroyAbortController.signal,async function*(){let n=Wa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ye(e.mime),r)).then(async n=>{if(!n)return;let{init:u,dataView:l,segments:d}=n,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Ae(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:rt.WTF,message:"loadInit threw",thrown:n})});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||!D(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ce(e))return!1;let r=[],s=0,a=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},n=u=>{if(s>=t)return r;r.push({...u.time}),r=a(r);let l=ja(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 d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&n(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};n(h)}}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 d of l)d.time.from>=e+u&&d.status==="fed"&&n(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!D(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||!D(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||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ce(e)?0:se(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!D(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,n=this.sourceBuffer.buffered.end(s)*1e3;if(!(n<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&n>=i.time.to){r=void 0;break}n>i.time.from&&n<i.time.to&&(r.from=n),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||!D(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:rt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||ce(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),n=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=a&&d.to+t>=n),l=e.filter(d=>a>=d.from&&a<d.to-t||n>d.from+t&&n<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:rt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var St=o=>{let e=new URL(o);return e.searchParams.set("quic","1"),e.toString()};var ks=o=>{let e=o.get("X-Delivery-Type"),t=o.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 lr,assertNever as vu,fromEvent as yu,merge as jd,now as cr,Subscription as zd,Subject as Tu,ValueSubject as qa,flattenObject as ni,ErrorCategory as dr}from"@vkontakte/videoplayer-shared/evergreen";var ws=o=>{let e=new URL(o);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Ls=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new qa(void 0);this.lastConnectionReused$=new qa(void 0);this.lastRequestFirstBytes$=new qa(void 0);this.recoverableError$=new Tu;this.error$=new Tu;this.abortAllController=new AbortController;this.subscription=new zd;this.fetchManifest=lr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=St(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ws(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(As);return r?(t.log("success",ni({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ni({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=lr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let M=new URL(l,location.href);M.searchParams.append("bytes",`${i.from}-${i.to}`),l=M.toString();break}default:vu(t)}this.requestQuic&&(l=St(l));let h=this.abortAllController.signal,p;if(a){let M=new AbortController;if(p=jd(yu(this.abortAllController.signal,"abort"),yu(a,"abort")).subscribe(()=>{try{M.abort()}catch(y){As(y)}}),this.subscription.add(p),this.abortAllController.signal.aborted||a.aborted)try{M.abort()}catch(y){As(y)}h=M.signal}let m=cr();c.log("startRequest",ni({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:d,signal:h}),b=cr();if(!f)return c.error("error",{message:"No response in request"}),c.end(),p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){p?.unsubscribe();let M=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:M}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!n){p?.unsubscribe();let M=cr(),y={requestStartedAt:m,requestEndedAt:M,duration:M-m};return c.log("endRequest",ni(y)),c.end(),f.arrayBuffer()}let[S,x]=f.body.tee(),g=S.getReader();n&&this.throughputEstimator?.trackStream(x,u);let I=0,E=new Uint8Array(0),P=!1,B=M=>{p?.unsubscribe(),P=!0,As(M)},k=lr(h,async function*({done:M,value:y}){if(I===0&&this.lastRequestFirstBytes$.next(cr()-m),h.aborted){p?.unsubscribe();return}if(!M&&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 g?.read().then(k,B)}}.bind(this));yield g?.read().then(k,B),p?.unsubscribe();let $=cr(),v={failed:P,requestStartedAt:m,requestEndedAt:$,duration:$-m};return P?(c.error("endRequest",ni(v)),c.end(),null):(c.log("endRequest",ni(v)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=lr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),n=Math.max(d,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-a,s-a+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=e.indexRange??t.getIndexRange(p);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,p,m);return{init:p,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=lr(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}=ks(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:vu(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:dr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:dr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:dr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:dr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:dr.FATAL})}}},As=o=>{if(!Ke(o))throw o};var st=(o,e,t)=>t*e+(1-t)*o,Ga=(o,e)=>o.reduce((t,i)=>t+i,0)/e,Iu=(o,e,t,i)=>{let r=0,s=t,a=Ga(o,e),n=e<i?e:i;for(let u=0;u<n;u++)o[s]>a?r++:r--,s=(o.length+s-1)%o.length;return Math.abs(r)===n};import{isNullable as Wd,ValueSubject as Eu}from"@vkontakte/videoplayer-shared/evergreen";var vt=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 Eu(e.initial),this.debounced$=new Eu(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new fe(`raw_${t}`),this.smoothedSeries$=new fe(`smoothed_${t}`),this.reportedSeries$=new fe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let n=0;n<this.pastMeasures.length;n++)this.pastMeasures[n]!==void 0&&(t+=(this.pastMeasures[n]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),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)&&(Wd(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 Ps=class extends vt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=st(this.slow,e,this.params.emaAlphaSlow),this.fast=st(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var $s=class extends vt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ga(this.pastMeasures,this.takenMeasures);this.emaSmoothed=st(this.emaSmoothed,e,this.params.emaAlpha);let i=Iu(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ms=class extends vt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?st(this.smoothed,t,this.params.emaAlpha):t}};var at=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ps({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new $s({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 Ms({initial:e,label:"liveEdgeDelay",...t})}};var oi=(o,e)=>{o&&o.playbackRate!==e&&(o.playbackRate=e)};import{isNullable as qd,ValueSubject as Gd}from"@vkontakte/videoplayer-shared/evergreen";var hr=class o{constructor(e,t){this.currentRepresentation$=new Gd(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(!qd(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,n=r.segments[s-1].time.to;if(e<a||e>n)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=o.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=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ae(t.segmentReference))}};import{assertNever as Ds}from"@vkontakte/videoplayer-shared/evergreen";var xu=(o,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:a}=V.video,n=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return o.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&n;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&&n||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&n;case"DASH_LIVE_CMAF":return u&&i.mp4&&n&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&n;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 Ds(l)}})},Rs=o=>{let{webmDecodingInfo:e}=V.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(o){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:Ds(o)}return[t,i]},ku=({webmCodec:o,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Rs(o),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(V.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",...Rs(o),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Rs(o),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Rs(o),...r,"HLS","HLS_ONDEMAND"];default:Ds(e)}return V.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},wu=({androidPreferredFormat:o,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],n,u=V.device.isMac&&V.browser.isSafari;if(V.device.isAndroid)switch(o){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=s;break}case"hls":case"mpeg":{n=a;break}default:Ds(o)}else V.video.nativeHlsSupported&&!u?n=a:u?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=s;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},Ya=o=>o?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Bs=o=>{if(o.size===0)return;if(o.size===1)return o.values().next().value.split(".").at(0);for(let t of o){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return o.values().next().value.split(".").at(0)};var ih=["timeupdate","progress","play","seeked","stalled","waiting"],rh=["timeupdate","progress","loadeddata","playing","seeked"];var Os=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Pu;this.representationSubscription=new Pu;this.state$=new O("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new Cs;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new Cs;this.fetcherError$=new Cs;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Cs;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Xa(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(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:_e.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Xa(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:_e.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=Es(e??"",this.manifestUrlString)}catch(a){let n=Is(e)??{id:"ManifestParsing",category:_e.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(n)}if(!t)return null;let i=(a,n,u)=>!!(this.element?.canPlayType?.(n)&&we()?.isTypeSupported?.(`${n}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:n,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((n-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:h})=>i(a,c,h)),l=new Set(u.map(({codecs:c})=>c)),d=Bs(l);if(d&&(r[a]=u.filter(({codecs:c})=>c.startsWith(d))),a==="video"){let c=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),p=r.video.some(m=>!m.hdr);V.display.isHDR&&c&&h?r.video=r.video.filter(m=>m.hdr):p&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",mr(s)),s}.bind(this));this.initRepresentations=Xa(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",mr({initialVideo:e,initialAudio:t,sourceHls:i})),ui(this.manifest),ui(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(nt(h,"error").pipe(Vs(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:_e.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?es():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Gt())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}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},n=this.manifest.streams.video.reduce((h,p)=>[...h,...p.representations],[]);if(this.videoBufferManager=new ur("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],fr(t)){let h=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new ur("audio",this.source,h,a),this.bufferManagers.push(this.audioBufferManager)}hr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new hr(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(Dt(...rh.map(h=>nt(this.element,h))).pipe(ci(h=>this.element?se(this.element.buffered,this.element.currentTime*1e3):0),pr(),eh(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Dt(nt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(pr()).subscribe(p=>this.liveStreamEndTimestamp=Za())),this.subscription.add(nt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Ja(1e3).subscribe(p=>{let m=ht(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(nt(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(li({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ci(({isActiveLive:p,isLowLatency:m})=>p&&m),pr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||oi(this.element,1)})),this.representationSubscription.add(li({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Vs(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(li({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Vs(({isLive:p})=>p),pr((p,m)=>m.bufferLength<p.bufferLength),ci(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=ht(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(li({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,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,g=p-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(g)>S&&(I=1+Math.sign(g)*x),oi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){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 h=0;this.representationSubscription.add(li({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(th(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=ht(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),g=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let k="none";if(P?k="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&E<x?k="live_forward_buffering":E<x+I&&(k="live_with_target_offset"),isFinite(p)&&(h=p>h?p:h),k==="live_forward_buffering"||k==="live_with_target_offset"){let $=h-(x+g),v=this.normolizeLiveOffset(Math.trunc(b+$/f)),M=Math.abs(v-b),y=0;!p||M<=this.tuning.dashCmafLive.offsetCalculationError?y=b:v>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(y=v),this.manifestUrlString=ee(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(h=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:_e.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Dt(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(ci(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=Dt(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(ci(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),c=li({allBuffersFull:l,someBufferEnded:d}).pipe(pr(),ci(({allBuffersFull:h,someBufferEnded:p})=>h&&p),Vs(h=>h));if(this.representationSubscription.add(Dt(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:_e.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Dt(...this.bufferManagers.map(h=>h.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 h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{h&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:_e.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),p()},{once:!0})})}if(!this.isLive$.getValue()){let h=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Ae(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&fr(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=Ja(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:_e.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 Ls({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=at.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){ui(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Za()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(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(){ui(this.element),this.state$.setState("running"),this.subscription.add(Dt(...ih.map(e=>nt(this.element,e)),nt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:_e.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(nt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(nt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&le(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=Za(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=u<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(p=>{this.error$.next({id:"stallIntervalCallback",category:_e.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:p})}),i.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),i.position=h}this.tracer.log("stallIntervalCallback",mr(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Ja(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:_e.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){ui(this.element),ui(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),le(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Lu(this.element)||Lu(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",mr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){fr(this.element)&&fr(this.source)&&fr(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=Zd(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 n of this.bufferManagers)for(let u of n.gaps)n.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 n=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,i={...i,gapEnds:s,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",mr(i)))}}calculateDurationFromSegments(){try{return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}catch(e){console.log("player",e)}}};var Fs=class{constructor(e,t){this.fov=e,this.orientation=t}};var _s=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 Mu=`attribute vec2 a_vertex;
|
|
123
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var pu=o=>{if(!o?.startsWith("P"))return;let e=(a,n)=>{let u=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(u)?0:u)*n},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(o),r=i?.[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},Fe=(o,e)=>{let t=o;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(n,u)=>hu(s)?n:hu(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Es=(o,e)=>{let i=new DOMParser().parseFromString(o,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map($=>$.textContent?.trim()??""),n=a.at(0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],h=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=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:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let g,x=s.getAttribute("mediaPresentationDuration"),S=[...s.getElementsByTagName("Period")],I=S.reduce(($,v)=>({...$,[v.id]:v.children}),{}),E=S.reduce(($,v)=>({...$,[v.id]:v.getAttribute("duration")}),{});x?g=pu(x):Object.values(E).filter($=>$).length&&!u?g=Object.values(E).reduce(($,v)=>$+(pu(v)??0),0):f&&(g=parseInt(f,10));let P=0,B=s.getAttribute("profiles")?.split(",")??[];for(let $ of S.map(v=>v.id))for(let v of I[$]){let M=v.getAttribute("id")??"id"+(P++).toString(10),y=v.getAttribute("mimeType")??"",T=v.getAttribute("codecs")??"",w=v.getAttribute("contentType")??y?.split("/")[0],K=v.getAttribute("profiles")?.split(",")??[],R=du(v.getAttribute("lang")??"")??{},N=v.querySelector("Label")?.textContent?.trim()??void 0,G=v.querySelectorAll("Representation"),Z=v.querySelector("SegmentTemplate"),te=v.querySelector("Role")?.getAttribute("value")??void 0,ne=w,oe={id:M,language:R.language,isDefault:te==="main",label:N,codecs:T,hdr:ne==="video"&&Ua(T),mime:y,representations:[]};for(let H of G){let F=H.getAttribute("lang")??void 0,be=N??v.getAttribute("label")??H.getAttribute("label")??void 0,he=H.querySelector("BaseURL")?.textContent?.trim()??"",ie=new URL(he||n,e).toString(),$e=H.getAttribute("mimeType")??y,ut=H.getAttribute("codecs")??T??"",Ue;if(w==="text"){let ke=H.getAttribute("id")||"",lt=R.privateuse?.includes("x-auto")||ke.includes("_auto"),He=H.querySelector("SegmentTemplate");if(He){let Si={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Or=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Fr=parseInt(He.getAttribute("startNumber")??"",10)??1,Nt=parseInt(He.getAttribute("timescale")??"",10),fa=He.querySelectorAll("SegmentTimeline S")??[],Ut=He.getAttribute("media");if(!Ut)continue;let _r=[],Nr=0,Ur="",Ht=0,vi=Fr,pe=0;for(let Ve of fa){let xt=parseInt(Ve.getAttribute("d")??"",10),Me=parseInt(Ve.getAttribute("r")??"",10)||0,ct=parseInt(Ve.getAttribute("t")??"",10);pe=Number.isFinite(ct)?ct:pe;let kt=xt/Nt*1e3,Qt=pe/Nt*1e3;for(let Qe=0;Qe<Me+1;Qe++){let dt=Fe(Ut,{...Si,segmentNumber:vi.toString(10),segmentTime:(pe+Qe*xt).toString(10)}),jt=(Qt??0)+Qe*kt,Ti=jt+kt;vi++,_r.push({time:{from:jt,to:Ti},url:dt})}pe+=(Me+1)*xt,Nr+=(Me+1)*kt}Ht=pe/Nt*1e3,Ur=Fe(Ut,{...Si,segmentNumber:vi.toString(10),segmentTime:pe.toString(10)});let yi={time:{from:Ht,to:1/0},url:Ur},Je={type:"template",baseUrl:ie,segmentTemplateUrl:Ut,initUrl:"",totalSegmentsDurationMs:Nr,segments:_r,nextSegmentBeyondManifest:yi,timescale:Nt};Ue={id:ke,kind:"text",segmentReference:Je,profiles:[],duration:g,bitrate:Or,mime:"",codecs:"",width:0,height:0,isAuto:lt}}else Ue={id:ke,isAuto:lt,kind:"text",url:ie}}else{let ke=H.getAttribute("contentType")??$e?.split("/")[0]??w,lt=v.getAttribute("profiles")?.split(",")??[],He=parseInt(H.getAttribute("width")??"",10),Si=parseInt(H.getAttribute("height")??"",10),Or=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Fr=H.getAttribute("frameRate")??"",Nt=H.getAttribute("quality")??void 0,fa=Fr?cu(Fr):void 0,Ut=H.getAttribute("id")??"id"+(P++).toString(10),_r=ke==="video"?`${Si}p`:ke==="audio"?`${Or}Kbps`:ut,Nr=`${Ut}@${_r}`,Ur=[...B,...K,...lt],Ht,vi=H.querySelector("SegmentBase"),pe=H.querySelector("SegmentTemplate")??Z;if(vi){let Je=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ve,xt]=Je.split("-").map(dt=>parseInt(dt,10)),Me={from:Ve,to:xt},ct=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[kt,Qt]=ct?ct.split("-").map(dt=>parseInt(dt,10)):[],Qe=ct?{from:kt,to:Qt}:void 0;Ht={type:"byteRange",url:ie,initRange:Me,indexRange:Qe}}else if(pe){let Je={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ve=parseInt(pe.getAttribute("timescale")??"",10),xt=pe.getAttribute("initialization")??"",Me=pe.getAttribute("media"),ct=parseInt(pe.getAttribute("startNumber")??"",10)??1,kt=Fe(xt,Je);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let Qt=pe.querySelectorAll("SegmentTimeline S")??[],Qe=[],dt=0,jt="",Ti=0;if(Qt.length){let Hr=ct,Ce=0;for(let zt of Qt){let je=parseInt(zt.getAttribute("d")??"",10),wt=parseInt(zt.getAttribute("r")??"",10)||0,Qr=parseInt(zt.getAttribute("t")??"",10);Ce=Number.isFinite(Qr)?Qr:Ce;let ba=je/Ve*1e3,Gl=Ce/Ve*1e3;for(let jr=0;jr<wt+1;jr++){let Yl=Fe(Me,{...Je,segmentNumber:Hr.toString(10),segmentTime:(Ce+jr*je).toString(10)}),Wn=(Gl??0)+jr*ba,Kl=Wn+ba;Hr++,Qe.push({time:{from:Wn,to:Kl},url:Yl})}Ce+=(wt+1)*je,dt+=(wt+1)*ba}Ti=Ce/Ve*1e3,jt=Fe(Me,{...Je,segmentNumber:Hr.toString(10),segmentTime:Ce.toString(10)})}else if(_d(g)){let Ce=parseInt(pe.getAttribute("duration")??"",10)/Ve*1e3,zt=Math.ceil(g/Ce),je=0;for(let wt=1;wt<zt;wt++){let Qr=Fe(Me,{...Je,segmentNumber:wt.toString(10),segmentTime:je.toString(10)});Qe.push({time:{from:je,to:je+Ce},url:Qr}),je+=Ce}Ti=je,jt=Fe(Me,{...Je,segmentNumber:zt.toString(10),segmentTime:je.toString(10)})}let ql={time:{from:Ti,to:1/0},url:jt};Ht={type:"template",baseUrl:ie,segmentTemplateUrl:Me,initUrl:kt,totalSegmentsDurationMs:dt,segments:Qe,nextSegmentBeyondManifest:ql,timescale:Ve}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!$e)continue;let yi={video:"video",audio:"audio",text:"text"}[ke];if(!yi)continue;ne||=yi,Ue={id:Nr,kind:yi,segmentReference:Ht,profiles:Ur,duration:g,bitrate:Or,mime:$e,codecs:ut,width:He,height:Si,fps:fa,quality:Nt}}oe.language||=F,oe.label||=be,oe.mime||=$e,oe.codecs||=ut,oe.hdr||=ne==="video"&&Ua(ut),oe.representations.push(Ue)}if(ne){let H=r[ne].find(F=>F.id===oe.id);if(H&&oe.representations.every(F=>F.segmentReference.type==="template"))for(let F of H.representations){let he=oe.representations.find($e=>$e.id===F.id)?.segmentReference,ie=F.segmentReference;ie.segments.push(...he.segments),ie.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[ne].push(oe)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{videoSizeToQuality as Nd}from"@vkontakte/videoplayer-shared/evergreen";var mu=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?mt(s):void 0)??Nd({width:e,height:t});return n&&{id:o,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},fu=({id:o,bitrate:e})=>({id:o,bitrate:e}),bu=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),gu=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),Ha=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Qa=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),ja=o=>"url"in o,Ae=o=>o.type==="template";import{isNonNullable as Su}from"@vkontakte/videoplayer-shared/evergreen";var D=(o,e)=>Su(o)&&Su(e)&&o.readyState==="open"&&Ud(o,e);function Ud(o,e){for(let t=0;t<o.activeSourceBuffers.length;++t)if(o.activeSourceBuffers[t]===e)return!0;return!1}var ur=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Rt(0);this.currentLowLatencySegmentLength$=new Rt(0);this.currentSegmentLength$=new Rt(0);this.onLastSegment$=new Rt(!1);this.fullyBuffered$=new Rt(!1);this.playingRepresentation$=new Rt(void 0);this.playingRepresentationInit$=new Rt(void 0);this.error$=new Qd;this.gaps=[];this.subscription=new jd;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=gt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ee(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new iu(this.sourceBuffer),this.subscription.add(za(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let n,u=this.mediaSource.readyState;u!=="open"&&(n={id:`SegmentEjection_source_${u}`,category:rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),n??={id:"SegmentEjection",category:rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(n)})),this.subscription.add(za(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:rt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!D(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(n),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,l<d).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);Ee(i,"No init buffer for starting representation"),Ee(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=gt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ee(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ee(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();ai(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=gt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ee(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ee(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();ai(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=gt(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(h=>h.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!Ae(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Ee(r);let s=this.segments.get(i);Ee(s,"No segments for starting representation");let a=this.initData.get(i);if(Ee(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.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=n,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,gt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ee(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(ce(n)||ce(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),Ee(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ai(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(){!ce(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(ce(e)||ce(this.downloadingRepresentationId)||ce(this.playingRepresentationId)||ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||ai(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ee(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ai(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 d=this.getForwardBufferDuration(e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&ti(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))d="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).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;ai(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||!Ae(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,u=r?.findIndex(l=>n>=l.time.from+s&&n<=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;Ee(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){return this.playingRepresentationId&&this.segments.get(this.playingRepresentationId)?.at(-1)?.time.to||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ae(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=Fe(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:h,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=i+x||r<x&&m-p>=x||m<=i+x;return(h==="none"||h==="partially_ejected"&&g&&S&&this.sourceBuffer&&D(this.mediaSource,this.sourceBuffer)&&!(le(this.sourceBuffer.buffered,p)&&le(this.sourceBuffer.buffered,m)))&&g&&S});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<a.length&&(n<=d||u<=c);h++){let p=a[h];if(n+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ae(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:n,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await gt(n,async function*(){let d=Wa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=xs(),!d)return;let c=new DataView(d),h=Ye(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(c);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ke(d)||(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())Ae(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:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await gt(a,async function*(){let u=Wa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),za(window,"online").pipe(Hd()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:n,signal:a,priority:i}),this.lastDataObtainedTimestampMs=xs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ke(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(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(n,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xs(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(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,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xs();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:rt.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||!D(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:u}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),d=Ye(a.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",n.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),n.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await a();continue}let d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,m=c<=r;if(!p)continue;let f=Ye(n.mime);if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+d,h);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(h,r-d),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===h?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer))){!this.isLive&&V.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(le(this.sourceBuffer.buffered,e.segment.time.from,100)&&le(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:rt.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",ja(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?gt(this.destroyAbortController.signal,async function*(){let n=Wa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ye(e.mime),r)).then(async n=>{if(!n)return;let{init:u,dataView:l,segments:d}=n,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Ae(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:rt.WTF,message:"loadInit threw",thrown:n})});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||!D(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ce(e))return!1;let r=[],s=0,a=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},n=u=>{if(s>=t)return r;r.push({...u.time}),r=a(r);let l=ja(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 d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&n(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};n(h)}}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 d of l)d.time.from>=e+u&&d.status==="fed"&&n(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!D(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||!D(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||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ce(e)?0:se(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!D(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,n=this.sourceBuffer.buffered.end(s)*1e3;if(!(n<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&n>=i.time.to){r=void 0;break}n>i.time.from&&n<i.time.to&&(r.from=n),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||!D(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:rt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ce(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||ce(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),n=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=a&&d.to+t>=n),l=e.filter(d=>a>=d.from&&a<d.to-t||n>d.from+t&&n<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:rt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var St=o=>{let e=new URL(o);return e.searchParams.set("quic","1"),e.toString()};var ks=o=>{let e=o.get("X-Delivery-Type"),t=o.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 lr,assertNever as vu,fromEvent as yu,merge as zd,now as cr,Subscription as Wd,Subject as Tu,ValueSubject as qa,flattenObject as ni,ErrorCategory as dr}from"@vkontakte/videoplayer-shared/evergreen";var ws=o=>{let e=new URL(o);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Ls=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new qa(void 0);this.lastConnectionReused$=new qa(void 0);this.lastRequestFirstBytes$=new qa(void 0);this.recoverableError$=new Tu;this.error$=new Tu;this.abortAllController=new AbortController;this.subscription=new Wd;this.fetchManifest=lr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=St(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ws(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(As);return r?(t.log("success",ni({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ni({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=lr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let M=new URL(l,location.href);M.searchParams.append("bytes",`${i.from}-${i.to}`),l=M.toString();break}default:vu(t)}this.requestQuic&&(l=St(l));let h=this.abortAllController.signal,p;if(a){let M=new AbortController;if(p=zd(yu(this.abortAllController.signal,"abort"),yu(a,"abort")).subscribe(()=>{try{M.abort()}catch(y){As(y)}}),this.subscription.add(p),this.abortAllController.signal.aborted||a.aborted)try{M.abort()}catch(y){As(y)}h=M.signal}let m=cr();c.log("startRequest",ni({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:d,signal:h}),b=cr();if(!f)return c.error("error",{message:"No response in request"}),c.end(),p?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){p?.unsubscribe();let M=`Fetch error ${f.status}: ${f.statusText}`;return c.error("error",{message:M}),c.end(),Promise.reject(new Error(`Fetch error ${f.status}: ${f.statusText}`))}if(this.onHeadersReceived(f.headers),!r&&!n){p?.unsubscribe();let M=cr(),y={requestStartedAt:m,requestEndedAt:M,duration:M-m};return c.log("endRequest",ni(y)),c.end(),f.arrayBuffer()}let[g,x]=f.body.tee(),S=g.getReader();n&&this.throughputEstimator?.trackStream(x,u);let I=0,E=new Uint8Array(0),P=!1,B=M=>{p?.unsubscribe(),P=!0,As(M)},k=lr(h,async function*({done:M,value:y}){if(I===0&&this.lastRequestFirstBytes$.next(cr()-m),h.aborted){p?.unsubscribe();return}if(!M&&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 S?.read().then(k,B)}}.bind(this));yield S?.read().then(k,B),p?.unsubscribe();let $=cr(),v={failed:P,requestStartedAt:m,requestEndedAt:$,duration:$-m};return P?(c.error("endRequest",ni(v)),c.end(),null):(c.log("endRequest",ni(v)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=lr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),n=Math.max(d,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-a,s-a+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=e.indexRange??t.getIndexRange(p);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 g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=lr(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}=ks(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:vu(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:dr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:dr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:dr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:dr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:dr.FATAL})}}},As=o=>{if(!Ke(o))throw o};var st=(o,e,t)=>t*e+(1-t)*o,Ga=(o,e)=>o.reduce((t,i)=>t+i,0)/e,Iu=(o,e,t,i)=>{let r=0,s=t,a=Ga(o,e),n=e<i?e:i;for(let u=0;u<n;u++)o[s]>a?r++:r--,s=(o.length+s-1)%o.length;return Math.abs(r)===n};import{isNullable as qd,ValueSubject as Eu}from"@vkontakte/videoplayer-shared/evergreen";var vt=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 Eu(e.initial),this.debounced$=new Eu(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new fe(`raw_${t}`),this.smoothedSeries$=new fe(`smoothed_${t}`),this.reportedSeries$=new fe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let n=0;n<this.pastMeasures.length;n++)this.pastMeasures[n]!==void 0&&(t+=(this.pastMeasures[n]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),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)&&(qd(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 Ps=class extends vt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=st(this.slow,e,this.params.emaAlphaSlow),this.fast=st(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var $s=class extends vt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ga(this.pastMeasures,this.takenMeasures);this.emaSmoothed=st(this.emaSmoothed,e,this.params.emaAlpha);let i=Iu(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ms=class extends vt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?st(this.smoothed,t,this.params.emaAlpha):t}};var at=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ps({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new $s({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 Ms({initial:e,label:"liveEdgeDelay",...t})}};var oi=(o,e)=>{o&&o.playbackRate!==e&&(o.playbackRate=e)};import{isNullable as Gd,ValueSubject as Yd}from"@vkontakte/videoplayer-shared/evergreen";var hr=class o{constructor(e,t){this.currentRepresentation$=new Yd(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(!Gd(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,n=r.segments[s-1].time.to;if(e<a||e>n)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=o.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=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ae(t.segmentReference))}};import{assertNever as Ds}from"@vkontakte/videoplayer-shared/evergreen";var xu=(o,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:a}=V.video,n=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return o.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&n;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&&n||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&n;case"DASH_LIVE_CMAF":return u&&i.mp4&&n&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&n;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 Ds(l)}})},Rs=o=>{let{webmDecodingInfo:e}=V.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(o){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:Ds(o)}return[t,i]},ku=({webmCodec:o,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Rs(o),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(V.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",...Rs(o),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Rs(o),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Rs(o),...r,"HLS","HLS_ONDEMAND"];default:Ds(e)}return V.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},wu=({androidPreferredFormat:o,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],n,u=V.device.isMac&&V.browser.isSafari;if(V.device.isAndroid)switch(o){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{n=s;break}case"hls":case"mpeg":{n=a;break}default:Ds(o)}else V.video.nativeHlsSupported&&!u?n=a:u?n=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:n=s;return t?["WEB_RTC_LIVE",...n]:[...n,"WEB_RTC_LIVE"]},Ya=o=>o?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Bs=o=>{if(o.size===0)return;if(o.size===1)return o.values().next().value.split(".").at(0);for(let t of o){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return o.values().next().value.split(".").at(0)};var rh=["timeupdate","progress","play","seeked","stalled","waiting"],sh=["timeupdate","progress","loadeddata","playing","seeked"];var Os=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Pu;this.representationSubscription=new Pu;this.state$=new O("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new Cs;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new Cs;this.fetcherError$=new Cs;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Cs;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Xa(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(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:_e.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Xa(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:_e.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=Es(e??"",this.manifestUrlString)}catch(a){let n=Is(e)??{id:"ManifestParsing",category:_e.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(n)}if(!t)return null;let i=(a,n,u)=>!!(this.element?.canPlayType?.(n)&&we()?.isTypeSupported?.(`${n}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:n,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((n-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:h})=>i(a,c,h)),l=new Set(u.map(({codecs:c})=>c)),d=Bs(l);if(d&&(r[a]=u.filter(({codecs:c})=>c.startsWith(d))),a==="video"){let c=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),p=r.video.some(m=>!m.hdr);V.display.isHDR&&c&&h?r.video=r.video.filter(m=>m.hdr):p&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",mr(s)),s}.bind(this));this.initRepresentations=Xa(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",mr({initialVideo:e,initialAudio:t,sourceHls:i})),ui(this.manifest),ui(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(nt(h,"error").pipe(Vs(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:_e.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?es():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Gt())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}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},n=this.manifest.streams.video.reduce((h,p)=>[...h,...p.representations],[]);if(this.videoBufferManager=new ur("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],fr(t)){let h=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new ur("audio",this.source,h,a),this.bufferManagers.push(this.audioBufferManager)}hr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new hr(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(Dt(...sh.map(h=>nt(this.element,h))).pipe(ci(h=>this.element?se(this.element.buffered,this.element.currentTime*1e3):0),pr(),th(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Dt(nt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(pr()).subscribe(p=>this.liveStreamEndTimestamp=Za())),this.subscription.add(nt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Ja(1e3).subscribe(p=>{let m=ht(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(nt(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(li({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ci(({isActiveLive:p,isLowLatency:m})=>p&&m),pr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||oi(this.element,1)})),this.representationSubscription.add(li({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Vs(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(li({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Vs(({isLive:p})=>p),pr((p,m)=>m.bufferLength<p.bufferLength),ci(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=ht(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(li({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=p-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(S)>g&&(I=1+Math.sign(S)*x),oi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let h=0;this.representationSubscription.add(li({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ih(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=ht(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let k="none";if(P?k="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&E<x?k="live_forward_buffering":E<x+I&&(k="live_with_target_offset"),isFinite(p)&&(h=p>h?p:h),k==="live_forward_buffering"||k==="live_with_target_offset"){let $=h-(x+S),v=this.normolizeLiveOffset(Math.trunc(b+$/f)),M=Math.abs(v-b),y=0;!p||M<=this.tuning.dashCmafLive.offsetCalculationError?y=b:v>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(y=v),this.manifestUrlString=ee(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(h=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:_e.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Dt(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(ci(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=Dt(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(ci(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),c=li({allBuffersFull:l,someBufferEnded:d}).pipe(pr(),ci(({allBuffersFull:h,someBufferEnded:p})=>h&&p),Vs(h=>h));if(this.representationSubscription.add(Dt(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:_e.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Dt(...this.bufferManagers.map(h=>h.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 h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{h&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:_e.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),p()},{once:!0})})}if(!this.isLive$.getValue()){let h=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Ae(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&fr(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=Ja(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:_e.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 Ls({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=at.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){ui(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Za()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(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(){ui(this.element),this.state$.setState("running"),this.subscription.add(Dt(...rh.map(e=>nt(this.element,e)),nt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:_e.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(nt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(nt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&le(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=Za(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=u<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(p=>{this.error$.next({id:"stallIntervalCallback",category:_e.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:p})}),i.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),i.position=h}this.tracer.log("stallIntervalCallback",mr(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Ja(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:_e.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){ui(this.element),ui(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),le(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Lu(this.element)||Lu(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",mr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){fr(this.element)&&fr(this.source)&&fr(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=eh(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 n of this.bufferManagers)for(let u of n.gaps)n.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 n=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,i={...i,gapEnds:s,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",mr(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Fs=class{constructor(e,t){this.fov=e,this.orientation=t}};var _s=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 Mu=`attribute vec2 a_vertex;
|
|
124
124
|
attribute vec2 a_texel;
|
|
125
125
|
|
|
126
126
|
varying vec2 v_texel;
|
|
@@ -174,6 +174,6 @@ void main(void) {
|
|
|
174
174
|
// sample using new coordinates
|
|
175
175
|
gl_FragColor = texture2D(u_texture, tc);
|
|
176
176
|
}
|
|
177
|
-
`;var di=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 Fs(this.params.fov,this.params.orientation),this.cameraRotationManager=new _s(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(Mu,this.gl.VERTEX_SHADER),i=this.createShader(Ru,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,n=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[s,a,n,u,l,d,c,h]}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 nh,now as br,once as oh,Subscription as uh,ValueSubject as en,isNonNullable as lh,safeStorage as tn,filterChanged as ch}from"@vkontakte/videoplayer-shared/evergreen";var Ns="stalls_manager_metrics",rn="stalls_manager_abr_params",Du="stalls_manager_default_tuning_abr_params",sn=class{constructor(){this.isSeeked$=new en(!1);this.isBuffering$=new en(!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 uh;this.severeStallOccurred$=new en(!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(rn):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=br(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(br()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Du)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(rn),this.setStoredData(Du,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ns,"[]");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((n,u)=>n+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,n)=>a+n.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(Ns,[]),this.setStoredData(rn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:n,stallsMetricsHistoryLength:u}=this.tuning,l=a*Math.min(t/(n*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){return JSON.parse(tn.get(e)??t)}setStoredData(e,t){tn.set(e,JSON.stringify(t))}removeStoredData(e){tn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ns,"[]"),r=t/e,s=i.length?st(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(Ns,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(oh()).subscribe(t=>this.providerStartWatchingTimestamp=br())),this.subscription.add(this.currentStallDuration$.pipe(ch()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(nh(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let n=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=br(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&d-l>=i+n&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,lh(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&br()-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}))}},Us=sn;import{combine as dh,map as hh,observeElementSize as ph,Subscription as mh,ValueSubject as an,noop as fh}from"@vkontakte/videoplayer-shared/evergreen";var Hs=class{constructor(){this.subscription=new mh;this.pipSize$=new an(void 0);this.videoSize$=new an(void 0);this.elementSize$=new an(void 0);this.pictureInPictureWindowRemoveEventListener=fh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(ph(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(dh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(hh(({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 Bt=class{constructor(e){this.subscription=new Ih;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ei;this.stallsManager=new Us;this.elementSizeManager=new Hs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ft;this.audioTrackSwitchHistory=new ft;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"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return gh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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 De(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(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 Os({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;Th(this.observableVideo)&&(this.observableVideo=Te(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Bu.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,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(nn(l=>!!l.length),Cu()).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(on(l=>l.to.state!=="none"),Qs());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(nn(Vu),Cu()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(on(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(ze(this.video,t.isLooped,r)),this.subscription.add(ye(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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 d=this.player.getStreams();if(Sh(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(Ha(p));let m=[];for(let f of p.representations){let b=fu(f);m.push(b),this.audioTracksMap.set(b,{stream:p,representation:f})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(Qa(h));let p=[];for(let m of h.representations){let f=mu({...m,streamId:h.id});f&&(p.push(f),this.videoTracksMap.set(f,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let m=bu(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}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(js(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$,yh(this.video,"progress")).pipe(nn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,m=[...this.videoTracksMap.keys()].find(b=>this.videoTracksMap.get(b)?.representation.id===h.id);Vu(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(h.id,p?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.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(Qs()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Qa(h));let m=this.player.calculateDurationFromSegments();m&&this.params.output.duration$.next(m/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qs()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Ha(h))},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(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 n=t.playbackState.stateChangeStarted$.pipe(on(({to:l})=>l==="ready"),Qs());this.subscription.add(js(n,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,un(["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(js(n,this.player.state$.stateChangeEnded$,un(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=js(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,un(["init"])).pipe(vh(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pi:Li,t=this.params.tuning.useNewAutoSelectVideoTrack?gs:bs,i=this.params.tuning.useNewAutoSelectVideoTrack?Ge:fs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:v})=>v===n),d=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 h=[...this.videoStreamsMap.keys()].find(({id:v})=>v===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let m=se(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),g=[...this.audioStreamsMap.keys()].find(({id:v})=>v===x?.id)??this.audioStreamsMap.keys().next().value,I=0;if(g){if(l&&!a){let v=e(l,p,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,v?.bitrate??-1/0)}if(d){let v=e(d,p,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,v?.bitrate??-1/0)}}let E=i(p,{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:d,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}),P=a?E??l:l??E,B=g&&t(P,p,this.audioStreamsMap.get(g)??[],{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(P)?.representation,$=B&&this.audioTracksMap.get(B)?.representation;if(k&&$)return[k,$];if(k&&!$&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bu.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),ve(this.video),this.tracer.end()}};var gr=class extends Bt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ln,merge as Ou,filter as Fu,filterChanged as Eh,isNullable as cn,map as _u,ValueSubject as dn,isNonNullable as xh}from"@vkontakte/videoplayer-shared/evergreen";var Sr=class extends Bt{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 dn(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(_u(n=>n.to)).subscribe(this.player.isLowLatency$)).add(ln({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_u(({liveBufferTime:n,liveAvailabilityStartTime:u})=>n&&u?n+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Fu(n=>xh(n))).subscribe(n=>t.isLiveEnded$.next(n!=="active"&&t.position$.getValue()===0))).add(ln({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Ou(i.playbackRateState$,new dn(1))}).pipe(Fu(({liveStreamStatus:n,liveDuration:u})=>n==="active"&&!!u)).subscribe(({liveDuration:n,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||cn(l)||(e=n-l)})).add(ln({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Ou(i.playbackRateState$,new dn(1))}).pipe(Eh((n,u)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===u.liveDuration:n.time===u.time)).subscribe(({time:n,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||cn(n)||cn(u))return;let h=-1*(u-n-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let u=gu(n);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 Kh,assertNonNullable as Xh,debounce as Jh,ErrorCategory as il,filter as kn,filterChanged as ea,fromEvent as Zh,isNonNullable as rl,isNullable as ep,map as wn,merge as ta,observableFrom as An,once as sl,Subscription as tp}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as yn,assertNonNullable as mi,combine as fi,ErrorCategory as Ne,filter as Ks,filterChanged as xr,flattenObject as kr,fromEvent as Xe,getTraceSubscriptionMethod as Nh,interval as Tn,isNonNullable as wr,isNullable as el,map as bi,merge as Ft,now as In,Subject as Xs,Subscription as En,tap as Uh,throttle as tl,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as kh,ErrorCategory as Nu,Subject as Uu}from"@vkontakte/videoplayer-shared/evergreen";var wh=18,Hu=!1;try{Hu=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=wh}catch(o){console.error(o)}var hn=class{constructor(e){this.bufferFull$=new Uu;this.error$=new Uu;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:Nu.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)};Hu&&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:Nu.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:kh(t)}}},Qu=hn;import{abortable as yt,assertNonNullable as xe,ErrorCategory as Ct,fromEvent as bn,getExponentialDelay as gn,isNonNullable as hi,isNullable as de,now as qs,once as Mh,Subject as Rh,Subscription as Dh,ValueSubject as Ot}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Ah,throttleFn as Lh}from"@vkontakte/videoplayer-shared/evergreen";var ju=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?mt(s):void 0)??Ah({width:e,height:t});return n&&{id:o,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},zu=({id:o,bitrate:e})=>({id:o,bitrate:e}),Wu=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),qu=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),pn=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),mn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),fn=o=>"url"in o,Le=o=>o.type==="template";var Gu=o=>{o.sort((t,i)=>t.from-i.from);let e=[o[0]];for(let t=1;t<o.length;t++){let{from:i,to:r}=o[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(o[t])}return e},Vt=(o,e)=>{for(let t of o)if(e(t))return t;return null},Yu=o=>{let e=!1,t=Lh(()=>{e=!0},o);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Ph,Subscription as $h}from"@vkontakte/videoplayer-shared/evergreen";var zs=o=>{let e=[];for(let t=0;t<o.length;t++){let i=Math.floor(o.start(t)*1e3),r=Math.ceil(o.end(t)*1e3);e.push(i,r)}return e};var Ws=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new $h;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Ph(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!D(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=zs(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],n=t[i+1];if(a>r||n<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var vr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ot(0);this.currentLowLatencySegmentLength$=new Ot(0);this.currentSegmentLength$=new Ot(0);this.onLastSegment$=new Ot(!1);this.fullyBuffered$=new Ot(!1);this.playingRepresentation$=new Ot(void 0);this.playingRepresentationInit$=new Ot(void 0);this.error$=new Rh;this.gaps=[];this.subscription=new Dh;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=yt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Qu(this.sourceBuffer),this.sourceBufferBufferedDiff=new Ws(this.mediaSource,this.sourceBuffer),this.subscription.add(bn(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(bn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ct.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!D(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=se(this.sourceBuffer.buffered,n),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,l<d).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);xe(i,"No init buffer for starting representation"),xe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();hi(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=yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();hi(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=yt(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(h=>h.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!Le(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);xe(r);let s=this.segments.get(i);xe(s,"No segments for starting representation");let a=this.initData.get(i);if(xe(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.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=n,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,yt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);xe(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(de(n)||de(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),xe(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();hi(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(){!de(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(de(e)||de(this.downloadingRepresentationId)||de(this.playingRepresentationId)||de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||hi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);hi(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 d=se(this.sourceBuffer.buffered,e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&ti(this.sourceBuffer.buffered)>=this.bufferLimit){let d=se(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))d="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&se(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-se(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;hi(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||!Le(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,u=r?.findIndex(l=>n>=l.time.from+s&&n<=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;xe(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(!Le(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=Fe(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:h,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,S=p>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&p<=i+x||r<x&&m-p>=x||m<=i+x;return(h==="none"||h==="partially_ejected"&&S&&g&&this.sourceBuffer&&D(this.mediaSource,this.sourceBuffer)&&!(le(this.sourceBuffer.buffered,p)&&le(this.sourceBuffer.buffered,m)))&&S&&g});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<a.length&&(n<=d||u<=c);h++){let p=a[h];if(n+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Le(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:n,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await yt(n,async function*(){let d=gn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=qs(),!d)return;let c=new DataView(d),h=Ye(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(c);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ke(d)||(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())Le(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:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await yt(a,async function*(){let u=gn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),bn(window,"online").pipe(Mh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:n,signal:a,priority:i}),this.lastDataObtainedTimestampMs=qs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ke(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Le(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(n,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=qs(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Le(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,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=qs();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal: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||!D(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:u}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),d=Ye(a.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",n.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),n.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,m=c<=r;if(p){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+d,h);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(h,r-d),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===h?f:Ye(n.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===h&&this.onSegmentFullyAppended(u,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer))){!this.isLive&&V.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(le(this.sourceBuffer.buffered,e.segment.time.from,100)&&le(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ct.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",fn(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?yt(this.destroyAbortController.signal,async function*(){let n=gn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ye(e.mime),r)).then(n=>{if(!n)return;let{init:u,dataView:l,segments:d}=n,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Le(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ct.WTF,message:"loadInit threw",thrown:n})});return this.initData.set(e.id,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||!D(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||de(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=n=>{if(s>=t)return;r.push({...n.time});let u=fn(n)?n.size??0:n.byte.to-n.byte.from;s+=u};for(let n of this.segments.values())for(let u of n){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&a(u)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let u=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3,d=0;for(let c of this.segments.values())for(let h of c)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};a(c)}}if(r.length&&i){let n=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+n&&l.status==="fed"&&a(l)}return r.length?(r=Gu(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||!D(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||!D(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||!D(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||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||de(e)?0:se(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!D(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),n=Math.round(s.to);for(let u=0;u<i.length;u++)if(a>=Math.round(i.start(u)*1e3)&&n<=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,n=i.end(s)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){r=void 0;break}n>t.time.from&&n<t.time.to&&(r.from=n),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||!D(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:Ct.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||de(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=zs(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),n=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=a&&h+t>=n),(a>=c&&a<h-t||n>c+t&&n<=h)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Ct.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){return this.playingRepresentationId&&this.segments.get(this.playingRepresentationId)?.at(-1)?.time.to||0}};import{abortable as yr,assertNever as Ku,fromEvent as Xu,merge as Bh,now as Tr,Subject as Ju,ValueSubject as Sn,flattenObject as pi,ErrorCategory as Ir,SubscriptionRemovable as Vh}from"@vkontakte/videoplayer-shared/evergreen";var Ys=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Sn(void 0);this.lastConnectionReused$=new Sn(void 0);this.lastRequestFirstBytes$=new Sn(void 0);this.recoverableError$=new Ju;this.error$=new Ju;this.abortAllController=new AbortController;this.subscription=new Vh;this.fetchManifest=yr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=St(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ws(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Gs);return r?(t.log("success",pi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",pi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=yr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.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:Ku(t)}this.requestQuic&&(l=St(l));let h=this.abortAllController.signal,p;if(a){let y=new AbortController;if(p=Bh(Xu(this.abortAllController.signal,"abort"),Xu(a,"abort")).subscribe(()=>{try{y.abort()}catch(T){Gs(T)}}),this.subscription.add(p),this.abortAllController.signal.aborted||a.aborted)try{y.abort()}catch(T){Gs(T)}h=y.signal}let m=Tr();c.log("startRequest",pi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:d,signal:h}),b=Tr();if(!f)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){this.unsubscribeAbortSubscription(p);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&&!n){this.unsubscribeAbortSubscription(p);let y=Tr(),T={requestStartedAt:m,requestEndedAt:y,duration:y-m};return c.log("endRequest",pi(T)),c.end(),f.arrayBuffer()}let S=f.body;if(n){let y;[S,y]=f.body.tee(),this.throughputEstimator?.trackStream(y,u)}let x=S.getReader(),g,I=parseInt(f.headers.get("content-length")??"",10);Number.isFinite(I)&&(g=I),!g&&i&&(g=i.to-i.from+1);let E=0,P=g?new Uint8Array(g):new Uint8Array(0),B=!1,k=y=>{this.unsubscribeAbortSubscription(p),B=!0,Gs(y)},$=yr(h,async function*({done:y,value:T}){if(E===0&&this.lastRequestFirstBytes$.next(Tr()-m),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!y&&T){if(g)P.set(T,E),E+=T.byteLength;else{let w=new Uint8Array(P.length+T.length);w.set(P),w.set(T,P.length),P=w,E+=T.byteLength}r?.(new DataView(P.buffer),E),yield x?.read().then($,k)}}.bind(this));yield x?.read().then($,k),this.unsubscribeAbortSubscription(p);let v=Tr(),M={failed:B,requestStartedAt:m,requestEndedAt:v,duration:v-m};return B?(c.error("endRequest",pi(M)),c.end(),null):(c.log("endRequest",pi(M)),c.end(),P.buffer)}.bind(this));this.fetchByteRangeRepresentation=yr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),n=Math.max(d,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-a,s-a+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=e.indexRange??t.getIndexRange(p);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,p,m);return{init:p,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=yr(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}=ks(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:Ku(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:Ir.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ir.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ir.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ir.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ir.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Gs=o=>{if(!Ke(o))throw o};import{isNullable as Ch,ValueSubject as Oh}from"@vkontakte/videoplayer-shared/evergreen";var Er=class o{constructor(e,t){this.currentRepresentation$=new Oh(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(!Ch(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,n=r.segments[s-1].time.to;if(e<a||e>n)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=o.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=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Le(t.segmentReference))}};var Hh=["progress","play","seeked","stalled","waiting"],Qh=["timeupdate","progress","loadeddata","playing","seeked"];var Js=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new En;this.representationSubscription=new En;this.state$=new O("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new Xs;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new Xs;this.fetcherError$=new Xs;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Xs;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=yn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(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:Ne.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=yn(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:Ne.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=Es(e??"",this.manifestUrlString)}catch(a){let n=Is(e)??{id:"ManifestParsing",category:Ne.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(n)}if(!t)return null;let i=(a,n,u)=>!!(this.element?.canPlayType?.(n)&&we()?.isTypeSupported?.(`${n}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:n,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((n-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:h})=>i(a,c,h)),l=new Set(u.map(({codecs:c})=>c)),d=Bs(l);if(d&&(r[a]=u.filter(({codecs:c})=>c.startsWith(d))),a==="video"){let c=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),p=r.video.some(m=>!m.hdr);V.display.isHDR&&c&&h?r.video=r.video.filter(m=>m.hdr):p&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",kr(s)),s}.bind(this));this.initRepresentations=yn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",kr({initialVideo:e,initialAudio:t,sourceHls:i})),mi(this.manifest),mi(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new En,this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(Xe(h,"error").pipe(Ks(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ne.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?es():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Gt())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}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},n=this.manifest.streams.video.reduce((h,p)=>[...h,...p.representations],[]);if(this.videoBufferManager=new vr("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],wr(t)){let h=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new vr("audio",this.source,h,a),this.bufferManagers.push(this.audioBufferManager)}Er.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Er(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(Ft(...Qh.map(h=>Xe(this.element,h))).pipe(bi(h=>this.element?se(this.element.buffered,this.element.currentTime*1e3):0),xr(),Uh(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ft(Xe(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(xr()).subscribe(p=>this.liveStreamEndTimestamp=In())),this.subscription.add(Xe(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Tn(1e3).subscribe(p=>{let m=ht(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Xe(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(fi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(bi(({isActiveLive:p,isLowLatency:m})=>p&&m),xr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||oi(this.element,1)})),this.representationSubscription.add(fi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ks(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(fi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ks(({isLive:p})=>p),xr((p,m)=>m.bufferLength<p.bufferLength),bi(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=ht(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(fi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,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,g=p-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(g)>S&&(I=1+Math.sign(g)*x),oi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){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 h=0;this.representationSubscription.add(fi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(tl(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=ht(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),g=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let k="none";if(P?k="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&E<x?k="live_forward_buffering":E<x+I&&(k="live_with_target_offset"),isFinite(p)&&(h=p>h?p:h),k==="live_forward_buffering"||k==="live_with_target_offset"){let $=h-(x+g),v=this.normolizeLiveOffset(Math.trunc(b+$/f)),M=Math.abs(v-b),y=0;!p||M<=this.tuning.dashCmafLive.offsetCalculationError?y=b:v>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(y=v),this.manifestUrlString=ee(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(h=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ne.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Ft(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(bi(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=Ft(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(bi(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),c=fi({allBuffersFull:l,someBufferEnded:d}).pipe(xr(),bi(({allBuffersFull:h,someBufferEnded:p})=>h&&p),Ks(h=>h));if(this.representationSubscription.add(Ft(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ft(...this.bufferManagers.map(h=>h.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 h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{h&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Ne.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),p()},{once:!0})})}if(!this.isLive$.getValue()){let h=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Le(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&wr(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=Tn(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ne.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 Ys({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=at.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){mi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?In()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(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(){mi(this.element),this.state$.setState("running");let e=Xe(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(tl(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Ft(...Hh.map(t=>Xe(this.element,t)),Xe(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ne.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Xe(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(Xe(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&le(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=In(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&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 p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:Ne.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",kr(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Tn(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ne.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){mi(this.element),mi(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),le(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(el(this.element)||el(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",kr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){wr(this.element)&&wr(this.source)&&wr(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=Nh(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,n=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-n<=s&&l.to+n>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",kr({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as jh,map as zh,observeElementSize as Wh,Subscription as qh,ValueSubject as xn,noop as Gh}from"@vkontakte/videoplayer-shared/evergreen";var Zs=class{constructor(){this.subscription=new qh;this.pipSize$=new xn(void 0);this.videoSize$=new xn(void 0);this.elementSize$=new xn(void 0);this.pictureInPictureWindowRemoveEventListener=Gh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Wh(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(jh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(zh(({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 _t=class{constructor(e){this.subscription=new tp;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ei;this.stallsManager=new Us;this.elementSizeManager=new Zs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ft;this.audioTrackSwitchHistory=new ft;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"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return Kh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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 De(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(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 Js({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;ep(this.observableVideo)&&(this.observableVideo=Te(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:il.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,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(kn(c=>!!c.length),sl()).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(wn(c=>c.to.state!=="none"),ea());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(kn(rl),sl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(wn(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(ze(this.video,t.isLooped,r)),this.subscription.add(ye(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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 h=this.player.getStreams();if(Xh(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of h.audio){m.push(pn(f));let b=[];for(let S of f.representations){let x=zu(S);b.push(x),this.audioTracksMap.set(x,{stream:f,representation:S})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let p=[];for(let m of h.video){p.push(mn(m));let f=[];for(let b of m.representations){let S=ju({...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(p);for(let m of h.text)for(let f of m.representations){let b=Wu(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:n}=this.params.tuning.dash,u=n&&Yu(n)||null;this.subscription.add(ta(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$,Zh(this.video,"progress")).pipe(kn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=Vt(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===p.id);rl(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(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.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(ea()).subscribe(c=>{let h=Vt(this.videoTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=h,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(mn(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ea()).subscribe(c=>{let h=Vt(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=h,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(pn(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(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}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(wn(({to:c})=>c==="ready"),ea());this.subscription.add(ta(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,An(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(ta(l,this.player.state$.stateChangeEnded$,An(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=ta(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,An(["init"])).pipe(Jh(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pi:Li,t=this.params.tuning.useNewAutoSelectVideoTrack?gs:bs,i=this.params.tuning.useNewAutoSelectVideoTrack?Ge:fs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,u=Vt(this.videoTracksMap.keys(),k=>k.id===n),l=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Vt(this.videoStreamsMap.keys(),k=>k.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=se(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(p/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&&Vt(this.audioStreamsMap.keys(),k=>k.id===S.id)||this.audioStreamsMap.keys().next().value,g=0;if(x){if(u&&!a){let k=e(u,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,k?.bitrate??-1/0)}if(l){let k=e(l,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,k?.bitrate??-1/0)}}let I=u;(a||!I)&&(I=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:g,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,h,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}),P=this.videoTracksMap.get(I)?.representation,B=E&&this.audioTracksMap.get(E)?.representation;P&&B?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=B):P&&!B&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:il.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),ve(this.video),this.tracer.end()}};var Ar=class extends _t{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Ln,merge as al,filter as nl,filterChanged as ip,isNullable as Pn,map as ol,ValueSubject as $n,isNonNullable as rp}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class extends _t{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 $n(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(ol(n=>n.to)).subscribe(this.player.isLowLatency$)).add(Ln({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ol(({liveBufferTime:n,liveAvailabilityStartTime:u})=>n&&u?n+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(nl(n=>rp(n))).subscribe(n=>t.isLiveEnded$.next(n!=="active"&&t.position$.getValue()===0))).add(Ln({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:al(i.playbackRateState$,new $n(1))}).pipe(nl(({liveStreamStatus:n,liveDuration:u})=>n==="active"&&!!u)).subscribe(({liveDuration:n,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||Pn(l)||(e=n-l)})).add(Ln({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:al(i.playbackRateState$,new $n(1))}).pipe(ip((n,u)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===u.liveDuration:n.time===u.time)).subscribe(({time:n,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Pn(n)||Pn(u))return;let h=-1*(u-n-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let u=qu(n);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 ul="X-Playback-Duration",Mn=async o=>{let e=await fetch(o),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(ul)?parseInt(e.headers.get(ul),10):void 0};import{assertNever as mp,combine as fp,debounce as bp,ErrorCategory as sa,filter as gp,filterChanged as Sp,isNonNullable as dl,isNullable as aa,map as hl,merge as vp,observableFrom as yp,Subscription as Tp,ValueSubject as Dn,VideoQuality as Ip}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as sp,getExponentialDelay as ap}from"@vkontakte/videoplayer-shared/evergreen";var np=o=>{let e=null;if(o.QUALITY&&(e=mt(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=sp({width:t,height:i})}return e??null},op=(o,e)=>{let t=o.split(`
|
|
178
|
-
`),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],n=a.match(/^#EXT-X-STREAM-INF:(.+)/),u=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!n&&!u)){if(n){let l=Object.fromEntries(n[1].split(",").map(b=>b.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=
|
|
179
|
-
`),s=0;for(let a=0;a<r.length;++a){let n=r[a];switch(!0){case n.startsWith("#EXTINF:"):{let u=r[++a],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",n))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case n.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",n));break;case n.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",n));break;case n.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",n));break;case n.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",n);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case n.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",n);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(lp(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:pp.WTF,thrown:t,message:e})}};var Pr=class{constructor(e){this.subscription=new Tp;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Dn([]);this.liveOffset=new Pt;this.manifestStartTime$=new Dn(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(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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||n){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.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"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(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"&&A(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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else r?.to==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return mp(t)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ip.INVARIANT,url:this.params.source.url};let t=(i,r)=>ia(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 ra(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new De(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:sa.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:sa.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(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Dn(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 n=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:sa.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=Te(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.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(ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(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"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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(n=>{n&&this.params.output.availableTextTracks$.next(n)})),this.subscription.add(this.maxSeekBackTime$.pipe(Sp(),hl(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&dl(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ue(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let n=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(fp({startTime:this.manifestStartTime$.pipe(gp(dl)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:u})=>this.params.output.liveTime$.next(n+u*1e3),i)),this.subscription.add(this.manifests$.pipe(hl(n=>n.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let a=vp(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,yp(["init"])).pipe(bp(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),ve(this.video)}prepare(){let e=this.selectManifest();if(aa(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:n,min:u}=t?.to??i??{};for(let[l,d]of[[n,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=ee(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),Mn(a).then(n=>{if(!aa(n))this.maxSeekBackTime$.next(n);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(aa(u)||!isFinite(u))&&fetch(a).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,a).toString();Mn(c).then(h=>{aa(h)||this.maxSeekBackTime$.next(h)})}}).catch(()=>{})}})}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sa.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=ee(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 Ep,debounce as xp,ErrorCategory as Bn,fromEvent as Vn,isNonNullable as kp,isNullable as wp,map as pl,merge as ml,observableFrom as fl,Subscription as Ap,ValueSubject as Lp,VideoQuality as Pp}from"@vkontakte/videoplayer-shared/evergreen";var $r=class{constructor(e){this.subscription=new Ap;this.videoState=new O("stopped");this.manifests$=new Lp([]);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(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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||n){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.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"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Ep(t)}};this.textTracksManager=new De(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Pp.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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ia(ee(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:Bn.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 n=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:Bn.WTF,message:"HlsProvider internal logic error",thrown:n})},r=Te(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.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(pl(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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 n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&kp(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(ue(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=this.params.output.element$.getValue()?.playbackRate;if(c!==h){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n.state==="requested"&&this.seek(n.position)},i))),this.subscription.add(this.manifests$.pipe(pl(n=>n.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!V.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(ml(Vn(n,"addtrack"),Vn(n,"removetrack"),Vn(n,"change"),fl(["init"])).subscribe(()=>{for(let u=0;u<n.length;u++)n[u].mode="hidden"},i))}let a=ml(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fl(["init"])).pipe(xp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){let e=this.selectManifest();if(wp(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[n,u]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(n||""));u&&n&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as $p,assertNonNullable as bl,debounce as Mp,ErrorCategory as gl,isHigherOrEqual as Rp,isLowerOrEqual as Dp,isNonNullable as Bp,merge as Vp,observableFrom as Cp,Subscription as Op,map as Fp}from"@vkontakte/videoplayer-shared/evergreen";var Mr=class{constructor(e){this.subscription=new Op;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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(),n=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(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return $p(e)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let 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=n=>{e.error$.next({id:"MpegProvider",category:gl.WTF,message:"MpegProvider internal logic error",thrown:n})},r=Te(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.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(Fp(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let n=this.params.desiredState.videoTrack.getTransition();if(n&&Bp(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let a=Vp(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Cp(["init"])).pipe(Mp(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),ve(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;bl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];bl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=St(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.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 d=Ge(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(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||Yt(e,a[0].quality,a.at(-1)?.quality)){i();return}let n=e.max?Dp(r,e.max):!0,u=e.min?Rp(r,e.min):!0;n&&u||i(e)}};import{assertNever as vl,debounce as Hp,merge as yl,observableFrom as Qp,Subscription as jp,map as Tl,ValueSubject as zp,ErrorCategory as On,VideoQuality as Wp}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as _p}from"@vkontakte/videoplayer-shared/evergreen";var Sl=["stun:videostun.mycdn.me:80"],Np=1e3,Up=3,Cn=()=>null,na=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=Cn;this.externalStopCallback=Cn;this.externalErrorCallback=Cn;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:Sl}]};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:_p.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),Np)}normalizeOptions(e={}){let t={stunServerList:Sl,maxRetryNumber:Up,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Rr=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new zp(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return vl(e)}};this.subscription=new jp,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Se(e.container,e.tuning),this.liveStreamClient=new na(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),ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:On.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(yl(this.videoState.stateChangeStarted$.pipe(Tl(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Tl(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}));let r=Te(this.video);this.subscription.add(()=>r.destroy());let s=(a,n)=>this.subscription.add(a.subscribe(n,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(Be(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(ye(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 vl(a.to)}},i)).add(yl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Qp(["init"])).pipe(Hp(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(ue(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:Wp.INVARIANT}),this.video.srcObject=e,A(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:On.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:On.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Dr=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 Br,assertNonNullable as Tt,ErrorCategory as oa,filter as Al,isNonNullable as Ll,isNullable as Zp,map as em,merge as tm,once as im,Subject as ae,Subscription as Pl,ValueSubject as _,flattenObject as Fn}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as qp,map as Il,Subscription as Gp,Subject as Yp}from"@vkontakte/videoplayer-shared/evergreen";var El=o=>new qp(e=>{let t=new Gp,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Il(({from:l,to:d})=>`${l}-${d}`)),r=o.desiredPlaybackState$.stateChangeEnded$,s=o.providerChanged$.pipe(Il(({type:l})=>l!==void 0)),a=new Yp,n=0,u="unknown";return t.add(i.subscribe(l=>{n&&window.clearTimeout(n),u=l,n=window.setTimeout(()=>a.next(l),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(n),u="unknown",n=0})),t.add(s.subscribe(l=>{n&&(window.clearTimeout(n),n=0,l&&(n=window.setTimeout(()=>a.next(u),o.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as Kp,Subscription as Xp,combine as Jp,filter as kl,once as wl}from"@vkontakte/videoplayer-shared/evergreen";function xl(){return new(window.AudioContext||window.webkitAudioContext)}var gi=class o{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Xp;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(kl(s=>!!s.type),wl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){V.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(Jp({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(kl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),wl()).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=xl();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:o.errorId,category:Kp.VIDEO_PIPELINE,message:e?.message??`${o.errorId} exception`,thrown:e})}};var rm={chunkDuration:5e3,maxParallelRequests:5},Vr=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new ae;this.noAvailableProvidersError$=new ae;this.volumeMultiplierError$=new ae;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new ae,fetcherError$:new ae,fetcherRecoverableError$:new ae,warning$:new ae,willSeekEvent$:new ae,soundProhibitedEvent$:new ae,seekedEvent$:new ae,loopedEvent$:new ae,endedEvent$:new ae,firstBytesEvent$:new ae,loadedMetadataEvent$:new ae,firstFrameEvent$:new ae,canplay$:new ae,isLive$:new _(void 0),isLiveEnded$:new _(null),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new ae,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new Pl;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=xu([...wu(this.params.tuning),...ku(this.params.tuning)],this.params.tuning).filter(l=>Ll(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",Fn(s)),this.screenFormatsIterator=new Dr(s);let a=[...Ya(!0),...Ya(!1)];this.chromecastFormatsIterator=new Dr(a.filter(l=>Ll(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:n=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&n!==1&&gi.isSupported()&&(this.volumeMultiplierManager=new gi(this.providerOutput,this.current$,this.volumeMultiplierError$,n))}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(Zp(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:oa.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 Br(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,n={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 Tt(u),this.params.tuning.useNewDashProvider?new Ar({...n,source:u,sourceHls:l}):new gr({...n,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Tt(u),this.params.tuning.useNewDashProvider?new Lr({...n,source:u}):new Sr({...n,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Tt(u),new $r({...n,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Tt(u),new Pr({...n,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Tt(u),new Mr({...n,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Tt(u),new Jo({...n,source:u,config:{...rm,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Tt(u),new Rr({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 Br(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return Tt(n),new Ii({connection:n,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 Br(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Br(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 Br(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 Pl,t=!1,i=0;return e.add(tm(this.providerOutput.error$.pipe(Al(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),El({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(em(r=>({id:`ProviderHangup:${r}`,category:oa.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(Al(({to:s})=>s==="playing"),im()).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 n=r.category===oa.NETWORK,u=r.category===oa.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(n&&t||!d);a={...a,isNetworkError:n,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(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",Fn(a)):this.tracer.error("providerError",Fn(a))})),e}};import{fromEvent as ua,once as sm,combine as am,Subscription as $l,ValueSubject as _n,map as nm,filter as om,isNonNullable as la,now as Pe,safeStorage as Nn}from"@vkontakte/videoplayer-shared/evergreen";var um=5e3,Ml="one_video_throughput",Rl="one_video_rtt",Cr=window.navigator.connection,Dl=()=>{let o=Cr?.downlink;if(la(o)&&o!==10)return o*1e3},Bl=()=>{let o=Cr?.rtt;if(la(o)&&o!==3e3)return o},Vl=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},Un=class o{constructor(e){this.subscription=new $l;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=o.load(Ml)||(e.useBrowserEstimation?Dl():void 0)||um,i=o.load(Rl)??(e.useBrowserEstimation?Bl():void 0)??0;if(this.throughput$=new _n(t),this.rtt$=new _n(i),this.rttAdjustedThroughput$=new _n(Vl(t,i,e.rttPenaltyRequestSize)),this.throughput=at.getSmoothedValue(t,-1,e),this.rtt=at.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Dl();a&&this.throughput.next(a);let n=Bl();la(n)&&this.rtt.next(n)};Cr&&"onchange"in Cr&&this.subscription.add(ua(Cr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Nn.set(Ml,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Nn.set(Rl,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(am({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(nm(({throughput:r,rtt:s})=>Vl(r,s,e.rttPenaltyRequestSize)),om(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=Pe(),r=new $l;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(ua(e,"progress").pipe(sm()).subscribe(s=>{t=s.loaded,i=Pe()}));break;case 1:case 0:r.add(ua(e,"loadstart").subscribe(()=>{t=0,i=Pe()}));break}r.add(ua(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,n=Pe(),u=a-t,l=n-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=Pe(),a=0,n=Pe(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,Pe()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=Pe();if(h-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=n-s;m&&this.addRawSpeed(a,m,1,t),a=c.byteLength,s=Pe()}else a+=c.byteLength;n=Pe()}else r+=c.byteLength,a+=c.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Pe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Pe()-n,this.concurrentDownloads.size),a=0,n=Pe());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(o.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=Nn.get(e);if(la(t))return parseInt(t,10)??void 0}},Cl=Un;import{fillWithDefault as lm,VideoQuality as ca}from"@vkontakte/videoplayer-shared/evergreen";var Ol={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:ca.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:ca.Q_720P,trafficSavingLimit:ca.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:ca.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},Fl=o=>({...lm(o,Ol),configName:[...o.configName??[],...Ol.configName]});import{assertNonNullable as da,combine as ot,ErrorCategory as ha,filter as C,filterChanged as z,fromEvent as Qn,isNonNullable as Hl,isNullable as bm,Logger as gm,map as j,mapTo as Ql,merge as It,now as pa,once as U,Subject as W,Subscription as jl,tap as jn,ValueSubject as L,isHigher as Sm,isInvariantQuality as zl,flattenObject as Et,throttle as zn,getTraceSubscriptionMethod as Wl,TracerFactory as vm,InternalsExposure as ym}from"@vkontakte/videoplayer-shared/evergreen";import{merge as cm,map as dm,filter as _l,isNonNullable as hm}from"@vkontakte/videoplayer-shared/evergreen";var Hn=({seekState:o,position$:e})=>cm(o.stateChangeEnded$.pipe(dm(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),_l(hm)),e.pipe(_l(()=>o.getState().state==="none")));import{assertNonNullable as pm}from"@vkontakte/videoplayer-shared/evergreen";var Nl=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return pm(e,`Wrong container or containerId {${o.container}}`),e};import{filter as mm,once as fm}from"@vkontakte/videoplayer-shared/evergreen";var Ul=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(mm(r=>r.length>0),fm()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t?.getValue().find(i))&&e.startTransitionTo(o)};var ma=class{constructor(e={configName:[]},t=vm.createRootTracer(!1)){this.subscription=new jl;this.logger=new gm;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new L(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new L(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new L(void 0),position$:new L(0),duration$:new L(1/0),muted$:new L(!1),volume$:new L(1),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableQualities$:new L([]),availableQualitiesFps$:new L({}),currentQuality$:new L(void 0),isAutoQualityEnabled$:new L(!0),autoQualityLimitingAvailable$:new L(!1),autoQualityLimits$:new L({}),predefinedQualityLimitType$:new L("unknown"),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),isAudioAvailable$:new L(!0),currentPlaybackRate$:new L(1),currentBuffer$:new L({start:0,end:0}),isBuffering$:new L(!0),isStalled$:new L(!1),isEnded$:new L(!1),isLooped$:new L(!1),isLive$:new L(void 0),isLiveEnded$:new L(null),canChangePlaybackSpeed$:new L(void 0),atLiveEdge$:new L(void 0),atLiveDurationEdge$:new L(void 0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),liveLatency$:new L(void 0),currentFormat$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),throughputEstimation$:new L(void 0),rttEstimation$:new L(void 0),videoBitrate$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),surface$:new L("none"),chromecastState$:new L("NOT_AVAILABLE"),chromecastDeviceName$:new L(void 0),intrinsicVideoSize$:new L(void 0),availableSources$:new L(void 0),is3DVideo$:new L(!1),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0)};this.events={inited$:new W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new L(void 0),tuningConfigName$:new L([]),enableDebugTelemetry$:new L(!1),dumpTelemetry:Po,getCurrentTime$:new L(null)};if(this.initLogs(),this.tuning=Fl(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Gr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Cl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new ym("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:(...n)=>{try{return a.apply(i,n)}catch(u){let l=n.map(h=>JSON.stringify(h,(p,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:ha.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",Et(a)),this.domContainer=Nl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Vr({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?V.isInited$.pipe(C(s=>!!s),U()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Qn(document,"visibilitychange").pipe(U()).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(C(e=>!!e),U()).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(C(e=>!!e),U()).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(C(e=>!!e),U()).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(C(e=>!!e),U()).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(C(i=>!!i),U()).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(C(t=>!!t),U()).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(C(i=>!!i),U()).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(C(i=>!!i),U()).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(C(t=>!!t),U()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).subscribe(()=>{da(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(C(i=>i.length>0),U()).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(C(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Et(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).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(C(t=>!!t),U()).subscribe(()=>{da(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(C(t=>!!t),U()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Et(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).subscribe(()=>{Ul(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(C(t=>!!t),U()).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(C(t=>!!t),U()).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(C(i=>!!i),U()).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(C(t=>!!t),U()).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(C(i=>!!i),U()).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(C(e=>e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(bm(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Hl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ra(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(C(({from:e})=>e==="stopped"),U()).subscribe(()=>{this.initedAt=pa(),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",Et(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:ha.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(U()).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",Et(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(j(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(a=>a.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ot({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:a,currentVideoStream:n})=>a.filter(u=>n?n.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>zl(u)?1:zl(l)?-1:Sm(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let n={};for(let u of a)u.fps&&(n[u.quality]=u.fps);this.info.availableQualitiesFps$.next(n)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(C(a=>Hl(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((a,n)=>Math.round(a)===Math.round(n))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((a,n)=>Math.round(a)===Math.round(n))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).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(j(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(jn(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(ot({hasLiveOffsetByPaused:It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(a=>a.to),z(),j(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:n})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(n));return}this.hasLiveOffsetByPaused.next(!1)})).add(ot({atLiveEdge:ot({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Hn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:a,position:n,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return a&&Math.abs(n)<l/1e3}),z(),jn(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:a,hasPausedTimeoutCase:n})=>a&&!n)).subscribe(this.info.atLiveEdge$)).add(ot({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:a,position:n,duration:u})=>a&&(Math.abs(u)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),z(),jn(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(a=>a.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(a=>a.volume),z()).subscribe(this.info.volume$)).add(Hn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(It(e.providerOutput.endedEvent$.pipe(Ql(!0)),e.providerOutput.seekedEvent$.pipe(Ql(!1))).pipe(z()).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(j(a=>({id:a?`No${a}`:"NoProviders",category:ha.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(U(),j(a=>a??pa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(U(),j(()=>pa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(U(),j(()=>pa()-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 L(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new L(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(C(({to:a})=>a==="playing"),U()).subscribe(()=>i.next(!1)));let r=0,s=It(e.providerOutput.isBuffering$,t,i).pipe(j(()=>{let a=e.providerOutput.isBuffering$.getValue(),n=t.getValue()||i.getValue();return a&&!n}),z());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(It(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 n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(It(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?a?c="pip":n?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(j(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new jl;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(C(i=>i.length>0),U()).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=Ge(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(It(this.desiredState.videoTrack.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(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;da(this.providerContainer),da(e),Lo(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ao(t)),this.providerContainer.current$.subscribe(({type:t})=>Ai("provider",t)),e.duration$.subscribe(t=>Ai("duration",t)),e.availableVideoTracks$.pipe(C(t=>!!t.length),U()).subscribe(t=>Ai("tracks",t)),this.events.fatalError$.subscribe(new fe("fatalError")),this.events.managedError$.subscribe(new fe("managedError")),e.position$.subscribe(new fe("position")),e.currentVideoTrack$.pipe(j(t=>t?.quality)).subscribe(new fe("quality")),this.info.currentBuffer$.subscribe(new fe("buffer")),e.isBuffering$.subscribe(new fe("isBuffering"))].forEach(t=>this.subscription.add(t)),Ai("codecs",V.video.supportedCodecs)}initTracerSubscription(){let e=Wl(this.tracer.log.bind(this.tracer)),t=Wl(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(z()).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(ot({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(C(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(C(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(C(i=>i>0),z()).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(ot({currentBuffer:this.info.currentBuffer$.pipe(C(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(zn(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(ot({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(C(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),zn(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),C(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),C(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),C(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ot({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(C(({throughputEstimation:i,rtt:r})=>!!i&&!!r),zn(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),C(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:ha.DOM,message:String(r)})})};this.subscription.add(It(Qn(document,"visibilitychange"),Qn(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",Et({quality:t,availableTracks:Et(e),track:Et(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&&!Bi()}};import{Subscription as KR,Observable as XR,Subject as JR,ValueSubject as ZR,VideoQuality as eD}from"@vkontakte/videoplayer-shared/evergreen";var tD=`@vkontakte/videoplayer-core@${qn}`;export{zr as ChromecastState,ga as HttpConnectionType,XR as Observable,ge as PlaybackState,ma as Player,Wr as PredefinedQualityLimits,tD as SDK_VERSION,JR as Subject,KR as Subscription,Sa as Surface,qn as VERSION,ZR as ValueSubject,Ze as VideoFormat,eD as VideoQuality,V as clientChecker,wi as isMobile};
|
|
177
|
+
`;var di=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 Fs(this.params.fov,this.params.orientation),this.cameraRotationManager=new _s(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(Mu,this.gl.VERTEX_SHADER),i=this.createShader(Ru,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,n=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[s,a,n,u,l,d,c,h]}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 oh,now as br,once as uh,Subscription as lh,ValueSubject as en,isNonNullable as ch,safeStorage as tn,filterChanged as dh}from"@vkontakte/videoplayer-shared/evergreen";var Ns="stalls_manager_metrics",rn="stalls_manager_abr_params",Du="stalls_manager_default_tuning_abr_params",sn=class{constructor(){this.isSeeked$=new en(!1);this.isBuffering$=new en(!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 lh;this.severeStallOccurred$=new en(!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(rn):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=br(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(br()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Du)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(rn),this.setStoredData(Du,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ns,"[]");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((n,u)=>n+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,n)=>a+n.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(Ns,[]),this.setStoredData(rn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:n,stallsMetricsHistoryLength:u}=this.tuning,l=a*Math.min(t/(n*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){return JSON.parse(tn.get(e)??t)}setStoredData(e,t){tn.set(e,JSON.stringify(t))}removeStoredData(e){tn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ns,"[]"),r=t/e,s=i.length?st(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(Ns,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(uh()).subscribe(t=>this.providerStartWatchingTimestamp=br())),this.subscription.add(this.currentStallDuration$.pipe(dh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(oh(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let n=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=br(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&d-l>=i+n&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,ch(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&br()-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}))}},Us=sn;import{combine as hh,map as ph,observeElementSize as mh,Subscription as fh,ValueSubject as an,noop as bh}from"@vkontakte/videoplayer-shared/evergreen";var Hs=class{constructor(){this.subscription=new fh;this.pipSize$=new an(void 0);this.videoSize$=new an(void 0);this.elementSize$=new an(void 0);this.pictureInPictureWindowRemoveEventListener=bh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(mh(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(hh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ph(({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 Bt=class{constructor(e){this.subscription=new Eh;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ei;this.stallsManager=new Us;this.elementSizeManager=new Hs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ft;this.audioTrackSwitchHistory=new ft;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"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return Sh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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 De(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(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 Os({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;Ih(this.observableVideo)&&(this.observableVideo=Te(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Bu.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,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(nn(l=>!!l.length),Cu()).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(on(l=>l.to.state!=="none"),Qs());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(nn(Vu),Cu()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(on(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(ze(this.video,t.isLooped,r)),this.subscription.add(ye(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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 d=this.player.getStreams();if(vh(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(Ha(p));let m=[];for(let f of p.representations){let b=fu(f);m.push(b),this.audioTracksMap.set(b,{stream:p,representation:f})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(Qa(h));let p=[];for(let m of h.representations){let f=mu({...m,streamId:h.id});f&&(p.push(f),this.videoTracksMap.set(f,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let m=bu(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}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(js(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$,Th(this.video,"progress")).pipe(nn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,m=[...this.videoTracksMap.keys()].find(b=>this.videoTracksMap.get(b)?.representation.id===h.id);Vu(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(h.id,p?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.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(Qs()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Qa(h));let m=this.player.calculateDurationFromSegments();m&&this.params.output.duration$.next(m/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qs()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Ha(h))},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(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 n=t.playbackState.stateChangeStarted$.pipe(on(({to:l})=>l==="ready"),Qs());this.subscription.add(js(n,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,un(["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(js(n,this.player.state$.stateChangeEnded$,un(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=js(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,un(["init"])).pipe(yh(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pi:Li,t=this.params.tuning.useNewAutoSelectVideoTrack?gs:bs,i=this.params.tuning.useNewAutoSelectVideoTrack?Ge:fs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:v})=>v===n),d=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 h=[...this.videoStreamsMap.keys()].find(({id:v})=>v===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let m=se(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,g=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),S=[...this.audioStreamsMap.keys()].find(({id:v})=>v===x?.id)??this.audioStreamsMap.keys().next().value,I=0;if(S){if(l&&!a){let v=e(l,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,v?.bitrate??-1/0)}if(d){let v=e(d,p,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,v?.bitrate??-1/0)}}let E=i(p,{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:g,current:d,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}),P=a?E??l:l??E,B=S&&t(P,p,this.audioStreamsMap.get(S)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=this.videoTracksMap.get(P)?.representation,$=B&&this.audioTracksMap.get(B)?.representation;if(k&&$)return[k,$];if(k&&!$&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bu.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),ve(this.video),this.tracer.end()}};var gr=class extends Bt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ln,merge as Ou,filter as Fu,filterChanged as xh,isNullable as cn,map as _u,ValueSubject as dn,isNonNullable as kh}from"@vkontakte/videoplayer-shared/evergreen";var Sr=class extends Bt{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 dn(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(_u(n=>n.to)).subscribe(this.player.isLowLatency$)).add(ln({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_u(({liveBufferTime:n,liveAvailabilityStartTime:u})=>n&&u?n+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Fu(n=>kh(n))).subscribe(n=>t.isLiveEnded$.next(n!=="active"&&t.position$.getValue()===0))).add(ln({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Ou(i.playbackRateState$,new dn(1))}).pipe(Fu(({liveStreamStatus:n,liveDuration:u})=>n==="active"&&!!u)).subscribe(({liveDuration:n,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||cn(l)||(e=n-l)})).add(ln({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Ou(i.playbackRateState$,new dn(1))}).pipe(xh((n,u)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===u.liveDuration:n.time===u.time)).subscribe(({time:n,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||cn(n)||cn(u))return;let h=-1*(u-n-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let u=gu(n);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 Xh,assertNonNullable as Jh,debounce as Zh,ErrorCategory as il,filter as kn,filterChanged as ea,fromEvent as ep,isNonNullable as rl,isNullable as tp,map as wn,merge as ta,observableFrom as An,once as sl,Subscription as ip}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as yn,assertNonNullable as mi,combine as fi,ErrorCategory as Ne,filter as Ks,filterChanged as xr,flattenObject as kr,fromEvent as Xe,getTraceSubscriptionMethod as Uh,interval as Tn,isNonNullable as wr,isNullable as el,map as bi,merge as Ft,now as In,Subject as Xs,Subscription as En,tap as Hh,throttle as tl,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as wh,ErrorCategory as Nu,Subject as Uu}from"@vkontakte/videoplayer-shared/evergreen";var Ah=18,Hu=!1;try{Hu=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=Ah}catch(o){console.error(o)}var hn=class{constructor(e){this.bufferFull$=new Uu;this.error$=new Uu;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:Nu.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)};Hu&&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:Nu.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:wh(t)}}},Qu=hn;import{abortable as yt,assertNonNullable as xe,ErrorCategory as Ct,fromEvent as bn,getExponentialDelay as gn,isNonNullable as hi,isNullable as de,now as qs,once as Rh,Subject as Dh,Subscription as Bh,ValueSubject as Ot}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Lh,throttleFn as Ph}from"@vkontakte/videoplayer-shared/evergreen";var ju=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let n=(s?mt(s):void 0)??Lh({width:e,height:t});return n&&{id:o,quality:n,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},zu=({id:o,bitrate:e})=>({id:o,bitrate:e}),Wu=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),qu=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),pn=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),mn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),fn=o=>"url"in o,Le=o=>o.type==="template";var Gu=o=>{o.sort((t,i)=>t.from-i.from);let e=[o[0]];for(let t=1;t<o.length;t++){let{from:i,to:r}=o[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(o[t])}return e},Vt=(o,e)=>{for(let t of o)if(e(t))return t;return null},Yu=o=>{let e=!1,t=Ph(()=>{e=!0},o);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as $h,Subscription as Mh}from"@vkontakte/videoplayer-shared/evergreen";var zs=o=>{let e=[];for(let t=0;t<o.length;t++){let i=Math.floor(o.start(t)*1e3),r=Math.ceil(o.end(t)*1e3);e.push(i,r)}return e};var Ws=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Mh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add($h(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!D(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=zs(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],n=t[i+1];if(a>r||n<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var vr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:n,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Ot(0);this.currentLowLatencySegmentLength$=new Ot(0);this.currentSegmentLength$=new Ot(0);this.onLastSegment$=new Ot(!1);this.fullyBuffered$=new Ot(!1);this.playingRepresentation$=new Ot(void 0);this.playingRepresentationInit$=new Ot(void 0);this.error$=new Dh;this.gaps=[];this.subscription=new Bh;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=yt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Qu(this.sourceBuffer),this.sourceBufferBufferedDiff=new Ws(this.mediaSource,this.sourceBuffer),this.subscription.add(bn(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(bn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ct.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let n=this.getCurrentPosition();if(!this.sourceBuffer||!n||!D(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ti(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=se(this.sourceBuffer.buffered,n),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(n,a*2,l<d).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);xe(i,"No init buffer for starting representation"),xe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();hi(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=yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!D(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();hi(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=yt(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(h=>h.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!Le(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);xe(r);let s=this.segments.get(i);xe(s,"No segments for starting representation");let a=this.initData.get(i);if(xe(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.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=n,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!D(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,yt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);xe(s,`No such representation ${i}`);let a=this.segments.get(i),n=this.initData.get(i);if(de(n)||de(a)?yield this.loadInit(s,"high",!1):n instanceof Promise&&(yield n),a=this.segments.get(i),xe(a,"No segments for starting representation"),n=this.initData.get(i),!(!(n instanceof ArrayBuffer)||!this.sourceBuffer||!D(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(n,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();hi(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(){!de(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(de(e)||de(this.downloadingRepresentationId)||de(this.playingRepresentationId)||de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||hi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);hi(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 d=se(this.sourceBuffer.buffered,e),c=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+a&&(s=c)}if(isFinite(this.bufferLimit)&&ti(this.sourceBuffer.buffered)>=this.bufferLimit){let d=se(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(u.includes(r))d="high";else{let c=u.at(0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&se(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=i.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-se(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;hi(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||!Le(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],n=a.at(-1)?.time.to??0,u=r?.findIndex(l=>n>=l.time.from+s&&n<=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;xe(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(!Le(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=Fe(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:h,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,x=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=i+x||r<x&&m-p>=x||m<=i+x;return(h==="none"||h==="partially_ejected"&&g&&S&&this.sourceBuffer&&D(this.mediaSource,this.sourceBuffer)&&!(le(this.sourceBuffer.buffered,p)&&le(this.sourceBuffer.buffered,m)))&&g&&S});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,n=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<a.length&&(n<=d||u<=c);h++){let p=a[h];if(n+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Le(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:n,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&n&&(await yt(n,async function*(){let d=gn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),n.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(a,{range:s,signal:n,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=qs(),!d)return;let c=new DataView(d),h=Ye(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,n);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(c);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ke(d)||(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())Le(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:n}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await yt(a,async function*(){let u=gn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),bn(window,"online").pipe(Rh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:n,signal:a,priority:i}),this.lastDataObtainedTimestampMs=qs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ke(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Le(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(n,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=qs(),await this.onSomeByteRangesDataLoaded({dataView:n,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Le(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,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=qs();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal: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||!D(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let n of this.activeSegments){let{segment:u}=n;if(n.representationId===t){if(s.aborted){r();continue}if(n.loadedBytes=i,n.loadedBytes>n.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+n.feedingBytes,n.loadedBytes-n.feedingBytes),d=Ye(a.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",n.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),n.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!D(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,m=c<=r;if(p){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+d,h);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(h,r-d),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===h?f:Ye(n.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===h&&this.onSegmentFullyAppended(u,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer))){!this.isLive&&V.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(le(this.sourceBuffer.buffered,e.segment.time.from,100)&&le(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ct.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",fn(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?yt(this.destroyAbortController.signal,async function*(){let n=gn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ye(e.mime),r)).then(n=>{if(!n)return;let{init:u,dataView:l,segments:d}=n,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Le(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,n=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ct.WTF,message:"loadInit threw",thrown:n})});return this.initData.set(e.id,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||!D(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||de(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=n=>{if(s>=t)return;r.push({...n.time});let u=fn(n)?n.size??0:n.byte.to-n.byte.from;s+=u};for(let n of this.segments.values())for(let u of n){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&a(u)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let u=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3,d=0;for(let c of this.segments.values())for(let h of c)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};a(c)}}if(r.length&&i){let n=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+n&&l.status==="fed"&&a(l)}return r.length?(r=Gu(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||!D(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||!D(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||!D(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||!D(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||de(e)?0:se(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!D(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),n=Math.round(s.to);for(let u=0;u<i.length;u++)if(a>=Math.round(i.start(u)*1e3)&&n<=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,n=i.end(s)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){r=void 0;break}n>t.time.from&&n<t.time.to&&(r.from=n),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||!D(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:Ct.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(de(this.sourceBuffer)||!D(this.mediaSource,this.sourceBuffer)||de(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=zs(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),n=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=a&&h+t>=n),(a>=c&&a<h-t||n>c+t&&n<=h)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Ct.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){return this.playingRepresentationId&&this.segments.get(this.playingRepresentationId)?.at(-1)?.time.to||0}};import{abortable as yr,assertNever as Ku,fromEvent as Xu,merge as Vh,now as Tr,Subject as Ju,ValueSubject as Sn,flattenObject as pi,ErrorCategory as Ir,SubscriptionRemovable as Ch}from"@vkontakte/videoplayer-shared/evergreen";var Ys=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Sn(void 0);this.lastConnectionReused$=new Sn(void 0);this.lastRequestFirstBytes$=new Sn(void 0);this.recoverableError$=new Ju;this.error$=new Ju;this.abortAllController=new AbortController;this.subscription=new Ch;this.fetchManifest=yr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=St(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ws(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Gs);return r?(t.log("success",pi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",pi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=yr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:n=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.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:Ku(t)}this.requestQuic&&(l=St(l));let h=this.abortAllController.signal,p;if(a){let y=new AbortController;if(p=Vh(Xu(this.abortAllController.signal,"abort"),Xu(a,"abort")).subscribe(()=>{try{y.abort()}catch(T){Gs(T)}}),this.subscription.add(p),this.abortAllController.signal.aborted||a.aborted)try{y.abort()}catch(T){Gs(T)}h=y.signal}let m=Tr();c.log("startRequest",pi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let f=yield this.doFetch(l,{priority:s,headers:d,signal:h}),b=Tr();if(!f)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if(this.throughputEstimator?.addRawRtt(b-m),!f.ok||!f.body){this.unsubscribeAbortSubscription(p);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&&!n){this.unsubscribeAbortSubscription(p);let y=Tr(),T={requestStartedAt:m,requestEndedAt:y,duration:y-m};return c.log("endRequest",pi(T)),c.end(),f.arrayBuffer()}let g=f.body;if(n){let y;[g,y]=f.body.tee(),this.throughputEstimator?.trackStream(y,u)}let x=g.getReader(),S,I=parseInt(f.headers.get("content-length")??"",10);Number.isFinite(I)&&(S=I),!S&&i&&(S=i.to-i.from+1);let E=0,P=S?new Uint8Array(S):new Uint8Array(0),B=!1,k=y=>{this.unsubscribeAbortSubscription(p),B=!0,Gs(y)},$=yr(h,async function*({done:y,value:T}){if(E===0&&this.lastRequestFirstBytes$.next(Tr()-m),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!y&&T){if(S)P.set(T,E),E+=T.byteLength;else{let w=new Uint8Array(P.length+T.length);w.set(P),w.set(T,P.length),P=w,E+=T.byteLength}r?.(new DataView(P.buffer),E),yield x?.read().then($,k)}}.bind(this));yield x?.read().then($,k),this.unsubscribeAbortSubscription(p);let v=Tr(),M={failed:B,requestStartedAt:m,requestEndedAt:v,duration:v-m};return B?(c.error("endRequest",pi(M)),c.end(),null):(c.log("endRequest",pi(M)),c.end(),P.buffer)}.bind(this));this.fetchByteRangeRepresentation=yr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,n=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(a=Math.min(l,r),n=Math.max(d,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:n},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-a,s-a+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=e.indexRange??t.getIndexRange(p);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 g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=yr(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}=ks(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:Ku(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:Ir.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ir.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ir.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ir.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ir.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Gs=o=>{if(!Ke(o))throw o};import{isNullable as Oh,ValueSubject as Fh}from"@vkontakte/videoplayer-shared/evergreen";var Er=class o{constructor(e,t){this.currentRepresentation$=new Fh(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(!Oh(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,n=r.segments[s-1].time.to;if(e<a||e>n)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=o.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=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Le(t.segmentReference))}};var Qh=["progress","play","seeked","stalled","waiting"],jh=["timeupdate","progress","loadeddata","playing","seeked"];var Js=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new En;this.representationSubscription=new En;this.state$=new O("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new Xs;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new Xs;this.fetcherError$=new Xs;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Xs;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=yn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(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:Ne.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=yn(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:Ne.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t=null;try{t=Es(e??"",this.manifestUrlString)}catch(a){let n=Is(e)??{id:"ManifestParsing",category:Ne.PARSER,message:"Failed to parse MPD manifest",thrown:a};this.error$.next(n)}if(!t)return null;let i=(a,n,u)=>!!(this.element?.canPlayType?.(n)&&we()?.isTypeSupported?.(`${n}; codecs="${u}"`)||a==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:a,latestSegmentPublishTime:n,streamIsUnpublished:u,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((n-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:h})=>i(a,c,h)),l=new Set(u.map(({codecs:c})=>c)),d=Bs(l);if(d&&(r[a]=u.filter(({codecs:c})=>c.startsWith(d))),a==="video"){let c=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),p=r.video.some(m=>!m.hdr);V.display.isHDR&&c&&h?r.video=r.video.filter(m=>m.hdr):p&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",kr(s)),s}.bind(this));this.initRepresentations=yn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",kr({initialVideo:e,initialAudio:t,sourceHls:i})),mi(this.manifest),mi(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new En,this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(Xe(h,"error").pipe(Ks(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ne.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?es():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Gt())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}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},n=this.manifest.streams.video.reduce((h,p)=>[...h,...p.representations],[]);if(this.videoBufferManager=new vr("video",this.source,n,a),this.bufferManagers=[this.videoBufferManager],wr(t)){let h=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new vr("audio",this.source,h,a),this.bufferManagers.push(this.audioBufferManager)}Er.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Er(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(Ft(...jh.map(h=>Xe(this.element,h))).pipe(bi(h=>this.element?se(this.element.buffered,this.element.currentTime*1e3):0),xr(),Hh(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ft(Xe(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(xr()).subscribe(p=>this.liveStreamEndTimestamp=In())),this.subscription.add(Xe(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Tn(1e3).subscribe(p=>{let m=ht(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Xe(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(fi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(bi(({isActiveLive:p,isLowLatency:m})=>p&&m),xr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||oi(this.element,1)})),this.representationSubscription.add(fi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ks(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(fi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ks(({isLive:p})=>p),xr((p,m)=>m.bufferLength<p.bufferLength),bi(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=ht(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(fi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=p-b;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(S)>g&&(I=1+Math.sign(S)*x),oi(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let h=0;this.representationSubscription.add(fi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(tl(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=ht(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,E=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),B=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(B);let k="none";if(P?k="active_low_latency":this.isLowLatency$.getValue()&&B?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&E<x?k="live_forward_buffering":E<x+I&&(k="live_with_target_offset"),isFinite(p)&&(h=p>h?p:h),k==="live_forward_buffering"||k==="live_with_target_offset"){let $=h-(x+S),v=this.normolizeLiveOffset(Math.trunc(b+$/f)),M=Math.abs(v-b),y=0;!p||M<=this.tuning.dashCmafLive.offsetCalculationError?y=b:v>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(y=v),this.manifestUrlString=ee(this.manifestUrlString,y,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(h=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ne.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Ft(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(bi(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=Ft(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(bi(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue()))),c=fi({allBuffersFull:l,someBufferEnded:d}).pipe(xr(),bi(({allBuffersFull:h,someBufferEnded:p})=>h&&p),Ks(h=>h));if(this.representationSubscription.add(Ft(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{this.source?.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ft(...this.bufferManagers.map(h=>h.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 h=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{h&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Ne.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),p()},{once:!0})})}if(!this.isLive$.getValue()){let h=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Le(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...h)/1e3}this.audioBufferManager&&wr(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=Tn(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ne.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 Ys({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=at.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){mi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?In()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(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(){mi(this.element),this.state$.setState("running");let e=Xe(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(tl(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Ft(...Qh.map(t=>Xe(this.element,t)),Xe(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ne.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Xe(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(Xe(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&le(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=In(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&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 p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:Ne.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",kr(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Tn(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ne.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){mi(this.element),mi(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),le(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(el(this.element)||el(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",kr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){wr(this.element)&&wr(this.source)&&wr(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=Uh(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,n=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-n<=s&&l.to+n>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",kr({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as zh,map as Wh,observeElementSize as qh,Subscription as Gh,ValueSubject as xn,noop as Yh}from"@vkontakte/videoplayer-shared/evergreen";var Zs=class{constructor(){this.subscription=new Gh;this.pipSize$=new xn(void 0);this.videoSize$=new xn(void 0);this.elementSize$=new xn(void 0);this.pictureInPictureWindowRemoveEventListener=Yh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(qh(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(zh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Wh(({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 _t=class{constructor(e){this.subscription=new ip;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ei;this.stallsManager=new Us;this.elementSizeManager=new Zs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ft;this.audioTrackSwitchHistory=new ft;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"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return Xh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new di(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 De(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(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 Js({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;tp(this.observableVideo)&&(this.observableVideo=Te(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:il.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,n)=>this.subscription.add(a.subscribe(n,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(kn(c=>!!c.length),sl()).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(wn(c=>c.to.state!=="none"),ea());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(kn(rl),sl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(wn(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(ze(this.video,t.isLooped,r)),this.subscription.add(ye(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Re(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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 h=this.player.getStreams();if(Jh(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of h.audio){m.push(pn(f));let b=[];for(let g of f.representations){let x=zu(g);b.push(x),this.audioTracksMap.set(x,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let p=[];for(let m of h.video){p.push(mn(m));let f=[];for(let b of m.representations){let g=ju({...b,streamId:m.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:m,representation:b}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(p);for(let m of h.text)for(let f of m.representations){let b=Wu(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:n}=this.params.tuning.dash,u=n&&Yu(n)||null;this.subscription.add(ta(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$,ep(this.video,"progress")).pipe(kn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=Vt(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);rl(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(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},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(ea()).subscribe(c=>{let h=Vt(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=h,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(mn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ea()).subscribe(c=>{let h=Vt(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=h,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(pn(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(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}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(wn(({to:c})=>c==="ready"),ea());this.subscription.add(ta(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,An(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(ta(l,this.player.state$.stateChangeEnded$,An(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=ta(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,An(["init"])).pipe(Zh(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Pi:Li,t=this.params.tuning.useNewAutoSelectVideoTrack?gs:bs,i=this.params.tuning.useNewAutoSelectVideoTrack?Ge:fs,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),n=r.videoTrack.getState()?.id,u=Vt(this.videoTracksMap.keys(),k=>k.id===n),l=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Vt(this.videoStreamsMap.keys(),k=>k.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=se(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(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=g?.id&&Vt(this.audioStreamsMap.keys(),k=>k.id===g.id)||this.audioStreamsMap.keys().next().value,S=0;if(x){if(u&&!a){let k=e(u,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,k?.bitrate??-1/0)}if(l){let k=e(l,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,k?.bitrate??-1/0)}}let I=u;(a||!I)&&(I=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:S,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,h,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}),P=this.videoTracksMap.get(I)?.representation,B=E&&this.audioTracksMap.get(E)?.representation;P&&B?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=B):P&&!B&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:il.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),ve(this.video),this.tracer.end()}};var Ar=class extends _t{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Ln,merge as al,filter as nl,filterChanged as rp,isNullable as Pn,map as ol,ValueSubject as $n,isNonNullable as sp}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class extends _t{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 $n(1);s(i.playbackRateState$,a),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(ol(n=>n.to)).subscribe(this.player.isLowLatency$)).add(Ln({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ol(({liveBufferTime:n,liveAvailabilityStartTime:u})=>n&&u?n+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(nl(n=>sp(n))).subscribe(n=>t.isLiveEnded$.next(n!=="active"&&t.position$.getValue()===0))).add(Ln({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:al(i.playbackRateState$,new $n(1))}).pipe(nl(({liveStreamStatus:n,liveDuration:u})=>n==="active"&&!!u)).subscribe(({liveDuration:n,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||Pn(l)||(e=n-l)})).add(Ln({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:al(i.playbackRateState$,new $n(1))}).pipe(rp((n,u)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===u.liveDuration:n.time===u.time)).subscribe(({time:n,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Pn(n)||Pn(u))return;let h=-1*(u-n-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let u=qu(n);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 ul="X-Playback-Duration",Mn=async o=>{let e=await fetch(o),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(ul)?parseInt(e.headers.get(ul),10):void 0};import{assertNever as fp,combine as bp,debounce as gp,ErrorCategory as sa,filter as Sp,filterChanged as vp,isNonNullable as dl,isNullable as aa,map as hl,merge as yp,observableFrom as Tp,Subscription as Ip,ValueSubject as Dn,VideoQuality as Ep}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as ap,getExponentialDelay as np}from"@vkontakte/videoplayer-shared/evergreen";var op=o=>{let e=null;if(o.QUALITY&&(e=mt(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ap({width:t,height:i})}return e??null},up=(o,e)=>{let t=o.split(`
|
|
178
|
+
`),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],n=a.match(/^#EXT-X-STREAM-INF:(.+)/),u=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!n&&!u)){if(n){let l=Object.fromEntries(n[1].split(",").map(b=>b.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=op(l),h;l.BANDWIDTH&&(h=parseInt(l.BANDWIDTH,10)/1e3||void 0),!h&&l["AVERAGE-BANDWIDTH"]&&(h=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[b,g]=l.RESOLUTION.split("x").map(x=>parseInt(x,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();c&&i.push({id:d,quality:c,url:f,bandwidth:h,size:m,fps:p})}if(u){let l=Object.fromEntries(u[1].split(",").map(p=>{let m=p.indexOf("=");return[p.substring(0,m),p.substring(m+1)]}).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,h=l.NAME;d&&c&&r.push({type:"internal",id:c,label:h,language:c,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},lp=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),Rn=0,ll=async(o,e=o,t,i)=>{let s=await(await fetch(o,i)).text();Rn+=1;try{let{qualityManifests:a,textTracks:n}=up(s,e);return{qualityManifests:a,textTracks:n}}catch{if(Rn<=t.manifestRetryMaxCount)return await lp(np(Rn-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ll(o,e,t)}return{qualityManifests:[],textTracks:[]}},ia=ll;import{isNonNullable as cp,Subscription as dp,throttle as hp,ValueSubject as cl,Subject as pp,ErrorCategory as mp}from"@vkontakte/videoplayer-shared/evergreen";var ra=class{constructor(e,t,i,r,s){this.subscription=new dp;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new cl(null);this.getCurrentTime$=new cl(null);this.error$=new pp;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(hp(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(),n=this.parsePlaylist(a,r);return{textTrack:i,playlist:n}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
179
|
+
`),s=0;for(let a=0;a<r.length;++a){let n=r[a];switch(!0){case n.startsWith("#EXTINF:"):{let u=r[++a],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",n))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case n.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",n));break;case n.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",n));break;case n.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",n));break;case n.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",n);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case n.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",n);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(cp(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:mp.WTF,thrown:t,message:e})}};var Pr=class{constructor(e){this.subscription=new Ip;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Dn([]);this.liveOffset=new Pt;this.manifestStartTime$=new Dn(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(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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||n){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.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"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(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"&&A(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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else r?.to==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return fp(t)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ep.INVARIANT,url:this.params.source.url};let t=(i,r)=>ia(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 ra(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new De(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:sa.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:sa.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(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Dn(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 n=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsLiveProvider",category:sa.WTF,message:"HlsLiveProvider internal logic error",thrown:n})},r=Te(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.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(ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(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"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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(n=>{n&&this.params.output.availableTextTracks$.next(n)})),this.subscription.add(this.maxSeekBackTime$.pipe(vp(),hl(n=>-n/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&dl(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ue(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n&&n.state==="requested"&&this.seek(n.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let n=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(n||void 0)},i)),this.subscription.add(bp({startTime:this.manifestStartTime$.pipe(Sp(dl)),currentTime:r.timeUpdate$}).subscribe(({startTime:n,currentTime:u})=>this.params.output.liveTime$.next(n+u*1e3),i)),this.subscription.add(this.manifests$.pipe(hl(n=>n.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let a=yp(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Tp(["init"])).pipe(gp(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),ve(this.video)}prepare(){let e=this.selectManifest();if(aa(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:n,min:u}=t?.to??i??{};for(let[l,d]of[[n,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=ee(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),Mn(a).then(n=>{if(!aa(n))this.maxSeekBackTime$.next(n);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(aa(u)||!isFinite(u))&&fetch(a).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,a).toString();Mn(c).then(h=>{aa(h)||this.maxSeekBackTime$.next(h)})}}).catch(()=>{})}})}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sa.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=ee(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 xp,debounce as kp,ErrorCategory as Bn,fromEvent as Vn,isNonNullable as wp,isNullable as Ap,map as pl,merge as ml,observableFrom as fl,Subscription as Lp,ValueSubject as Pp,VideoQuality as $p}from"@vkontakte/videoplayer-shared/evergreen";var $r=class{constructor(e){this.subscription=new Lp;this.videoState=new O("stopped");this.manifests$=new Pp([]);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(),n=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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||n){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),n&&this.params.output.autoVideoTrackLimits$.next(n.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"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return xp(t)}};this.textTracksManager=new De(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$p.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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ia(ee(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:Bn.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 n=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(u=>u.id===n)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"HlsProvider",category:Bn.WTF,message:"HlsProvider internal logic error",thrown:n})},r=Te(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.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(pl(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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 n=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&wp(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(ue(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=this.params.output.element$.getValue()?.playbackRate;if(c!==h){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),n.state==="requested"&&this.seek(n.position)},i))),this.subscription.add(this.manifests$.pipe(pl(n=>n.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!V.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:n}=this.video;this.subscription.add(ml(Vn(n,"addtrack"),Vn(n,"removetrack"),Vn(n,"change"),fl(["init"])).subscribe(()=>{for(let u=0;u<n.length;u++)n[u].mode="hidden"},i))}let a=ml(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fl(["init"])).pipe(kp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){let e=this.selectManifest();if(Ap(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[n,u]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(n||""));u&&n&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Mp,assertNonNullable as bl,debounce as Rp,ErrorCategory as gl,isHigherOrEqual as Dp,isLowerOrEqual as Bp,isNonNullable as Vp,merge as Cp,observableFrom as Op,Subscription as Fp,map as _p}from"@vkontakte/videoplayer-shared/evergreen";var Mr=class{constructor(e){this.subscription=new Fp;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new De;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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(),n=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(),n.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&n.state==="requested"&&this.seek(n.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return Mp(e)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let 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=n=>{e.error$.next({id:"MpegProvider",category:gl.WTF,message:"MpegProvider internal logic error",thrown:n})},r=Te(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.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(_p(n=>n.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Re(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let n=this.params.desiredState.videoTrack.getTransition();if(n&&Vp(n.to)){this.params.desiredState.videoTrack.setState(n.to),this.params.output.currentVideoTrack$.next(this.trackUrls[n.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let a=Cp(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Op(["init"])).pipe(Rp(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),ve(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;bl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];bl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=St(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.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 d=Ge(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(d)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||Yt(e,a[0].quality,a.at(-1)?.quality)){i();return}let n=e.max?Bp(r,e.max):!0,u=e.min?Dp(r,e.min):!0;n&&u||i(e)}};import{assertNever as vl,debounce as Qp,merge as yl,observableFrom as jp,Subscription as zp,map as Tl,ValueSubject as Wp,ErrorCategory as On,VideoQuality as qp}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Np}from"@vkontakte/videoplayer-shared/evergreen";var Sl=["stun:videostun.mycdn.me:80"],Up=1e3,Hp=3,Cn=()=>null,na=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=Cn;this.externalStopCallback=Cn;this.externalErrorCallback=Cn;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:Sl}]};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:Np.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),Up)}normalizeOptions(e={}){let t={stunServerList:Sl,maxRetryNumber:Hp,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Rr=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new Wp(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return vl(e)}};this.subscription=new zp,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Se(e.container,e.tuning),this.liveStreamClient=new na(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),ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:On.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(yl(this.videoState.stateChangeStarted$.pipe(Tl(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Tl(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}));let r=Te(this.video);this.subscription.add(()=>r.destroy());let s=(a,n)=>this.subscription.add(a.subscribe(n,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(Be(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(ye(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 vl(a.to)}},i)).add(yl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,jp(["init"])).pipe(Qp(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(ue(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:qp.INVARIANT}),this.video.srcObject=e,A(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:On.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ie(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:On.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Dr=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 Br,assertNonNullable as Tt,ErrorCategory as oa,filter as Al,isNonNullable as Ll,isNullable as em,map as tm,merge as im,once as rm,Subject as ae,Subscription as Pl,ValueSubject as _,flattenObject as Fn}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as Gp,map as Il,Subscription as Yp,Subject as Kp}from"@vkontakte/videoplayer-shared/evergreen";var El=o=>new Gp(e=>{let t=new Yp,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Il(({from:l,to:d})=>`${l}-${d}`)),r=o.desiredPlaybackState$.stateChangeEnded$,s=o.providerChanged$.pipe(Il(({type:l})=>l!==void 0)),a=new Kp,n=0,u="unknown";return t.add(i.subscribe(l=>{n&&window.clearTimeout(n),u=l,n=window.setTimeout(()=>a.next(l),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(n),u="unknown",n=0})),t.add(s.subscribe(l=>{n&&(window.clearTimeout(n),n=0,l&&(n=window.setTimeout(()=>a.next(u),o.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(n),t.unsubscribe()}});import{ErrorCategory as Xp,Subscription as Jp,combine as Zp,filter as kl,once as wl}from"@vkontakte/videoplayer-shared/evergreen";function xl(){return new(window.AudioContext||window.webkitAudioContext)}var gi=class o{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new Jp;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(kl(s=>!!s.type),wl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){V.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(Zp({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(kl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),wl()).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=xl();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:o.errorId,category:Xp.VIDEO_PIPELINE,message:e?.message??`${o.errorId} exception`,thrown:e})}};var sm={chunkDuration:5e3,maxParallelRequests:5},Vr=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new ae;this.noAvailableProvidersError$=new ae;this.volumeMultiplierError$=new ae;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new ae,fetcherError$:new ae,fetcherRecoverableError$:new ae,warning$:new ae,willSeekEvent$:new ae,soundProhibitedEvent$:new ae,seekedEvent$:new ae,loopedEvent$:new ae,endedEvent$:new ae,firstBytesEvent$:new ae,loadedMetadataEvent$:new ae,firstFrameEvent$:new ae,canplay$:new ae,isLive$:new _(void 0),isLiveEnded$:new _(null),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new ae,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new Pl;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=xu([...wu(this.params.tuning),...ku(this.params.tuning)],this.params.tuning).filter(l=>Ll(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",Fn(s)),this.screenFormatsIterator=new Dr(s);let a=[...Ya(!0),...Ya(!1)];this.chromecastFormatsIterator=new Dr(a.filter(l=>Ll(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:n=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&n!==1&&gi.isSupported()&&(this.volumeMultiplierManager=new gi(this.providerOutput,this.current$,this.volumeMultiplierError$,n))}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(em(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:oa.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 Br(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,n={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 Tt(u),this.params.tuning.useNewDashProvider?new Ar({...n,source:u,sourceHls:l}):new gr({...n,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Tt(u),this.params.tuning.useNewDashProvider?new Lr({...n,source:u}):new Sr({...n,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Tt(u),new $r({...n,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Tt(u),new Pr({...n,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Tt(u),new Mr({...n,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Tt(u),new Jo({...n,source:u,config:{...sm,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Tt(u),new Rr({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 Br(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return Tt(n),new Ii({connection:n,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 Br(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Br(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 Br(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 Pl,t=!1,i=0;return e.add(im(this.providerOutput.error$.pipe(Al(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),El({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(tm(r=>({id:`ProviderHangup:${r}`,category:oa.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(Al(({to:s})=>s==="playing"),rm()).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 n=r.category===oa.NETWORK,u=r.category===oa.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(n&&t||!d);a={...a,isNetworkError:n,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(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",Fn(a)):this.tracer.error("providerError",Fn(a))})),e}};import{fromEvent as ua,once as am,combine as nm,Subscription as $l,ValueSubject as _n,map as om,filter as um,isNonNullable as la,now as Pe,safeStorage as Nn}from"@vkontakte/videoplayer-shared/evergreen";var lm=5e3,Ml="one_video_throughput",Rl="one_video_rtt",Cr=window.navigator.connection,Dl=()=>{let o=Cr?.downlink;if(la(o)&&o!==10)return o*1e3},Bl=()=>{let o=Cr?.rtt;if(la(o)&&o!==3e3)return o},Vl=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},Un=class o{constructor(e){this.subscription=new $l;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=o.load(Ml)||(e.useBrowserEstimation?Dl():void 0)||lm,i=o.load(Rl)??(e.useBrowserEstimation?Bl():void 0)??0;if(this.throughput$=new _n(t),this.rtt$=new _n(i),this.rttAdjustedThroughput$=new _n(Vl(t,i,e.rttPenaltyRequestSize)),this.throughput=at.getSmoothedValue(t,-1,e),this.rtt=at.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Dl();a&&this.throughput.next(a);let n=Bl();la(n)&&this.rtt.next(n)};Cr&&"onchange"in Cr&&this.subscription.add(ua(Cr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Nn.set(Ml,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Nn.set(Rl,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(nm({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(om(({throughput:r,rtt:s})=>Vl(r,s,e.rttPenaltyRequestSize)),um(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=Pe(),r=new $l;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(ua(e,"progress").pipe(am()).subscribe(s=>{t=s.loaded,i=Pe()}));break;case 1:case 0:r.add(ua(e,"loadstart").subscribe(()=>{t=0,i=Pe()}));break}r.add(ua(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,n=Pe(),u=a-t,l=n-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=Pe(),a=0,n=Pe(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,Pe()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=Pe();if(h-n>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=n-s;m&&this.addRawSpeed(a,m,1,t),a=c.byteLength,s=Pe()}else a+=c.byteLength;n=Pe()}else r+=c.byteLength,a+=c.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Pe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Pe()-n,this.concurrentDownloads.size),a=0,n=Pe());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(o.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=Nn.get(e);if(la(t))return parseInt(t,10)??void 0}},Cl=Un;import{fillWithDefault as cm,VideoQuality as ca}from"@vkontakte/videoplayer-shared/evergreen";var Ol={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:ca.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:ca.Q_720P,trafficSavingLimit:ca.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:ca.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},Fl=o=>({...cm(o,Ol),configName:[...o.configName??[],...Ol.configName]});import{assertNonNullable as da,combine as ot,ErrorCategory as ha,filter as C,filterChanged as z,fromEvent as Qn,isNonNullable as Hl,isNullable as gm,Logger as Sm,map as j,mapTo as Ql,merge as It,now as pa,once as U,Subject as W,Subscription as jl,tap as jn,ValueSubject as L,isHigher as vm,isInvariantQuality as zl,flattenObject as Et,throttle as zn,getTraceSubscriptionMethod as Wl,TracerFactory as ym,InternalsExposure as Tm}from"@vkontakte/videoplayer-shared/evergreen";import{merge as dm,map as hm,filter as _l,isNonNullable as pm}from"@vkontakte/videoplayer-shared/evergreen";var Hn=({seekState:o,position$:e})=>dm(o.stateChangeEnded$.pipe(hm(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),_l(pm)),e.pipe(_l(()=>o.getState().state==="none")));import{assertNonNullable as mm}from"@vkontakte/videoplayer-shared/evergreen";var Nl=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return mm(e,`Wrong container or containerId {${o.container}}`),e};import{filter as fm,once as bm}from"@vkontakte/videoplayer-shared/evergreen";var Ul=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(fm(r=>r.length>0),bm()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t?.getValue().find(i))&&e.startTransitionTo(o)};var ma=class{constructor(e={configName:[]},t=ym.createRootTracer(!1)){this.subscription=new jl;this.logger=new Sm;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new L(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new L(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new L(void 0),position$:new L(0),duration$:new L(1/0),muted$:new L(!1),volume$:new L(1),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableQualities$:new L([]),availableQualitiesFps$:new L({}),currentQuality$:new L(void 0),isAutoQualityEnabled$:new L(!0),autoQualityLimitingAvailable$:new L(!1),autoQualityLimits$:new L({}),predefinedQualityLimitType$:new L("unknown"),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),isAudioAvailable$:new L(!0),currentPlaybackRate$:new L(1),currentBuffer$:new L({start:0,end:0}),isBuffering$:new L(!0),isStalled$:new L(!1),isEnded$:new L(!1),isLooped$:new L(!1),isLive$:new L(void 0),isLiveEnded$:new L(null),canChangePlaybackSpeed$:new L(void 0),atLiveEdge$:new L(void 0),atLiveDurationEdge$:new L(void 0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),liveLatency$:new L(void 0),currentFormat$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),throughputEstimation$:new L(void 0),rttEstimation$:new L(void 0),videoBitrate$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),surface$:new L("none"),chromecastState$:new L("NOT_AVAILABLE"),chromecastDeviceName$:new L(void 0),intrinsicVideoSize$:new L(void 0),availableSources$:new L(void 0),is3DVideo$:new L(!1),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0)};this.events={inited$:new W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new L(void 0),tuningConfigName$:new L([]),enableDebugTelemetry$:new L(!1),dumpTelemetry:Po,getCurrentTime$:new L(null)};if(this.initLogs(),this.tuning=Fl(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Gr({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Cl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Tm("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:(...n)=>{try{return a.apply(i,n)}catch(u){let l=n.map(h=>JSON.stringify(h,(p,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:ha.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",Et(a)),this.domContainer=Nl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Vr({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?V.isInited$.pipe(C(s=>!!s),U()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Qn(document,"visibilitychange").pipe(U()).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(C(e=>!!e),U()).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(C(e=>!!e),U()).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(C(e=>!!e),U()).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(C(e=>!!e),U()).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(C(i=>!!i),U()).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(C(t=>!!t),U()).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(C(i=>!!i),U()).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(C(i=>!!i),U()).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(C(t=>!!t),U()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).subscribe(()=>{da(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(C(i=>i.length>0),U()).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(C(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Et(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).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(C(t=>!!t),U()).subscribe(()=>{da(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(C(t=>!!t),U()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Et(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),U()).subscribe(()=>{Ul(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(C(t=>!!t),U()).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(C(t=>!!t),U()).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(C(i=>!!i),U()).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(C(t=>!!t),U()).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(C(i=>!!i),U()).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(C(e=>e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(gm(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Hl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ra(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(C(({from:e})=>e==="stopped"),U()).subscribe(()=>{this.initedAt=pa(),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",Et(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:ha.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(U()).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",Et(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(j(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(a=>a.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ot({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:a,currentVideoStream:n})=>a.filter(u=>n?n.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>zl(u)?1:zl(l)?-1:vm(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let n={};for(let u of a)u.fps&&(n[u.quality]=u.fps);this.info.availableQualitiesFps$.next(n)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(C(a=>Hl(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((a,n)=>Math.round(a)===Math.round(n))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((a,n)=>Math.round(a)===Math.round(n))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).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(j(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(jn(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(ot({hasLiveOffsetByPaused:It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(a=>a.to),z(),j(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:n})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(n));return}this.hasLiveOffsetByPaused.next(!1)})).add(ot({atLiveEdge:ot({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Hn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:a,position:n,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return a&&Math.abs(n)<l/1e3}),z(),jn(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:a,hasPausedTimeoutCase:n})=>a&&!n)).subscribe(this.info.atLiveEdge$)).add(ot({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:a,position:n,duration:u})=>a&&(Math.abs(u)-Math.abs(n))*1e3<this.tuning.live.activeLiveDelay),z(),jn(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(a=>a.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(a=>a.volume),z()).subscribe(this.info.volume$)).add(Hn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(It(e.providerOutput.endedEvent$.pipe(Ql(!0)),e.providerOutput.seekedEvent$.pipe(Ql(!1))).pipe(z()).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(j(a=>({id:a?`No${a}`:"NoProviders",category:ha.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(U(),j(a=>a??pa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(U(),j(()=>pa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(U(),j(()=>pa()-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 L(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new L(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(C(({to:a})=>a==="playing"),U()).subscribe(()=>i.next(!1)));let r=0,s=It(e.providerOutput.isBuffering$,t,i).pipe(j(()=>{let a=e.providerOutput.isBuffering$.getValue(),n=t.getValue()||i.getValue();return a&&!n}),z());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(It(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 n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(It(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?a?c="pip":n?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(j(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new jl;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(C(i=>i.length>0),U()).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=Ge(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(It(this.desiredState.videoTrack.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(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;da(this.providerContainer),da(e),Lo(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Ao(t)),this.providerContainer.current$.subscribe(({type:t})=>Ai("provider",t)),e.duration$.subscribe(t=>Ai("duration",t)),e.availableVideoTracks$.pipe(C(t=>!!t.length),U()).subscribe(t=>Ai("tracks",t)),this.events.fatalError$.subscribe(new fe("fatalError")),this.events.managedError$.subscribe(new fe("managedError")),e.position$.subscribe(new fe("position")),e.currentVideoTrack$.pipe(j(t=>t?.quality)).subscribe(new fe("quality")),this.info.currentBuffer$.subscribe(new fe("buffer")),e.isBuffering$.subscribe(new fe("isBuffering"))].forEach(t=>this.subscription.add(t)),Ai("codecs",V.video.supportedCodecs)}initTracerSubscription(){let e=Wl(this.tracer.log.bind(this.tracer)),t=Wl(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(z()).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(ot({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(C(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(C(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(C(i=>i>0),z()).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(ot({currentBuffer:this.info.currentBuffer$.pipe(C(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(zn(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(ot({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(C(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),zn(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),C(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),C(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),C(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ot({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(C(({throughputEstimation:i,rtt:r})=>!!i&&!!r),zn(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),C(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:ha.DOM,message:String(r)})})};this.subscription.add(It(Qn(document,"visibilitychange"),Qn(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",Et({quality:t,availableTracks:Et(e),track:Et(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&&!Bi()}};import{Subscription as XR,Observable as JR,Subject as ZR,ValueSubject as eD,VideoQuality as tD}from"@vkontakte/videoplayer-shared/evergreen";var iD=`@vkontakte/videoplayer-core@${qn}`;export{zr as ChromecastState,ga as HttpConnectionType,JR as Observable,ge as PlaybackState,ma as Player,Wr as PredefinedQualityLimits,iD as SDK_VERSION,ZR as Subject,XR as Subscription,Sa as Surface,qn as VERSION,eD as ValueSubject,Ze as VideoFormat,tD as VideoQuality,nc as areValidLiveRecordSources,V as clientChecker,wi as isMobile};
|