@vkontakte/videoplayer-core 2.0.105-dev.7303ff18.0 → 2.0.105-dev.8ee45bd1.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 +14 -14
- package/es2015.esm.js +15 -15
- package/es2018.cjs.js +13 -13
- package/es2018.esm.js +11 -11
- package/esnext.cjs.js +17 -17
- package/esnext.esm.js +12 -12
- package/evergreen.esm.js +12 -12
- package/package.json +2 -2
- package/types/player/types.d.ts +1 -0
- package/types/providers/DashProvider/consts.d.ts +1 -1
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -1
- package/types/providers/ProviderContainer/index.d.ts +3 -0
- package/types/providers/ProviderContainer/types.d.ts +1 -0
- package/types/providers/types.d.ts +1 -0
- package/types/utils/VolumeMultiplierManager/VolumeMultiplierManager.d.ts +17 -0
- package/types/utils/VolumeMultiplierManager/audioContext.d.ts +9 -0
- package/types/utils/VolumeMultiplierManager/index.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +2 -0
package/es2015.cjs.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.105-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.105-dev.8ee45bd1.0
|
|
3
|
+
* Wed, 17 Jul 2024 10:04:57 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-105/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var sn=Object.create;var Gt=Object.defineProperty,nn=Object.defineProperties,on=Object.getOwnPropertyDescriptor,un=Object.getOwnPropertyDescriptors,dn=Object.getOwnPropertyNames,Sa=Object.getOwnPropertySymbols,ln=Object.getPrototypeOf,ya=Object.prototype.hasOwnProperty,cn=Object.prototype.propertyIsEnumerable;var _e=Math.pow,va=(n,e,t)=>e in n?Gt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,M=(n,e)=>{for(var t in e||(e={}))ya.call(e,t)&&va(n,t,e[t]);if(Sa)for(var t of Sa(e))cn.call(e,t)&&va(n,t,e[t]);return n},q=(n,e)=>nn(n,un(e));var pn=(n,e)=>{for(var t in e)Gt(n,t,{get:e[t],enumerable:!0})},Ta=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of dn(e))!ya.call(n,r)&&r!==t&&Gt(n,r,{get:()=>e[r],enumerable:!(i=on(e,r))||i.enumerable});return n};var hn=(n,e,t)=>(t=n!=null?sn(ln(n)):{},Ta(e||!n||!n.__esModule?Gt(t,"default",{value:n,enumerable:!0}):t,n)),mn=n=>Ta(Gt({},"__esModule",{value:!0}),n);var V=(n,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(d){r(d)}},s=u=>{try{o(t.throw(u))}catch(d){r(d)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,s);o((t=t.apply(n,e)).next())}),fn=function(n,e){this[0]=n,this[1]=e},le=(n,e,t)=>{var i=(s,o,u,d)=>{try{var c=t[s](o),l=(o=c.value)instanceof fn,h=c.done;Promise.resolve(l?o[0]:o).then(m=>l?i(s==="return"?s:"next",o[1]?{done:m.done,value:m.value}:m,u,d):u({value:m,done:h})).catch(m=>i("throw",m,u,d))}catch(m){d(m)}},r=s=>a[s]=o=>new Promise((u,d)=>i(s,o,u,d)),a={};return t=t.apply(n,e),a[Symbol.asyncIterator]=()=>a,r("next"),r("throw"),r("return"),a};var So={};pn(So,{ChromecastState:()=>Qt,HttpConnectionType:()=>ji,Observable:()=>Ge.Observable,PlaybackState:()=>ge,Player:()=>Oi,SDK_VERSION:()=>go,Subject:()=>Ge.Subject,Subscription:()=>Ge.Subscription,Surface:()=>Yi,VERSION:()=>$r,ValueSubject:()=>Ge.ValueSubject,VideoFormat:()=>st,VideoQuality:()=>Ge.VideoQuality});module.exports=mn(So);var $r="2.0.105-dev.7303ff18.0";var ge=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ge||{}),st=(g=>(g.MPEG="MPEG",g.DASH="DASH_SEP",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_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))(st||{});var Qt=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Qt||{}),ji=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ji||{});var Yi=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Yi||{});var N=require("@vkontakte/videoplayer-shared");var Ia=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var qi=class{constructor(e){this.connection$=new N.ValueSubject(void 0);this.castState$=new N.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new N.Subject;this.realCastState$=new N.ValueSubject("NOT_AVAILABLE");this.subscription=new N.Subscription;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,N.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},r||Ia("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:N.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,N.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,N.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,s;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(s=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:s.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,N.assertNever)(r.sessionState)}})).add((0,N.merge)((0,N.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,N.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,N.map)(r=>r.castState)),(0,N.observableFrom)([i.getCastState()])).pipe((0,N.filterChanged)(),(0,N.map)(bn),(0,N.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o;let a=r==="CONNECTED",s=(0,N.isNonNullable)(this.connection$.getValue());if(a&&!s){let u=i.getCurrentSession();(0,N.assertNonNullable)(u);let d=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;((0,N.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,N.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:N.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},bn=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,N.assertNever)(n)}};var Rr=require("@vkontakte/videoplayer-shared");var he=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Rr.assertNever)(t)}return n},Dr=(n,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(n);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(n);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Rr.assertNever)(e)}};var P=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};var Ne=require("@vkontakte/videoplayer-shared"),G=class{constructor(e){this.transitionStarted$=new Ne.Subject;this.transitionEnded$=new Ne.Subject;this.transitionUpdated$=new Ne.Subject;this.forceChanged$=new Ne.Subject;this.stateChangeStarted$=(0,Ne.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Ne.merge)(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||(0,Ne.isNonNullable)(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}};var Ea=require("@vkontakte/videoplayer-shared"),xa=n=>{switch(n){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":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(0,Ea.assertNever)(n)}};var w=require("@vkontakte/videoplayer-shared");var gn=5,Sn=5,vn=500,Pa=7e3,Wt=class{constructor(e){this.subscription=new w.Subscription;this.loadMediaTimeoutSubscription=new w.Subscription;this.videoState=new G("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,w.assertNever)(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:(0,w.assertNever)(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:(0,w.assertNever)(e)}break}default:(0,w.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(xa(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 w.Subscription;this.subscription.add(e),this.subscription.add((0,w.merge)(this.videoState.stateChangeStarted$.pipe((0,w.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,w.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new w.Subject;e.add(r.pipe((0,w.debounce)(vn)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>gn)&&r.next(o),a=o})),e.add((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Sn&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:(0,w.assertNever)(s)}}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,w.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,w.observableFrom)(["init"])).pipe((0,w.debounce)(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var d;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let c=t[e];(0,w.assertNonNullable)(c);let l=(0,w.getHighestQuality)(Object.keys(c));(0,w.assertNonNullable)(l);let h=c[l];(0,w.assertNonNullable)(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,w.assertNonNullable)(c),i=c.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let c=t[e];(0,w.assertNonNullable)(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,w.assertNonNullable)(c),i=c.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,w.assertNonNullable)(c),i=he(c.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",l=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:w.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:l}),l}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,w.assertNever)(e)}let s=new chrome.cast.media.MediaInfo((d=this.params.meta.videoId)!=null?d:i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,w.isNonNullable)(o)&&(s.metadata.title=o),(0,w.isNonNullable)(u)&&(s.metadata.subtitle=u),s}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add((0,w.timeout)(Pa).subscribe(()=>a(`timeout(${Pa})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:w.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var jt=n=>{n.removeAttribute("src"),n.load()};var ka=n=>{try{n.pause(),n.playbackRate=0,jt(n),n.remove()}catch(e){console.error(e)}};var Mr=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)}},Cr=window.WeakMap?new WeakMap:new Mr,Se=n=>{let e=n.querySelector("video"),t=!!e;return e?jt(e):(e=document.createElement("video"),n.appendChild(e)),Cr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ve=n=>{let e=Cr.get(n);Cr.delete(n),e?jt(n):ka(n)};var L=require("@vkontakte/videoplayer-shared");var nt=require("@vkontakte/videoplayer-shared"),zi=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=(0,nt.isNullable)(r),d=new nt.Subscription;return r&&d.add(r.subscribe(c=>{let l=n.getState();i(c,l)&&n.setState(c)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(c=>{t(c.to),u&&n.setState(c.to)},a)),d},Fe=(n,e,t)=>zi(e,()=>n.loop,i=>{(0,nt.isNonNullable)(i)&&(n.loop=i)},{onError:t}),ye=(n,e,t,i)=>zi(e,()=>({muted:n.muted,volume:n.volume}),r=>{(0,nt.isNonNullable)(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),we=(n,e,t,i)=>zi(e,()=>n.playbackRate,r=>{(0,nt.isNonNullable)(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),ot=zi;var yn=n=>["__",n.language,n.label].join("|"),Tn=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Br=class n{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ot(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{(0,L.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,s)=>(0,L.isNonNullable)(a)&&(0,L.isNonNullable)(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe((0,L.map)(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(ot(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{(0,L.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,s)=>(0,L.isNonNullable)(a)&&(0,L.isNonNullable)(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe((0,L.map)(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(ot(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ot(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{var a,s;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var d,c,l,h,m;let u=(c=(d=o.target)==null?void 0:d.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(l=o.target)==null?void 0:l.cues)!=null?h:null),(m=o.target)==null||m.removeEventListener("cuechange",r))};(s=i.track)==null||s.addEventListener("cuechange",r)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,L.isNonNullable)(t.align)&&(r.align=t.align),(0,L.isNonNullable)(t.position)&&(r.position=t.position),(0,L.isNonNullable)(t.size)&&(r.size=t.size),(0,L.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:i}=e,r=e.id?e.id:yn(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:(o=this.externalTracks.get(r))==null?void 0:o.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:(u=this.internalTracks.get(r))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!Tn(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){(0,L.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Le=Br;var je=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 Aa=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Vr=n=>{let e=Aa(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},wa=n=>{let e=Aa(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};var A=require("@vkontakte/videoplayer-shared");var In=3,La=(n,e,t=In)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var Te=n=>{let e=I=>(0,A.fromEvent)(n,I).pipe((0,A.mapTo)(void 0)),i=(0,A.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,A.fromEvent)(n,I))).pipe((0,A.map)(I=>I.type==="ended"?n.readyState<2:n.readyState<3),(0,A.filterChanged)()),r=(0,A.merge)((0,A.fromEvent)(n,"progress"),(0,A.fromEvent)(n,"timeupdate")).pipe((0,A.map)(()=>La(n.buffered,n.currentTime))),s=(0,A.getCurrentBrowser)().browser===A.CurrentClientBrowser.Safari?(0,A.combine)({play:e("play").pipe((0,A.once)()),playing:e("playing")}).pipe((0,A.mapTo)(void 0)):e("playing"),o=(0,A.fromEvent)(n,"volumechange").pipe((0,A.map)(()=>({muted:n.muted,volume:n.volume}))),u=(0,A.fromEvent)(n,"ratechange").pipe((0,A.map)(()=>n.playbackRate)),d=(0,A.fromEvent)(n,"error").pipe((0,A.filter)(()=>!!(n.error||n.played.length)),(0,A.map)(()=>{var E;let I=n.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:A.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(E=n.error)!=null?E:void 0}})),c=(0,A.fromEvent)(n,"timeupdate").pipe((0,A.map)(()=>n.currentTime)),l=new A.Subject,h=.3,m;c.subscribe(I=>{n.loop&&(0,A.isNonNullable)(m)&&(0,A.isNonNullable)(I)&&m>=n.duration-h&&I<=h&&l.next(m),m=I});let f=e("pause").pipe((0,A.filter)(()=>!n.error&&m!==n.duration)),b=(0,A.fromEvent)(n,"enterpictureinpicture"),v=(0,A.fromEvent)(n,"leavepictureinpicture"),T=new A.ValueSubject(wa(n));b.subscribe(()=>T.next(!0)),v.subscribe(()=>T.next(!1));let g=new A.ValueSubject(Vr(n));return(0,A.fromEvent)(n,"fullscreenchange").pipe((0,A.map)(()=>Vr(n))).subscribe(g),{playing$:s,pause$:f,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,A.fromEvent)(n,"durationchange").pipe((0,A.map)(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:g}};var Ye=require("@vkontakte/videoplayer-shared"),ut=n=>{switch(n){case"mobile":return Ye.VideoQuality.Q_144P;case"lowest":return Ye.VideoQuality.Q_240P;case"low":return Ye.VideoQuality.Q_360P;case"sd":case"medium":return Ye.VideoQuality.Q_480P;case"hd":case"high":return Ye.VideoQuality.Q_720P;case"fullhd":case"full":return Ye.VideoQuality.Q_1080P;case"quadhd":case"quad":return Ye.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Ye.VideoQuality.Q_2160P}};var U=require("@vkontakte/videoplayer-shared");var Or=!1,qe={},$a=n=>{Or=n},Ra=()=>{qe={}},Da=n=>{n(qe)},Yt=(n,e)=>{var t;Or&&(qe.meta=(t=qe.meta)!=null?t:{},qe.meta[n]=e)},fe=class{constructor(e){this.name=e}next(e){var i,r;if(!Or)return;qe.series=(i=qe.series)!=null?i:{};let t=(r=qe.series[this.name])!=null?r:[];t.push([Date.now(),e]),qe.series[this.name]=t}};var En=new fe("best_bitrate"),xn=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t,Ki=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,U.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Pn='Assertion "ABR Tracks is empty array" failed',kn=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:c,abrLogger:l})=>{var Z,B,$,ee,se;(0,U.assertNotEmptyArray)(n,Pn);let h=i.usePixelRatio&&(Z=window.devicePixelRatio)!=null?Z:1,m=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*i.containerSizeFactor,height:e.height*h*i.containerSizeFactor},f=m&&(0,U.videoSizeToQuality)(m),b=i.considerPlaybackRate&&(0,U.isNonNullable)(o)?o:1,v=n.filter(D=>!(0,U.isInvariantQuality)(D.quality)).sort((D,k)=>(0,U.isHigher)(D.quality,k.quality)?-1:1),T=(B=v.at(-1))==null?void 0:B.quality,g=($=v.at(0))==null?void 0:$.quality,_=(0,U.isNullable)(r)||(0,U.isNonNullable)(r.min)&&(0,U.isNonNullable)(r.max)&&(0,U.isLower)(r.max,r.min)||(0,U.isNonNullable)(r.min)&&g&&(0,U.isHigher)(r.min,g)||(0,U.isNonNullable)(r.max)&&T&&(0,U.isLower)(r.max,T),I=b*xn(s!=null?s:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},W=v.filter(D=>(f?(0,U.isLower)(D.quality,f):!0)?((0,U.isNonNullable)(t)&&isFinite(t)&&(0,U.isNonNullable)(D.bitrate)?t-a>=D.bitrate*I:!0)?i.lazyQualitySwitch&&(0,U.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,U.isInvariantQuality)(u.quality)&&(s!=null?s:0)<i.minBufferToSwitchUp&&(0,U.isHigher)(D.quality,u.quality)?(E[D.quality]="Buffer",!1):!!c&&(0,U.isHigherOrEqual)(D.quality,c)?(E[D.quality]="DroppedFramesLimit",!1):_||((0,U.isNullable)(r.max)||(0,U.isLowerOrEqual)(D.quality,r.max))&&((0,U.isNullable)(r.min)||(0,U.isHigherOrEqual)(D.quality,r.min))?!0:(E[D.quality]="FitsQualityLimits",!1):(E[D.quality]="FitsThroughput",!1):(E[D.quality]="FitsContainer",!1))[0];W&&W.bitrate&&En.next(W.bitrate);let Q=(ee=W!=null?W:v[Math.ceil((v.length-1)/2)])!=null?ee:n[0];Q.quality!==((se=d==null?void 0:d.last)==null?void 0:se.quality)&&l({message:`
|
|
6
|
+
"use strict";var pn=Object.create;var Wt=Object.defineProperty,hn=Object.defineProperties,mn=Object.getOwnPropertyDescriptor,fn=Object.getOwnPropertyDescriptors,bn=Object.getOwnPropertyNames,Pa=Object.getOwnPropertySymbols,gn=Object.getPrototypeOf,Aa=Object.prototype.hasOwnProperty,Sn=Object.prototype.propertyIsEnumerable;var _e=Math.pow,ka=(n,e,t)=>e in n?Wt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,C=(n,e)=>{for(var t in e||(e={}))Aa.call(e,t)&&ka(n,t,e[t]);if(Pa)for(var t of Pa(e))Sn.call(e,t)&&ka(n,t,e[t]);return n},q=(n,e)=>hn(n,fn(e));var vn=(n,e)=>{for(var t in e)Wt(n,t,{get:e[t],enumerable:!0})},wa=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of bn(e))!Aa.call(n,r)&&r!==t&&Wt(n,r,{get:()=>e[r],enumerable:!(i=mn(e,r))||i.enumerable});return n};var yn=(n,e,t)=>(t=n!=null?pn(gn(n)):{},wa(e||!n||!n.__esModule?Wt(t,"default",{value:n,enumerable:!0}):t,n)),Tn=n=>wa(Wt({},"__esModule",{value:!0}),n);var B=(n,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(d){r(d)}},s=u=>{try{o(t.throw(u))}catch(d){r(d)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,s);o((t=t.apply(n,e)).next())}),In=function(n,e){this[0]=n,this[1]=e},le=(n,e,t)=>{var i=(s,o,u,d)=>{try{var l=t[s](o),c=(o=l.value)instanceof In,h=l.done;Promise.resolve(c?o[0]:o).then(m=>c?i(s==="return"?s:"next",o[1]?{done:m.done,value:m.value}:m,u,d):u({value:m,done:h})).catch(m=>i("throw",m,u,d))}catch(m){d(m)}},r=s=>a[s]=o=>new Promise((u,d)=>i(s,o,u,d)),a={};return t=t.apply(n,e),a[Symbol.asyncIterator]=()=>a,r("next"),r("throw"),r("return"),a};var Po={};vn(Po,{ChromecastState:()=>jt,HttpConnectionType:()=>Ki,Observable:()=>Qe.Observable,PlaybackState:()=>fe,Player:()=>Ui,SDK_VERSION:()=>xo,Subject:()=>Qe.Subject,Subscription:()=>Qe.Subscription,Surface:()=>Ji,VERSION:()=>Vr,ValueSubject:()=>Qe.ValueSubject,VideoFormat:()=>je,VideoQuality:()=>Qe.VideoQuality});module.exports=Tn(Po);var Vr="2.0.105-dev.8ee45bd1.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(fe||{}),je=(g=>(g.MPEG="MPEG",g.DASH="DASH_SEP",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_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))(je||{});var jt=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(jt||{}),Ki=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Ki||{});var Ji=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Ji||{});var _=require("@vkontakte/videoplayer-shared");var La=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Xi=class{constructor(e){this.connection$=new _.ValueSubject(void 0);this.castState$=new _.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new _.Subject;this.realCastState$=new _.ValueSubject("NOT_AVAILABLE");this.subscription=new _.Subscription;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,_.isNonNullable)((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},r||La("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,_.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,_.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,_.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,_.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,s;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(s=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:s.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,_.assertNever)(r.sessionState)}})).add((0,_.merge)((0,_.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,_.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,_.map)(r=>r.castState)),(0,_.observableFrom)([i.getCastState()])).pipe((0,_.filterChanged)(),(0,_.map)(En),(0,_.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o;let a=r==="CONNECTED",s=(0,_.isNonNullable)(this.connection$.getValue());if(a&&!s){let u=i.getCurrentSession();(0,_.assertNonNullable)(u);let d=u.getCastDevice(),l=(o=u.getMediaSession())==null?void 0:o.media.contentId;((0,_.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,_.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:_.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},En=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,_.assertNever)(n)}};var Or=require("@vkontakte/videoplayer-shared");var he=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Or.assertNever)(t)}return n},Nr=(n,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(n);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(n);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Or.assertNever)(e)}};var P=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};var Fe=require("@vkontakte/videoplayer-shared"),G=class{constructor(e){this.transitionStarted$=new Fe.Subject;this.transitionEnded$=new Fe.Subject;this.transitionUpdated$=new Fe.Subject;this.forceChanged$=new Fe.Subject;this.stateChangeStarted$=(0,Fe.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Fe.merge)(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||(0,Fe.isNonNullable)(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}};var $a=require("@vkontakte/videoplayer-shared"),Ra=n=>{switch(n){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":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(0,$a.assertNever)(n)}};var w=require("@vkontakte/videoplayer-shared");var xn=5,Pn=5,kn=500,Da=7e3,Yt=class{constructor(e){this.subscription=new w.Subscription;this.loadMediaTimeoutSubscription=new w.Subscription;this.videoState=new G("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,w.assertNever)(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:(0,w.assertNever)(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:(0,w.assertNever)(e)}break}default:(0,w.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Ra(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 w.Subscription;this.subscription.add(e),this.subscription.add((0,w.merge)(this.videoState.stateChangeStarted$.pipe((0,w.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,w.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new w.Subject;e.add(r.pipe((0,w.debounce)(kn)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>xn)&&r.next(o),a=o})),e.add((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Pn&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:(0,w.assertNever)(s)}}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,w.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,w.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,w.observableFrom)(["init"])).pipe((0,w.debounce)(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var d;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];(0,w.assertNonNullable)(l);let c=(0,w.getHighestQuality)(Object.keys(l));(0,w.assertNonNullable)(c);let h=l[c];(0,w.assertNonNullable)(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,w.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let l=t[e];(0,w.assertNonNullable)(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,w.assertNonNullable)(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,w.assertNonNullable)(l),i=he(l.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:w.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,w.assertNever)(e)}let s=new chrome.cast.media.MediaInfo((d=this.params.meta.videoId)!=null?d:i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,w.isNonNullable)(o)&&(s.metadata.title=o),(0,w.isNonNullable)(u)&&(s.metadata.subtitle=u),s}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add((0,w.timeout)(Da).subscribe(()=>a(`timeout(${Da})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:w.ErrorCategory.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var qt=n=>{n.removeAttribute("src"),n.load()};var Ma=n=>{try{n.pause(),n.playbackRate=0,qt(n),n.remove()}catch(e){console.error(e)}};var _r=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)}},Fr=window.WeakMap?new WeakMap:new _r,Se=n=>{let e=n.querySelector("video"),t=!!e;return e?qt(e):(e=document.createElement("video"),n.appendChild(e)),Fr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ve=n=>{let e=Fr.get(n);Fr.delete(n),e?qt(n):Ma(n)};var L=require("@vkontakte/videoplayer-shared");var ot=require("@vkontakte/videoplayer-shared"),Zi=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=(0,ot.isNullable)(r),d=new ot.Subscription;return r&&d.add(r.subscribe(l=>{let c=n.getState();i(l,c)&&n.setState(l)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),u&&n.setState(l.to)},a)),d},Ue=(n,e,t)=>Zi(e,()=>n.loop,i=>{(0,ot.isNonNullable)(i)&&(n.loop=i)},{onError:t}),ye=(n,e,t,i)=>Zi(e,()=>({muted:n.muted,volume:n.volume}),r=>{(0,ot.isNonNullable)(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Le=(n,e,t,i)=>Zi(e,()=>n.playbackRate,r=>{(0,ot.isNonNullable)(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),ut=Zi;var An=n=>["__",n.language,n.label].join("|"),wn=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Ur=class n{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ut(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{(0,L.isNonNullable)(a)&&this.setInternal(a)},{equal:(a,s)=>(0,L.isNonNullable)(a)&&(0,L.isNonNullable)(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe((0,L.map)(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(ut(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{(0,L.isNonNullable)(a)&&this.setExternal(a)},{equal:(a,s)=>(0,L.isNonNullable)(a)&&(0,L.isNonNullable)(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe((0,L.map)(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(ut(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ut(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,L.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,L.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,L.filterChanged)()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(i=>{var a,s;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var d,l,c,h,m;let u=(l=(d=o.target)==null?void 0:d.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(m=o.target)==null||m.removeEventListener("cuechange",r))};(s=i.track)==null||s.addEventListener("cuechange",r)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,L.isNonNullable)(t.align)&&(r.align=t.align),(0,L.isNonNullable)(t.position)&&(r.position=t.position),(0,L.isNonNullable)(t.size)&&(r.size=t.size),(0,L.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:i}=e,r=e.id?e.id:An(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:(o=this.externalTracks.get(r))==null?void 0:o.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:(u=this.internalTracks.get(r))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!wn(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){(0,L.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,L.assertNonNullable)(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)}},$e=Ur;var qe=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 Ca=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Hr=n=>{let e=Ca(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Ba=n=>{let e=Ca(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};var k=require("@vkontakte/videoplayer-shared");var Ln=3,Va=(n,e,t=Ln)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var Te=n=>{let e=I=>(0,k.fromEvent)(n,I).pipe((0,k.mapTo)(void 0)),i=(0,k.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,k.fromEvent)(n,I))).pipe((0,k.map)(I=>I.type==="ended"?n.readyState<2:n.readyState<3),(0,k.debounce)(100),(0,k.filterChanged)()),r=(0,k.merge)((0,k.fromEvent)(n,"progress"),(0,k.fromEvent)(n,"timeupdate")).pipe((0,k.map)(()=>Va(n.buffered,n.currentTime))),s=(0,k.getCurrentBrowser)().browser===k.CurrentClientBrowser.Safari?(0,k.combine)({play:e("play").pipe((0,k.once)()),playing:e("playing")}).pipe((0,k.mapTo)(void 0)):e("playing"),o=(0,k.fromEvent)(n,"volumechange").pipe((0,k.map)(()=>({muted:n.muted,volume:n.volume}))),u=(0,k.fromEvent)(n,"ratechange").pipe((0,k.map)(()=>n.playbackRate)),d=(0,k.fromEvent)(n,"error").pipe((0,k.filter)(()=>!!(n.error||n.played.length)),(0,k.map)(()=>{var E;let I=n.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:k.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(E=n.error)!=null?E:void 0}})),l=(0,k.fromEvent)(n,"timeupdate").pipe((0,k.map)(()=>n.currentTime)),c=new k.Subject,h=.3,m;l.subscribe(I=>{n.loop&&(0,k.isNonNullable)(m)&&(0,k.isNonNullable)(I)&&m>=n.duration-h&&I<=h&&c.next(m),m=I});let f=e("pause").pipe((0,k.filter)(()=>!n.error&&m!==n.duration)),b=(0,k.fromEvent)(n,"enterpictureinpicture"),y=(0,k.fromEvent)(n,"leavepictureinpicture"),T=new k.ValueSubject(Ba(n));b.subscribe(()=>T.next(!0)),y.subscribe(()=>T.next(!1));let g=new k.ValueSubject(Hr(n));return(0,k.fromEvent)(n,"fullscreenchange").pipe((0,k.map)(()=>Hr(n))).subscribe(g),{playing$:s,pause$:f,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,k.fromEvent)(n,"durationchange").pipe((0,k.map)(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:g}};var ze=require("@vkontakte/videoplayer-shared"),dt=n=>{switch(n){case"mobile":return ze.VideoQuality.Q_144P;case"lowest":return ze.VideoQuality.Q_240P;case"low":return ze.VideoQuality.Q_360P;case"sd":case"medium":return ze.VideoQuality.Q_480P;case"hd":case"high":return ze.VideoQuality.Q_720P;case"fullhd":case"full":return ze.VideoQuality.Q_1080P;case"quadhd":case"quad":return ze.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return ze.VideoQuality.Q_2160P}};var H=require("@vkontakte/videoplayer-shared");var Gr=!1,Ke={},Oa=n=>{Gr=n},Na=()=>{Ke={}},_a=n=>{n(Ke)},zt=(n,e)=>{var t;Gr&&(Ke.meta=(t=Ke.meta)!=null?t:{},Ke.meta[n]=e)},be=class{constructor(e){this.name=e}next(e){var i,r;if(!Gr)return;Ke.series=(i=Ke.series)!=null?i:{};let t=(r=Ke.series[this.name])!=null?r:[];t.push([Date.now(),e]),Ke.series[this.name]=t}};var $n=new be("best_bitrate"),Rn=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t,er=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,H.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Dn='Assertion "ABR Tracks is empty array" failed',Mn=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var Z,O,R,ee,se;(0,H.assertNotEmptyArray)(n,Dn);let h=i.usePixelRatio&&(Z=window.devicePixelRatio)!=null?Z:1,m=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*i.containerSizeFactor,height:e.height*h*i.containerSizeFactor},f=m&&(0,H.videoSizeToQuality)(m),b=i.considerPlaybackRate&&(0,H.isNonNullable)(o)?o:1,y=n.filter(M=>!(0,H.isInvariantQuality)(M.quality)).sort((M,A)=>(0,H.isHigher)(M.quality,A.quality)?-1:1),T=(O=y.at(-1))==null?void 0:O.quality,g=(R=y.at(0))==null?void 0:R.quality,D=(0,H.isNullable)(r)||(0,H.isNonNullable)(r.min)&&(0,H.isNonNullable)(r.max)&&(0,H.isLower)(r.max,r.min)||(0,H.isNonNullable)(r.min)&&g&&(0,H.isHigher)(r.min,g)||(0,H.isNonNullable)(r.max)&&T&&(0,H.isLower)(r.max,T),I=b*Rn(s!=null?s:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},W=y.filter(M=>(f?(0,H.isLower)(M.quality,f):!0)?((0,H.isNonNullable)(t)&&isFinite(t)&&(0,H.isNonNullable)(M.bitrate)?t-a>=M.bitrate*I:!0)?i.lazyQualitySwitch&&(0,H.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,H.isInvariantQuality)(u.quality)&&(s!=null?s:0)<i.minBufferToSwitchUp&&(0,H.isHigher)(M.quality,u.quality)?(E[M.quality]="Buffer",!1):!!l&&(0,H.isHigherOrEqual)(M.quality,l)?(E[M.quality]="DroppedFramesLimit",!1):D||((0,H.isNullable)(r.max)||(0,H.isLowerOrEqual)(M.quality,r.max))&&((0,H.isNullable)(r.min)||(0,H.isHigherOrEqual)(M.quality,r.min))?!0:(E[M.quality]="FitsQualityLimits",!1):(E[M.quality]="FitsThroughput",!1):(E[M.quality]="FitsContainer",!1))[0];W&&W.bitrate&&$n.next(W.bitrate);let Q=(ee=W!=null?W:y[Math.ceil((y.length-1)/2)])!=null?ee:n[0];Q.quality!==((se=d==null?void 0:d.last)==null?void 0:se.quality)&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
|
-
${n.map(
|
|
8
|
+
${n.map(M=>`{ id: ${M.id}, quality: ${M.quality}, bitrate: ${M.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(i!=null?i:{}).map(([
|
|
12
|
+
${Object.entries(i!=null?i:{}).map(([M,A])=>`${M}: ${A}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
@@ -21,20 +21,20 @@
|
|
|
21
21
|
forwardBufferHealth: ${s},
|
|
22
22
|
bitrateFactor: ${I},
|
|
23
23
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
24
|
-
droppedVideoMaxQualityLimit: ${
|
|
25
|
-
limitsAreInvalid: ${
|
|
24
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
25
|
+
limitsAreInvalid: ${D},
|
|
26
26
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
27
27
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(E).map(([
|
|
30
|
+
${Object.entries(E).map(([M,A])=>`${M}: ${A}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
33
|
[best track] ${W==null?void 0:W.quality}
|
|
34
34
|
[selected track] ${Q==null?void 0:Q.quality}
|
|
35
|
-
`});let te=Q&&d&&d.history[Q.id]&&(0,
|
|
36
|
-
[last selected] ${
|
|
37
|
-
`}),D}return d==null||d.recordSwitch(Q),Q},dt=kn;var ce=n=>new URL(n).hostname;var O=require("@vkontakte/videoplayer-shared");var Ma=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},Ie=n=>V(void 0,null,function*(){let e=n.muted;try{yield n.play()}catch(t){if(!Ma(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{yield n.play()}catch(i){return Ma(i)&&(n.muted=!1,console.warn(i)),!1}}return!0});var Pe=require("@vkontakte/videoplayer-shared");var Ue=require("@vkontakte/videoplayer-shared");function pe(){return(0,Ue.now)()}function _r(n){return pe()-n}function Nr(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Ca(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Mt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,c,l,h=!1,m="arraybuffer",f=7e3,b=2e3,v=()=>{if(u)return;(0,Ue.assertNonNullable)(c);let $=_r(c),ee;if($<b){ee=b-$,setTimeout(v,ee);return}b*=2,b>f&&(b=f),s&&s.abort(),s=new r,Y()},T=$=>(a=$,B),g=$=>(l=$,B),_=()=>(m="json",B),I=()=>{if(!u){if(--d>=0){v(),i&&i();return}u=!0,l&&l(),t&&t()}},E=$=>(h=$,B),Y=()=>{c=pe(),s=new r,s.open("get",n);let $=0,ee,se=0,D=()=>((0,Ue.assertNonNullable)(c),Math.max(c,Math.max(ee||0,se||0)));if(a&&s.addEventListener("progress",k=>{let J=pe();a.updateChunk&&k.loaded>$&&(a.updateChunk(D(),k.loaded-$),$=k.loaded,ee=J)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>I())),s.addEventListener("load",()=>{if(u)return;(0,Ue.assertNonNullable)(s);let k=s.status;if(k>=200&&k<300){if(s.response.byteLength&&a){let J=s.response.byteLength-$;J&&a.updateChunk&&a.updateChunk(D(),J)}s.responseType==="json"&&!Object.values(s.response).length?I():(l&&l(),e(s.response))}else I()}),s.addEventListener("error",()=>{I()}),h){let k=()=>{(0,Ue.assertNonNullable)(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(se=pe(),s.removeEventListener("readystatechange",k))};s.addEventListener("readystatechange",k)}return s.responseType=m,s.send(),B},B={withBitrateReporting:T,withParallel:E,withJSONResponse:_,withRetryCount:$=>(d=$,B),withRetryInterval:($,ee)=>((0,Ue.isNonNullable)($)&&(b=$),(0,Ue.isNonNullable)(ee)&&(f=ee),B),withTimeout:$=>(o=$,B),withFinally:g,send:Y,abort:()=>{s&&(s.abort(),s=void 0),u=!0,l&&l()}};return B}var qt=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var zt=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=pe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Mt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=pe()}_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=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Ji=1e4,Fr=3;var wn=6e4,Ln=10,$n=1,Rn=500,Kt=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new qt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Nr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Nr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Pe.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{Ca(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zt(Fr,Ji,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,d=null,c=!1,l=()=>{let I=a&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,E,Y)=>{u&&u.abort(),u=Mt(this.urlResolver.resolve(I,!1),E,Y,()=>this._retryCallback()).withTimeout(Ji).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Fr).withFinally(()=>{u=null}).send()},m=(I,E,Y)=>{(0,Pe.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,Y,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),i.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let Y=pe()-1e4,W=0;for(let te=0;te<this.bufferStates.length;te++){let Z=this.bufferStates[te];I=Math.min(I,Z.buf),Z.ts<Y&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${I} drop=${W} jitter=${this.sourceJitter}`);let Q=I-$n;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?f(1.15):Q>1?f(1.1):Q>.3?f(1.05):f(1)}},T=I=>{let E,Y=()=>E&&E.start?E.start.length:0,W=k=>E.start[k]/1e3,Q=k=>E.dur[k]/1e3,te=k=>E.fragIndex+k,Z=(k,J)=>({chunkIdx:te(k),startTS:W(k),dur:Q(k),discontinuity:J}),B=()=>{let k=0;if(E&&E.dur){let J=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ne=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,de=J;this.sourceJitter>1&&(de+=this.sourceJitter-1);let me=E.dur.length-1;for(;me>=0&&(de-=E.dur[me],!(de<=0));--me);k=Math.min(me,E.dur.length-1-ne),k=Math.max(k,0)}return Z(k,!0)},$=k=>{let J=Y();if(!(J<=0)){if((0,Pe.isNonNullable)(k)){for(let ne=0;ne<J;ne++)if(W(ne)>k)return Z(ne)}return B()}},ee=k=>{let J=Y(),ne=k?k.chunkIdx+1:0,de=ne-E.fragIndex;if(!(J<=0)){if(!k||de<0||de-J>Ln)return t(`Resync: offset=${de} bChunks=${J} chunk=`+JSON.stringify(k)),B();if(!(de>=J))return Z(ne-E.fragIndex,!1)}},se=(k,J,ne)=>{d&&d.abort(),d=Mt(this.urlResolver.resolve(k,!0,this.lowLatency),J,ne,()=>this._retryCallback()).withTimeout(Ji).withRetryCount(Fr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,J)=>{se(I,ne=>{if(!l())return;E=ne;let de=!!E.lowLatency;de!==this.lowLatency&&b(de);let me=0;for(let Qe=0;Qe<E.dur.length;++Qe)me+=E.dur[Qe];me>0&&((0,Pe.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(me/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,k($(J))},()=>this._handleNetworkError())},nextChunk:ee}},g=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),(0,Pe.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:Y}=this.params,W=T(e.jidxUrl),Q,te,Z,B,$=0,ee,se,D,k=()=>{ee&&(clearTimeout(ee),ee=void 0);let z=Math.max(Rn,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=$+z,xe=pe(),ke=Math.min(1e4,be-xe);$=xe;let tt=()=>{d||l()&&W.seek(()=>{l()&&($=pe(),J(),k())})};ke>0?ee=window.setTimeout(()=>{this.paused?k():tt()},ke):tt()},J=()=>{let z;for(;z=W.nextChunk(B);)B=z,_i(z);let be=W.nextChunk(Z);if(be){if(Z&&be.discontinuity){Y("Detected discontinuity; restarting playback"),this.paused?k():(g(),this._initPlayerWith(e));return}Qe(be)}else k()},ne=(z,be)=>{if(!l()||!this.sourceBuffer)return;let xe,ke,tt,wt=it=>{window.setTimeout(()=>{l()&&ne(z,be)},it)};if(this.sourceBuffer.updating)Y("Source buffer is updating; delaying appendBuffer"),wt(100);else{let it=pe(),pt=E.currentTime;!this.paused&&E.buffered.length>1&&se===pt&&it-D>500&&(Y("Stall suspected; trying to fix"),this._fixupStall()),se!==pt&&(se=pt,D=it);let Lt=this._getBufferSizeSec();if(Lt>30)Y(`Buffered ${Lt} seconds; delaying appendBuffer`),wt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:it,buf:Lt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(Ft){if(Ft.name==="QuotaExceededError")Y("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(xe=this.sourceBuffer.buffered.start(0),ke=pt,ke-xe>4&&this.sourceBuffer.remove(xe,ke-3)),wt(1e3);else throw Ft}}},de=()=>{te&&Q&&(Y([`Appending chunk, sz=${te.byteLength}:`,JSON.stringify(Z)]),ne(te,function(){te=null,J()}))},me=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),Qe=z=>{l()&&m(me(z),(be,xe)=>{if(l()){if(xe/=1e3,te=be,Z=z,s=z.startTS,xe){let ke=Math.min(10,z.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}de()}},()=>this._handleNetworkError())},_i=z=>{l()&&((0,Pe.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(me(z),!1)))},Nt=z=>{l()&&(e.cachedHeader=z,ne(z,()=>{Q=!0,de()}))};a=!0,W.seek(z=>{if(l()){if($=pe(),!z){k();return}B=z,!(0,Pe.isNullable)(I)||z.startTS>I?Qe(z):(Z=z,J())}},I),e.cachedHeader?Nt(e.cachedHeader):h(e.headerUrl,Nt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>s},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Pe.isNonNullable)(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,(0,Pe.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Pe.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let h,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(m=this._getBufferSizeSec(),f=l/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}h=this._selectQuality(l),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${l}`)},a=(()=>({updateChunk:(h,m)=>{let f=pe();if(this.chunkRateEstimator.addInterval(h,f,m)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-h,speed:v}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))(),s=-1/0,o,u=!0,d=()=>{let l=a.get();if(l&&o&&this.autoQuality){if(u&&l>o&&_r(s)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,h)=>{let m=a.updateChunk(l,h);return m&&d(),m},notifySwitch:l=>{let h=pe();l<o&&(s=h),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=Mt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ji).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).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s!=null&&s.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},wn))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ae=require("@vkontakte/videoplayer-shared"),Ur=class{constructor(){this.onDroopedVideoFramesLimit$=new ae.Subject;this.subscription=new ae.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ae.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ae.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var s;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,ae.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((s=this.limitCounts[this.currentQuality])!=null?s:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ae.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ae.interval)(this.droppedFramesChecker.checkTime).pipe((0,ae.filter)(()=>this.playing),(0,ae.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ae.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ae.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[s])=>(0,ae.isLower)(a,s)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Xi=Ur;var Zi=require("@vkontakte/videoplayer-shared"),Ba=require("@vkontakte/videoplayer-shared");var Jt=()=>{var n;return!!((n=window.documentPictureInPicture)!=null&&n.window)||!!document.pictureInPictureElement};var Dn=(n,e)=>new Zi.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Jt()))},M(M({},i),e));r.observe(n);let a=(0,Ba.fromEvent)(document,"visibilitychange").pipe((0,Zi.map)(s=>!document.hidden||Jt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),$e=Dn;var Mn=["paused","playing","ready"],Cn=["paused","playing","ready"],Xt=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new G("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new Le;this.droppedFramesManager=new Xi;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new je;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let s=e.isBuffering;this.params.output.isBuffering$.next(s);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let s=e.manifest,o=[];for(let u of s){let d=(t=u.name)!=null?t:u.index.toString(10),c=(i=ut(u.name))!=null?i:(0,O.videoSizeToQuality)(u.video),l=u.bitrate/1e3,h=M({},u.video);if(!c)continue;let m={id:d,quality:c,bitrate:l,size:h};o.push({track:m,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let s=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===s))==null?void 0:a.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:s,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(s,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Cn.includes(e)&&(s||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&Mn.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(he(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Se(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Te(this.video);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$:this.representations$.pipe((0,O.map)(r=>r.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Fe(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(we(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add($e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&(0,O.videoQualityToHeight)(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(r.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(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 Kt({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var d,c,l,h,m,f;let e=this.representations$.getValue(),t=(c=(d=this.params.desiredState.videoTrack.getTransition())==null?void 0:d.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(h=(l=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:l.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,O.isNonNullable)(t)?t:dt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,s=this.params.desiredState.videoTrack.getTransition(),o=(m=this.params.desiredState.videoTrack.getState())==null?void 0:m.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let b=(f=e.find(({track:v})=>v.id===a))==null?void 0:f.representation;(0,O.assertNonNullable)(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(he(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var Va=Xt;var ze=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var R=require("@vkontakte/videoplayer-shared");var Zt=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var Re=require("@vkontakte/videoplayer-shared");var Bn=16,Na=!1,Oa,_a;try{Na=(0,Re.getCurrentBrowser)().browser===Re.CurrentClientBrowser.Safari&&parseInt((_a=(Oa=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Oa[1])!=null?_a:"",10)<=Bn}catch(n){console.error(n)}var Hr=class{constructor(e){this.bufferFull$=new Re.Subject;this.error$=new Re.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Re.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return V(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return V(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return V(this,null,function*(){return new Promise(t=>{let i;Na&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Re.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Re.assertNever)(t)}}},Fa=Hr;var Gr=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Ct=class extends K{};var ei=class extends K{};var ti=class extends K{constructor(t,i){super(t,i);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var ii=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ri=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends K{constructor(t,i){super(t,i);this.data=this.content}};var oe=class extends K{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var gt=class extends oe{constructor(t,i){super(t,i);this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,o=a<<1>>>1,u=this.readUint32();a=this.readUint32();let d=a>>>28,c=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:o,subsegmentDuration:u,SAPType:d,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var si=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oi=class extends oe{constructor(t,i){super(t,i);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ui=class extends oe{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var di=class extends oe{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var li=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends oe{constructor(t,i){super(t,i);this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var pi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends oe{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var fi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends oe{constructor(t,i){super(t,i);this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var gi=class extends oe{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Si=class extends oe{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 On={ftyp:ti,moov:ii,moof:ri,mdat:ai,sidx:gt,trak:si,mdia:li,mfhd:mi,tkhd:ci,traf:fi,tfhd:bi,tfdt:gi,trun:Si,minf:pi,sv3d:ni,st3d:oi,prhd:ui,proj:hi,equi:di,uuid:ei,unknown:Ct},St=class n{constructor(e={}){this.options=M({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch(r){break}return t}createBox(e,t){let i=On[e];return i?new i(t,new n):new Ct(t,new n)}};var Bt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Nn=new TextDecoder("ascii"),Fn=n=>Nn.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Un=n=>{let e=new gt(n,new St),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},Hn=(n,e)=>{let i=new St().parse(n),r=new Bt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,l)},Gn=(n,e)=>{let i=new St().parse(n),a=new Bt(i).findAll("traf"),s=a[a.length-1].children.find(l=>l.type==="tfhd"),o=a[a.length-1].children.find(l=>l.type==="tfdt"),u=a[a.length-1].children.find(l=>l.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((l,h)=>l+h,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},Qn=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new St().parse(n),r=new Bt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Ua={validateData:Fn,parseInit:Qn,getIndexRange:()=>{},parseSegments:Un,parseFeedableSegmentChunk:Hn,getSegmentEndTime:Gn};var Ke=require("@vkontakte/videoplayer-shared");var Ga=require("@vkontakte/videoplayer-shared");var Ha={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"}},Qa=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=vi(n,t),r=i in Ha,a=r?Ha[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,c=vi(u),l=d*_e(2,(o-1)*8)+c,h=t+o,m;return h+l>n.byteLength?m=new DataView(n.buffer,n.byteOffset+h):m=new DataView(n.buffer,n.byteOffset+h,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+l,value:m,valueSize:l}},vi=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*_e(2,16)+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*_e(2,32)+n.getUint32(1);case 6:return n.getUint16(0)*_e(2,32)+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Be=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return vi(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:(0,Ga.assertNever)(e)}},vt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Qa(i);if(!e(r))return;r.type==="master"&&vt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Wa=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Qa(n);return vt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=Be(o,s):a===17026?t=Be(o,s):a===17029&&(i=Be(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var ja=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Wn=[231,22612,22743,167,171,163,160,175],jn=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,c=!1,l=0;return vt(n,({tag:h,type:m,value:f,valueSize:b})=>{if(h===21419){let v=Be(f,m);d=vi(v)}else h!==21420&&(d=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?a=!0:h===290298740?s=!0:h===2807729?i=Be(f,m):h===17545?r=Be(f,m):h===21420&&d===475249515?u=Be(f,m):h===374648427?vt(f,({tag:v,type:T,value:g})=>v===30321?(c=Be(g,T)===1,!1):!0):a&&s&&ja.includes(h)&&(o=!0),!o}),(0,Ke.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ke.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ke.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Yn=n=>{if((0,Ke.isNullable)(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},qn=(n,e)=>{let t=!1,i=!1,r=o=>(0,Ke.isNonNullable)(o.time)&&(0,Ke.isNonNullable)(o.position),a=[],s;return vt(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Be(d,u));break;case 183:break;case 241:s&&(s.position=Be(d,u));break;default:t&&ja.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:c}=o,l=a[u+1];return{status:"none",time:{from:d,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},zn=n=>{let e=0,t=!1;try{vt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Wn.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},Ya={validateData:Wa,parseInit:jn,getIndexRange:Yn,parseSegments:qn,parseFeedableSegmentChunk:zn};var Vt=require("@vkontakte/videoplayer-shared");var qa=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var za=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},yt=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>(0,Vt.isNullable)(a)?o:(0,Vt.isNullable)(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Ja=(n,e)=>{var I,E,Y,W,Q,te,Z,B,$,ee,se,D,k,J,ne,de,me,Qe,_i,Nt,z,be,xe,ke,tt,wt,it,pt,Lt,Ft,ea,ta,ia,ra,aa,sa,na,oa,ua,da,la,ca;let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=(Y=(E=(I=a.querySelector("BaseURL"))==null?void 0:I.textContent)==null?void 0:E.trim())!=null?Y:"",u=s.children,d=a.getAttribute("type")==="dynamic",c=a.getAttribute("availabilityStartTime"),l=c?new Date(c).getTime():void 0,h,m=a.getAttribute("mediaPresentationDuration"),f=s.getAttribute("duration"),b=a.getElementsByTagName("vk:Attrs")[0],v=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=za(m);else if(f){let Ae=za(f);(0,Vt.isNonNullable)(Ae)&&(h=Ae)}else v&&(h=parseInt(v,10));let T=0,g=(Q=(W=a.getAttribute("profiles"))==null?void 0:W.split(","))!=null?Q:[],_=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let Ae of u){let Ni=Ae.getAttribute("mimeType"),Qs=Ae.getAttribute("codecs"),pa=(te=Ae.getAttribute("contentType"))!=null?te:Ni==null?void 0:Ni.split("/")[0],Ws=(B=(Z=Ae.getAttribute("profiles"))==null?void 0:Z.split(","))!=null?B:[],ha=Ae.querySelectorAll("Representation"),js=Ae.querySelector("SegmentTemplate");if(pa==="text"){for(let ue of ha){let rt=ue.getAttribute("id")||"",Fi=Ae.getAttribute("lang"),$t=Ae.getAttribute("label"),yr=(se=(ee=($=ue.querySelector("BaseURL"))==null?void 0:$.textContent)==null?void 0:ee.trim())!=null?se:"",Tr=new URL(yr||o,e).toString(),Ui=rt.includes("_auto");r.text.push({id:rt,lang:Fi,label:$t,isAuto:Ui,kind:"text",url:Tr})}continue}for(let ue of ha){let rt=(D=ue.getAttribute("mimeType"))!=null?D:Ni,Fi=(J=(k=ue.getAttribute("codecs"))!=null?k:Qs)!=null?J:"",$t=(de=(ne=ue.getAttribute("contentType"))!=null?ne:rt==null?void 0:rt.split("/")[0])!=null?de:pa,yr=(Qe=(me=Ae.getAttribute("profiles"))==null?void 0:me.split(","))!=null?Qe:[],Tr=parseInt((_i=ue.getAttribute("width"))!=null?_i:"",10),Ui=parseInt((Nt=ue.getAttribute("height"))!=null?Nt:"",10),ma=parseInt((z=ue.getAttribute("bandwidth"))!=null?z:"",10)/1e3,fa=(be=ue.getAttribute("frameRate"))!=null?be:"",Ys=(xe=ue.getAttribute("quality"))!=null?xe:void 0,qs=fa?qa(fa):void 0,zs=(ke=ue.getAttribute("id"))!=null?ke:(T++).toString(10),Ks=$t==="video"?`${Ui}p`:$t==="audio"?`${ma}Kbps`:Fi,Js=`${zs}@${Ks}`,Xs=(it=(wt=(tt=ue.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:wt.trim())!=null?it:"",ba=new URL(Xs||o,e).toString(),Zs=[...g,...Ws,...yr],Ir,en=ue.querySelector("SegmentBase"),ht=(pt=ue.querySelector("SegmentTemplate"))!=null?pt:js;if(en){let mt=(Ft=(Lt=ue.querySelector("SegmentBase Initialization"))==null?void 0:Lt.getAttribute("range"))!=null?Ft:"",[ft,xr]=mt.split("-").map(Rt=>parseInt(Rt,10)),at={from:ft,to:xr},Ut=(ea=ue.querySelector("SegmentBase"))==null?void 0:ea.getAttribute("indexRange"),[Pr,Hi]=Ut?Ut.split("-").map(Rt=>parseInt(Rt,10)):[],Ht=Ut?{from:Pr,to:Hi}:void 0;Ir={type:"byteRange",url:ba,initRange:at,indexRange:Ht}}else if(ht){let mt={representationId:(ta=ue.getAttribute("id"))!=null?ta:void 0,bandwidth:(ia=ue.getAttribute("bandwidth"))!=null?ia:void 0},ft=parseInt((ra=ht.getAttribute("timescale"))!=null?ra:"",10),xr=(aa=ht.getAttribute("initialization"))!=null?aa:"",at=ht.getAttribute("media"),Ut=(na=parseInt((sa=ht.getAttribute("startNumber"))!=null?sa:"",10))!=null?na:1,Pr=yt(xr,mt);if(!at)throw new ReferenceError("No media attribute in SegmentTemplate");let Hi=(oa=ht.querySelectorAll("SegmentTimeline S"))!=null?oa:[],Ht=[],Rt=0,kr="",Ar=0;if(Hi.length){let Gi=Ut,Ce=0;for(let Dt of Hi){let Oe=parseInt((ua=Dt.getAttribute("d"))!=null?ua:"",10),bt=parseInt((da=Dt.getAttribute("r"))!=null?da:"",10)||0,Qi=parseInt((la=Dt.getAttribute("t"))!=null?la:"",10);Ce=Number.isFinite(Qi)?Qi:Ce;let wr=Oe/ft*1e3,Lr=Ce/ft*1e3;for(let Wi=0;Wi<bt+1;Wi++){let rn=yt(at,q(M({},mt),{segmentNumber:Gi.toString(10),segmentTime:(Ce+Wi*Oe).toString(10)})),ga=(Lr!=null?Lr:0)+Wi*wr,an=ga+wr;Gi++,Ht.push({time:{from:ga,to:an},url:rn})}Ce+=(bt+1)*Oe,Rt+=(bt+1)*wr}Ar=Ce/ft*1e3,kr=yt(at,q(M({},mt),{segmentNumber:Gi.toString(10),segmentTime:Ce.toString(10)}))}else if((0,Vt.isNonNullable)(h)){let Ce=parseInt((ca=ht.getAttribute("duration"))!=null?ca:"",10)/ft*1e3,Dt=Math.ceil(h/Ce),Oe=0;for(let bt=1;bt<Dt;bt++){let Qi=yt(at,q(M({},mt),{segmentNumber:bt.toString(10),segmentTime:Oe.toString(10)}));Ht.push({time:{from:Oe,to:Oe+Ce},url:Qi}),Oe+=Ce}Ar=Oe,kr=yt(at,q(M({},mt),{segmentNumber:Dt.toString(10),segmentTime:Oe.toString(10)}))}let tn={time:{from:Ar,to:1/0},url:kr};Ir={type:"template",baseUrl:ba,segmentTemplateUrl:at,initUrl:Pr,totalSegmentsDurationMs:Rt,segments:Ht,nextSegmentBeyondManifest:tn,timescale:ft}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$t||!rt)continue;let Er={video:"video",audio:"audio",text:"text"}[$t];Er&&r[Er].push({id:Js,kind:Er,segmentReference:Ir,profiles:Zs,duration:h,bitrate:ma,mime:rt,codecs:Fi,width:Tr,height:Ui,fps:qs,quality:Ys})}}return{dynamic:d,liveAvailabilityStartTime:l,duration:h,container:_,representations:r}};var Xa=require("@vkontakte/videoplayer-shared"),Za=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var o;let s=(o=a?ut(a):void 0)!=null?o:(0,Xa.videoSizeToQuality)({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},es=({id:n,bitrate:e})=>({id:n,bitrate:e}),ts=(n,e,t)=>{var r;let i=e.indexOf(t);return(r=n.at(Math.round(n.length*i/e.length)))!=null?r:n.at(-1)},is=({id:n,lang:e,label:t,url:i,isAuto:r})=>({id:n,url:i,isAuto:r,type:"internal",language:e,label:t}),er=n=>"url"in n,Tt=n=>n.type==="template",yi=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Ti=class{constructor(e,t,i,r,{fetcher:a,tuning:s,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:c}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,x.abortable)(this.destroyAbortController.signal,function(e){return le(this,null,function*(){let t=this.representations.get(e);(0,x.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Fa(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>this.error$.next({id:"SegmentEjection",category:x.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:s}))),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Gr(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=ze(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,d<c)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,x.assertNonNullable)(i,"No init buffer for starting representation"),(0,x.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=(0,x.abortable)(this.destroyAbortController.signal,function(e){return le(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);(0,x.assertNonNullable)(t,`No such representation ${e}`);let i=this.segments.get(e),r=this.initData.get(e);if((0,x.isNullable)(r)||(0,x.isNullable)(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),(0,x.assertNonNullable)(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);let a=this.getCurrentPosition();(0,x.isNonNullable)(a)&&(this.isLive||(i.forEach(s=>s.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(a,1/0,!0)),this.maintain(a))})}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,function(e){return le(this,null,function*(){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let d=e.find(h=>h.id===u);d&&this.representations.set(u,d);let c=this.representations.get(u);if(!c||!Tt(c.segmentReference))return;let l=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,l)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,i=this.representations.get(t);(0,x.assertNonNullable)(i);let r=this.segments.get(t);(0,x.assertNonNullable)(r,"No segments for starting representation");let a=this.initData.get(t);if((0,x.assertNonNullable)(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let s=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),s&&(yield this.sourceBufferTaskQueue.remove(s.from*1e3,s.to*1e3,this.destroyAbortController.signal)),this.searchGaps(r,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));switch(this.fetcher=a,this.tuning=s,this.compatibilityMode=d,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=i,i){case"mp4":this.containerParser=Ua;break;case"webm":this.containerParser=Ya;break;default:(0,x.assertNever)(i)}this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var d,c;if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next(((d=r==null?void 0:r.time.to)!=null?d:0)-((c=r==null?void 0:r.time.from)!=null?c:0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=ze(this.sourceBuffer.buffered,e),m=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=r.time.to-e+100&&(a=m)}if(isFinite(this.bufferLimit)&&Gr(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ze(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{let h=o.at(0);h&&h.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=i.at(-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(let s of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!s||!Tt(s.segmentReference))return;let o=s.segmentReference.segments.map(l=>q(M({},l),{status:"none",size:void 0})),u=(i=this.segments.get(s.id))!=null?i:[],d=(a=(r=u.at(-1))==null?void 0:r.time.to)!=null?a:0,c=o==null?void 0:o.findIndex(l=>Math.floor(d)>=Math.floor(l.time.from)&&Math.floor(d)<=Math.floor(l.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(s.segmentReference);this.segments.set(s.id,l)}else{let l=o.slice(c+1);this.segments.set(s.id,[...u,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,x.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLive(i)}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let i of this.representations.values()){let r=i.segmentReference;if(!Tt(r))return;let a=Math.round(e.time.to*r.timescale/1e3).toString(10),s=yt(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(i.id))!=null?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.time.from));u&&(u.time.to=e.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.time.to))||o.push({status:"none",time:{from:e.time.to,to:1/0},url:s})}}findSegmentStartTime(e){var a,s,o;let t=(s=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?s:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:l,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,v=h>i||b||f===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&h<=i+T||m<=i+T;return(l==="none"||l==="partially_ejected"&&v&&g&&this.sourceBuffer&&!Zt(this.sourceBuffer.buffered,i))&&v&&g});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=r;l<a.length&&(s<=d||o<=c);l++){let h=a[l];if(s+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return V(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return V(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,x.abortable)(o,function(){return le(this,null,function*(){let c=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;let l=new DataView(c);if(this.isActiveLowLatency()){let h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(l,h)}u&&r.feedingBytes&&d?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(l,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),yi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,i="auto"){return V(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(yield(0,x.abortable)(s,function(){return le(this,null,function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),yi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Tt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Tt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,c)=>{if(!a.aborted)try{let l=this.onSomeTemplateDataLoaded({dataView:d,loaded:c,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(s){return V(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(d.status="partially_fed",u.feedingBytes+=l.byteLength,yield this.sourceBufferTaskQueue.append(l),u.fedBytes+=l.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let c=d.byte.from-i,l=d.byte.to-i,h=l-c+1,m=c<r,f=l<=r;if(m){if(d.status==="downloading"&&f){d.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,h);this.sourceBufferTaskQueue.append(b,a).then(v=>v&&!a.aborted?this.onSegmentFullyAppended(u,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(u.loadedBytes=Math.min(h,r-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===h?b:this.containerParser.parseFeedableSegmentChunk(b);v!=null&&v.byteLength&&(d.status="partially_fed",u.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,a).then(T=>{if(a.aborted)s();else if(T)u.fedBytes+=v.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t);else{if(u.feedingBytes<h)return;s()}}))}}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",er(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;t||(t=s),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return V(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,function(){return le(this,null,function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>V(this,null,function*(){if(!o)return;let{init:u,dataView:d,segments:c}=o,l=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,l);let h=c;this.isLive&&Tt(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,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s})}pruneBuffer(e,t,i=!1){return V(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)})}pruneBufferNew(e,t,i=!1){return V(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=o=>{var c;let u=!0;for(let l of r)Math.round(l.from)===Math.round(o.time.to)?(l.from=o.time.from,u=!1):Math.round(l.to)===Math.round(o.time.from)&&(l.to=o.time.to,u=!1);u&&r.push(o.time);let d=er(o)?(c=o.size)!=null?c:0:o.byte.to-o.byte.from;a+=d};for(let o of this.segments.values())for(let u of o){if(a>=t)break;let d=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&u.status==="fed"&&s(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,d=this.sourceBuffer.buffered.end(o)*1e3;for(let c of this.segments.values())for(let l of c)if(l.status==="none"&&Math.round(l.time.from)<=Math.round(u)&&Math.round(l.time.to)>=Math.round(d)){r.push({from:u,to:d});break}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let d of u)d.time.from>=e+o&&d.status==="fed"&&s(d)}return r.length?(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,d)=>u||d,!1):!1})}pruneBufferOld(e,t,i=!1){return V(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,u=d=>{var l;a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let c=er(d)?(l=d.size)!=null?l:0:d.byte.to-d.byte.from;r+=c};for(let d of this.segments.values())for(let c of d){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let c of d){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(a)&&isFinite(s),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let c=this.sourceBuffer.buffered.start(d)*1e3,l=this.sourceBuffer.buffered.end(d)*1e3;for(let h of this.segments.values())for(let m of h)if(m.status==="none"&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.time.to)>=Math.round(l)){a=c,s=l;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>e+d&&l.status==="fed"&&u(l)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=1;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=s&&c.to+t>=o),d=e.filter(c=>s>=c.from-t&&s<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var Ii=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var rs=n=>{var a;let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};var ie=require("@vkontakte/videoplayer-shared");var tr=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new ie.ValueSubject(void 0);this.lastConnectionReused$=new ie.ValueSubject(void 0);this.lastRequestFirstBytes$=new ie.ValueSubject(void 0);this.abortAllController=new AbortController;this.subscription=new ie.Subscription;this.fetchManifest=(0,ie.abortable)(this.abortAllController.signal,function(e){return le(this,null,function*(){let t=e;this.requestQuic&&(t=Ii(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(Ei);return i?(this.onHeadersReceived(i.headers),i.text()):null})}.bind(this));this.fetch=(0,ie.abortable)(this.abortAllController.signal,function(d){return le(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){var te,Z;let c=e,l=new Headers;if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let B=new URL(c,location.href);B.searchParams.append("bytes",`${i.from}-${i.to}`),c=B.toString();break}default:(0,ie.assertNever)(t)}this.requestQuic&&(c=Ii(c));let h=this.abortAllController.signal,m;if(s){let B=new AbortController;if(m=(0,ie.merge)((0,ie.fromEvent)(this.abortAllController.signal,"abort"),(0,ie.fromEvent)(s,"abort")).subscribe(()=>{try{B.abort()}catch($){Ei($)}}),this.abortAllController.signal.aborted||s.aborted)try{B.abort()}catch($){Ei($)}h=B.signal}let f=(0,ie.now)(),b=yield fetch(c,{priority:a,headers:l,signal:h}).catch(Ei),v=(0,ie.now)();if(!b)return m==null||m.unsubscribe(),null;if((te=this.throughputEstimator)==null||te.addRawRtt(v-f),!b.ok||!b.body)return m==null||m.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!r&&!o)return m==null||m.unsubscribe(),b.arrayBuffer();let[T,g]=b.body.tee(),_=T.getReader();o&&((Z=this.throughputEstimator)==null||Z.trackStream(g,u));let I=0,E=new Uint8Array(0),Y=!1,W=B=>{m==null||m.unsubscribe(),Y=!0,Ei(B)},Q=(0,ie.abortable)(h,function(ee){return le(this,arguments,function*({done:B,value:$}){if(I===0&&this.lastRequestFirstBytes$.next((0,ie.now)()-f),h.aborted){m==null||m.unsubscribe();return}if(!B&&$){let se=new Uint8Array(E.length+$.length);se.set(E),se.set($,E.length),E=se,I+=$.byteLength,r==null||r(new DataView(E.buffer),I),yield _==null?void 0:_.read().then(Q,W)}})}.bind(this));return yield _==null?void 0:_.read().then(Q,W),m==null||m.unsubscribe(),Y?null:E.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,ie.abortable)(this.abortAllController.signal,function(e,t,i){return le(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,d,c;e.indexRange&&(d=e.indexRange.from,c=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(c,a))),s=Math.min(s,0);let l=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!l)return null;let h=new DataView(l,r-s,a-s+1);if(!t.validateData(h))throw new Error("Invalid media file");let m=t.parseInit(h),f=(T=e.indexRange)!=null?T:t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(l,f.from-s,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let v=t.parseSegments(b,m,f);return{init:m,dataView:new DataView(l),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,ie.abortable)(this.abortAllController.signal,function(e,t){return le(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(s=>q(M({},s),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){let{type:t,reused:i}=rs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return V(this,null,function*(){var a,s;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(s=yield this.fetchTemplateRepresentation(e,i))!=null?s:null;default:(0,ie.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ei=n=>{if(!yi(n))throw n};var It=(n,e,t)=>t*e+(1-t)*n,jr=(n,e)=>n.reduce((t,i)=>t+i,0)/e,as=(n,e,t,i)=>{let r=0,a=t,s=jr(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};var xi=require("@vkontakte/videoplayer-shared");var lt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new xi.ValueSubject(e.initial),this.debounced$=new xi.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"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 o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=_e(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&((0,xi.isNullable)(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 ir=class extends lt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=It(this.slow,t,this.params.emaAlphaSlow),this.fast=It(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var rr=class extends lt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=jr(this.pastMeasures,this.takenMeasures);this.emaSmoothed=It(this.emaSmoothed,t,this.params.emaAlpha);let r=as(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var ar=class extends lt{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?It(this.smoothed,t,this.params.emaAlpha):t}};var Et=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ir({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new rr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ar(M({initial:e,label:"liveEdgeDelay"},t))}};var Yr=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var Je=()=>window.ManagedMediaSource||window.MediaSource,sr=()=>{var n,e;return!!(window.ManagedMediaSource&&((e=(n=window.ManagedSourceBuffer)==null?void 0:n.prototype)!=null&&e.appendBuffer))},ss=()=>{var n,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(n=window.SourceBuffer)==null?void 0:n.prototype)!=null&&e.appendBuffer))},ns=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var us=["timeupdate","progress","play","seeked","stalled","waiting"];var nr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new G("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new S.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=(0,S.abortable)(this.destroyController.signal,function(e,t,i){return le(this,null,function*(){var r;this.element=e,this.manifestUrlString=he(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,function(){return le(this,null,function*(){var r;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=Ja(e!=null?e:"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let i=({kind:a,mime:s,codecs:o})=>{var u,d,c,l;return!!((d=(u=this.element)==null?void 0:u.canPlayType)!=null&&d.call(u,s)&&((l=(c=Je())==null?void 0:c.isTypeSupported)!=null&&l.call(c,`${s}; codecs="${o}"`))||a==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((r=t.duration)!=null?r:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),q(M({},t),{representations:Object.fromEntries(Object.entries(t.representations).map(([a,s])=>[a,s.filter(i)]))})})}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,function(e,t,i){return le(this,null,function*(){var m;(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=f=>{this.representationSubscription.add((0,S.fromEvent)(f,"error").pipe((0,S.filter)(b=>{var v;return!!((v=this.element)!=null&&v.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?ns():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&sr())if(i){let f=document.createElement("source");r(f),f.type="application/x-mpegurl",f.src=i.url,this.element.appendChild(f)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest};if(this.videoBufferManager=new Ti("video",this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)&&(this.audioBufferManager=new Ti("audio",this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(f=>{var b;if((b=this.element)!=null&&b.paused){let v=Dr(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,v+1e3,2)}})),this.representationSubscription.add((0,S.merge)(...us.filter(f=>f!=="waiting").map(f=>(0,S.fromEvent)(this.element,f))).pipe((0,S.map)(f=>this.element?ze(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.filter)(f=>!!f),(0,S.tap)(f=>{var b;(b=this.stallWatchdogSubscription)==null||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(b=>Yr(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:b,isActiveLowLatency:v})=>v&&!!b)).subscribe(({bufferLength:b})=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add((0,S.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:b,isActiveLowLatency:v})=>{if(!v)return;let T=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,_=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=b-T,E=1;Math.abs(I)>g&&(E=1+Math.sign(I)*_),Yr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var T,g;let v=0;if(b){let _=((g=(T=this.element)==null?void 0:T.currentTime)!=null?g:0)*1e3;v=Math.min(...this.bufferManagers.map(E=>{var Y,W;return(W=(Y=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:Y.to)!=null?W:_}))-_}this.liveLoadBufferLength$.getValue()!==v&&this.liveLoadBufferLength$.next(v)}));let f=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(T=>V(this,[T],function*({liveLoadBufferLength:b,bufferLength:v}){if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,_=Dr(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),Y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,W=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,Q=isFinite(b)?b:v,te=this.isActiveLowLatency$.getValue(),Z=I<=this.tuning.live.activeLiveDelay&&_===0;this.isActiveLowLatency$.next(te&&Z);let B="none";if(te?B="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&Z?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),B="active_low_latency"):_!==0&&Q<E?B="live_forward_buffering":Q<E+W&&(B="live_with_target_offset"),isFinite(b)&&(f=b>f?b:f),B==="live_forward_buffering"||B==="live_with_target_offset"){let $=f-(E+Y),ee=this.normolizeLiveOffset(Math.trunc(_+$/g)),se=Math.abs(ee-_),D;!b||se<=this.tuning.dashCmafLive.offsetCalculationError?D=_:ee>0&&se>this.tuning.dashCmafLive.offsetCalculationError?D=ee:D=0,this.manifestUrlString=he(this.manifestUrlString,D,2)}B!=="none"&&B!=="active_low_latency"&&(f=0,this.updateLive())})))}let o=(0,S.merge)(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),u=(0,S.merge)(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:o,someBufferEnded:u}).pipe((0,S.filter)(({allBuffersFull:f,someBufferEnded:b})=>f&&b))).subscribe(()=>{var f;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(f=this.source)==null||f.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(f=>f.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(f=>{var b;return(b=this.source)==null?void 0:b.addEventListener("sourceopen",f)}));let d=(m=this.manifest.duration)!=null?m:0,c=(f,b)=>{var v;return Math.max(f,(v=b.duration)!=null?v:0)},l=this.manifest.representations.audio.reduce(c,d),h=this.manifest.representations.video.reduce(c,d);(l||h)&&(this.source.duration=Math.max(l,h)/1e3),this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),r=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:r})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new tr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Et.getLiveEstimatedDelaySmoothedValue(0,M({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return V(this,null,function*(){var i,r,a,s;(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=he(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive((i=this.manifest)==null?void 0:i.representations.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive((a=this.manifest)==null?void 0:a.representations.audio))})}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...us.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Zt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=5e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(5e3).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return V(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var r,a,s,o,u;(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(s=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?s:e),Zt(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3}stop(){var e,t,i;(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return V(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,i=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let a of this.bufferManagers)for(let s of a.gaps)a.playingRepresentation$.getValue()===s.representation&&s.from-r<=t&&s.to+r>t&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?i.push(1/0):i.push(s.to));if(i.length){let a=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,a===1/0?this.forceEnded$.next():this.element.currentTime=a/1e3}}};var or=class{constructor(e,t){this.fov=e,this.orientation=t}};var ur=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/_e(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=M({},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*_e(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 ds=`attribute vec2 a_vertex;
|
|
35
|
+
`});let te=Q&&d&&d.history[Q.id]&&(0,H.now)()-d.history[Q.id]<=i.trackCooldown&&(!d.last||Q.id!==d.last.id);if(Q!=null&&Q.id&&d&&!te&&d.recordSelection(Q),te&&(d!=null&&d.last)){let M=d.last;return d==null||d.recordSwitch(M),c({message:`
|
|
36
|
+
[last selected] ${M==null?void 0:M.quality}
|
|
37
|
+
`}),M}return d==null||d.recordSwitch(Q),Q},lt=Mn;var ce=n=>new URL(n).hostname;var N=require("@vkontakte/videoplayer-shared");var Fa=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},Ie=n=>B(void 0,null,function*(){let e=n.muted;try{yield n.play()}catch(t){if(!Fa(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{yield n.play()}catch(i){return Fa(i)&&(n.muted=!1,console.warn(i)),!1}}return!0});var Pe=require("@vkontakte/videoplayer-shared");var He=require("@vkontakte/videoplayer-shared");function pe(){return(0,He.now)()}function Qr(n){return pe()-n}function Wr(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Ua(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Ct(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,l,c,h=!1,m="arraybuffer",f=7e3,b=2e3,y=()=>{if(u)return;(0,He.assertNonNullable)(l);let R=Qr(l),ee;if(R<b){ee=b-R,setTimeout(y,ee);return}b*=2,b>f&&(b=f),s&&s.abort(),s=new r,Y()},T=R=>(a=R,O),g=R=>(c=R,O),D=()=>(m="json",O),I=()=>{if(!u){if(--d>=0){y(),i&&i();return}u=!0,c&&c(),t&&t()}},E=R=>(h=R,O),Y=()=>{l=pe(),s=new r,s.open("get",n);let R=0,ee,se=0,M=()=>((0,He.assertNonNullable)(l),Math.max(l,Math.max(ee||0,se||0)));if(a&&s.addEventListener("progress",A=>{let X=pe();a.updateChunk&&A.loaded>R&&(a.updateChunk(M(),A.loaded-R),R=A.loaded,ee=X)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>I())),s.addEventListener("load",()=>{if(u)return;(0,He.assertNonNullable)(s);let A=s.status;if(A>=200&&A<300){if(s.response.byteLength&&a){let X=s.response.byteLength-R;X&&a.updateChunk&&a.updateChunk(M(),X)}s.responseType==="json"&&!Object.values(s.response).length?I():(c&&c(),e(s.response))}else I()}),s.addEventListener("error",()=>{I()}),h){let A=()=>{(0,He.assertNonNullable)(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(se=pe(),s.removeEventListener("readystatechange",A))};s.addEventListener("readystatechange",A)}return s.responseType=m,s.send(),O},O={withBitrateReporting:T,withParallel:E,withJSONResponse:D,withRetryCount:R=>(d=R,O),withRetryInterval:(R,ee)=>((0,He.isNonNullable)(R)&&(b=R),(0,He.isNonNullable)(ee)&&(f=ee),O),withTimeout:R=>(o=R,O),withFinally:g,send:Y,abort:()=>{s&&(s.abort(),s=void 0),u=!0,c&&c()}};return O}var Kt=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Jt=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=pe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ct(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=pe()}_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=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var tr=1e4,jr=3;var Bn=6e4,Vn=10,On=1,Nn=500,Xt=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Kt(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Wr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Pe.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{Ua(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Jt(jr,tr,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,d=null,l=!1,c=()=>{let I=a&&(!l||l===this.rep);return I||t("Not running!"),I},h=(I,E,Y)=>{u&&u.abort(),u=Ct(this.urlResolver.resolve(I,!1),E,Y,()=>this._retryCallback()).withTimeout(tr).withBitrateReporting(this.bitrateSwitcher).withRetryCount(jr).withFinally(()=>{u=null}).send()},m=(I,E,Y)=>{(0,Pe.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,Y,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),i.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let Y=pe()-1e4,W=0;for(let te=0;te<this.bufferStates.length;te++){let Z=this.bufferStates[te];I=Math.min(I,Z.buf),Z.ts<Y&&W++}this.bufferStates.splice(0,W),t(`update playback rate; minBuffer=${I} drop=${W} jitter=${this.sourceJitter}`);let Q=I-On;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?f(1.15):Q>1?f(1.1):Q>.3?f(1.05):f(1)}},T=I=>{let E,Y=()=>E&&E.start?E.start.length:0,W=A=>E.start[A]/1e3,Q=A=>E.dur[A]/1e3,te=A=>E.fragIndex+A,Z=(A,X)=>({chunkIdx:te(A),startTS:W(A),dur:Q(A),discontinuity:X}),O=()=>{let A=0;if(E&&E.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ne=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,de=X;this.sourceJitter>1&&(de+=this.sourceJitter-1);let me=E.dur.length-1;for(;me>=0&&(de-=E.dur[me],!(de<=0));--me);A=Math.min(me,E.dur.length-1-ne),A=Math.max(A,0)}return Z(A,!0)},R=A=>{let X=Y();if(!(X<=0)){if((0,Pe.isNonNullable)(A)){for(let ne=0;ne<X;ne++)if(W(ne)>A)return Z(ne)}return O()}},ee=A=>{let X=Y(),ne=A?A.chunkIdx+1:0,de=ne-E.fragIndex;if(!(X<=0)){if(!A||de<0||de-X>Vn)return t(`Resync: offset=${de} bChunks=${X} chunk=`+JSON.stringify(A)),O();if(!(de>=X))return Z(ne-E.fragIndex,!1)}},se=(A,X,ne)=>{d&&d.abort(),d=Ct(this.urlResolver.resolve(A,!0,this.lowLatency),X,ne,()=>this._retryCallback()).withTimeout(tr).withRetryCount(jr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(A,X)=>{se(I,ne=>{if(!c())return;E=ne;let de=!!E.lowLatency;de!==this.lowLatency&&b(de);let me=0;for(let We=0;We<E.dur.length;++We)me+=E.dur[We];me>0&&((0,Pe.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(me/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,A(R(X))},()=>this._handleNetworkError())},nextChunk:ee}},g=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),(0,Pe.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:I=>{let{videoElement:E,logger:Y}=this.params,W=T(e.jidxUrl),Q,te,Z,O,R=0,ee,se,M,A=()=>{ee&&(clearTimeout(ee),ee=void 0);let z=Math.max(Nn,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=R+z,xe=pe(),Ae=Math.min(1e4,ge-xe);R=xe;let rt=()=>{d||c()&&W.seek(()=>{c()&&(R=pe(),X(),A())})};Ae>0?ee=window.setTimeout(()=>{this.paused?A():rt()},Ae):rt()},X=()=>{let z;for(;z=W.nextChunk(O);)O=z,Hi(z);let ge=W.nextChunk(Z);if(ge){if(Z&&ge.discontinuity){Y("Detected discontinuity; restarting playback"),this.paused?A():(g(),this._initPlayerWith(e));return}We(ge)}else A()},ne=(z,ge)=>{if(!c()||!this.sourceBuffer)return;let xe,Ae,rt,Lt=at=>{window.setTimeout(()=>{c()&&ne(z,ge)},at)};if(this.sourceBuffer.updating)Y("Source buffer is updating; delaying appendBuffer"),Lt(100);else{let at=pe(),ht=E.currentTime;!this.paused&&E.buffered.length>1&&se===ht&&at-M>500&&(Y("Stall suspected; trying to fix"),this._fixupStall()),se!==ht&&(se=ht,M=at);let $t=this._getBufferSizeSec();if($t>30)Y(`Buffered ${$t} seconds; delaying appendBuffer`),Lt(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:at,buf:$t}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Ht){if(Ht.name==="QuotaExceededError")Y("QuotaExceededError; delaying appendBuffer"),rt=this.sourceBuffer.buffered.length,rt!==0&&(xe=this.sourceBuffer.buffered.start(0),Ae=ht,Ae-xe>4&&this.sourceBuffer.remove(xe,Ae-3)),Lt(1e3);else throw Ht}}},de=()=>{te&&Q&&(Y([`Appending chunk, sz=${te.byteLength}:`,JSON.stringify(Z)]),ne(te,function(){te=null,X()}))},me=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),We=z=>{c()&&m(me(z),(ge,xe)=>{if(c()){if(xe/=1e3,te=ge,Z=z,s=z.startTS,xe){let Ae=Math.min(10,z.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ae:Ae}de()}},()=>this._handleNetworkError())},Hi=z=>{c()&&((0,Pe.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(me(z),!1)))},Ut=z=>{c()&&(e.cachedHeader=z,ne(z,()=>{Q=!0,de()}))};a=!0,W.seek(z=>{if(c()){if(R=pe(),!z){A();return}O=z,!(0,Pe.isNullable)(I)||z.startTS>I?We(z):(Z=z,X())}},I),e.cachedHeader?Ut(e.cachedHeader):h(e.headerUrl,Ut,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>s},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Pe.isNonNullable)(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,(0,Pe.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Pe.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(m=this._getBufferSizeSec(),f=c/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,m)=>{let f=pe();if(this.chunkRateEstimator.addInterval(h,f,m)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-h,speed:y}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))(),s=-1/0,o,u=!0,d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Qr(s)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let m=a.updateChunk(c,h);return m&&d(),m},notifySwitch:c=>{let h=pe();c<o&&(s=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ct(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(tr).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).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s!=null&&s.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Bn))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ae=require("@vkontakte/videoplayer-shared"),Yr=class{constructor(){this.onDroopedVideoFramesLimit$=new ae.Subject;this.subscription=new ae.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ae.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ae.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var s;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&(0,ae.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((s=this.limitCounts[this.currentQuality])!=null?s:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ae.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ae.interval)(this.droppedFramesChecker.checkTime).pipe((0,ae.filter)(()=>this.playing),(0,ae.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ae.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ae.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[s])=>(0,ae.isLower)(a,s)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ir=Yr;var rr=require("@vkontakte/videoplayer-shared"),Ha=require("@vkontakte/videoplayer-shared");var Zt=()=>{var n;return!!((n=window.documentPictureInPicture)!=null&&n.window)||!!document.pictureInPictureElement};var _n=(n,e)=>new rr.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Zt()))},C(C({},i),e));r.observe(n);let a=(0,Ha.fromEvent)(document,"visibilitychange").pipe((0,rr.map)(s=>!document.hidden||Zt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),Re=_n;var Fn=["paused","playing","ready"],Un=["paused","playing","ready"],ei=class{constructor(e){this.subscription=new N.Subscription;this.videoState=new G("stopped");this.representations$=new N.ValueSubject([]);this.textTracksManager=new $e;this.droppedFramesManager=new ir;this.maxSeekBackTime$=new N.ValueSubject(1/0);this.zeroTime$=new N.ValueSubject(void 0);this.liveOffset=new qe;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let s=e.isBuffering;this.params.output.isBuffering$.next(s);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:N.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let s=e.manifest,o=[];for(let u of s){let d=(t=u.name)!=null?t:u.index.toString(10),l=(i=dt(u.name))!=null?i:(0,N.videoSizeToQuality)(u.video),c=u.bitrate/1e3,h=C({},u.video);if(!l)continue;let m={id:d,quality:l,bitrate:c,size:h};o.push({track:m,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let s=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===s))==null?void 0:a.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),(0,N.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:s,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(s,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Un.includes(e)&&(s||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&Fn.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(he(this.params.source.url,u))}return;default:return(0,N.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:N.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,N.merge)(this.videoState.stateChangeStarted$.pipe((0,N.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,N.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Se(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Te(this.video);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$:this.representations$.pipe((0,N.map)(r=>r.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,N.filterChanged)(),(0,N.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,N.combine)({zeroTime:this.zeroTime$.pipe((0,N.filter)(N.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ue(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(Le(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Re(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&(0,N.videoQualityToHeight)(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,N.assertNever)(r.to)}},t)).add((0,N.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,N.observableFrom)(["init"])).pipe((0,N.debounce)(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 Xt({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var d,l,c,h,m,f;let e=this.representations$.getValue(),t=(l=(d=this.params.desiredState.videoTrack.getTransition())==null?void 0:d.to)!=null?l:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,N.isNonNullable)(t)?t:lt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,s=this.params.desiredState.videoTrack.getTransition(),o=(m=this.params.desiredState.videoTrack.getState())==null?void 0:m.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let b=(f=e.find(({track:y})=>y.id===a))==null?void 0:f.representation;(0,N.assertNonNullable)(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,N.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(he(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var Ga=ei;var Je=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var $=require("@vkontakte/videoplayer-shared");var ti=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared");var De=require("@vkontakte/videoplayer-shared");var Hn=16,ja=!1,Qa,Wa;try{ja=(0,De.getCurrentBrowser)().browser===De.CurrentClientBrowser.Safari&&parseInt((Wa=(Qa=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Qa[1])!=null?Wa:"",10)<=Hn}catch(n){console.error(n)}var qr=class{constructor(e){this.bufferFull$=new De.Subject;this.error$=new De.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:De.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return B(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return B(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return B(this,null,function*(){return new Promise(t=>{let i;ja&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:De.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,De.assertNever)(t)}}},Ya=qr;var zr=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var K=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Bt=class extends K{};var ii=class extends K{};var ri=class extends K{constructor(t,i){super(t,i);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var ai=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends K{constructor(t,i){super(t,i);this.data=this.content}};var oe=class extends K{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var St=class extends oe{constructor(t,i){super(t,i);this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,o=a<<1>>>1,u=this.readUint32();a=this.readUint32();let d=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:o,subsegmentDuration:u,SAPType:d,SAPDeltaTime:l})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var oi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ui=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends oe{constructor(t,i){super(t,i);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var li=class extends oe{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ci=class extends oe{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var pi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends oe{constructor(t,i){super(t,i);this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var mi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends oe{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var gi=class extends K{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends oe{constructor(t,i){super(t,i);this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var vi=class extends oe{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 yi=class extends oe{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 Qn={ftyp:ri,moov:ai,moof:si,mdat:ni,sidx:St,trak:oi,mdia:pi,mfhd:bi,tkhd:hi,traf:gi,tfhd:Si,tfdt:vi,trun:yi,minf:mi,sv3d:ui,st3d:di,prhd:li,proj:fi,equi:ci,uuid:ii,unknown:Bt},vt=class n{constructor(e={}){this.options=C({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch(r){break}return t}createBox(e,t){let i=Qn[e];return i?new i(t,new n):new Bt(t,new n)}};var Vt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var jn=new TextDecoder("ascii"),Yn=n=>jn.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",qn=n=>{let e=new St(n,new vt),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},zn=(n,e)=>{let i=new vt().parse(n),r=new Vt(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,c)},Kn=(n,e)=>{let i=new vt().parse(n),a=new Vt(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,h)=>c+h,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},Jn=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new vt().parse(n),r=new Vt(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},qa={validateData:Yn,parseInit:Jn,getIndexRange:()=>{},parseSegments:qn,parseFeedableSegmentChunk:zn,getSegmentEndTime:Kn};var Xe=require("@vkontakte/videoplayer-shared");var Ka=require("@vkontakte/videoplayer-shared");var za={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"}},Ja=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ti(n,t),r=i in za,a=r?za[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,l=Ti(u),c=d*_e(2,(o-1)*8)+l,h=t+o,m;return h+c>n.byteLength?m=new DataView(n.buffer,n.byteOffset+h):m=new DataView(n.buffer,n.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:m,valueSize:c}},Ti=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*_e(2,16)+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*_e(2,32)+n.getUint32(1);case 6:return n.getUint16(0)*_e(2,32)+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ve=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return Ti(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:(0,Ka.assertNever)(e)}},yt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=Ja(i);if(!e(r))return;r.type==="master"&&yt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},Xa=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=Ja(n);return yt(r.value,({tag:a,type:s,value:o})=>(a===17143?e=Ve(o,s):a===17026?t=Ve(o,s):a===17029&&(i=Ve(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Za=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Xn=[231,22612,22743,167,171,163,160,175],Zn=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,l=!1,c=0;return yt(n,({tag:h,type:m,value:f,valueSize:b})=>{if(h===21419){let y=Ve(f,m);d=Ti(y)}else h!==21420&&(d=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?a=!0:h===290298740?s=!0:h===2807729?i=Ve(f,m):h===17545?r=Ve(f,m):h===21420&&d===475249515?u=Ve(f,m):h===374648427?yt(f,({tag:y,type:T,value:g})=>y===30321?(l=Ve(g,T)===1,!1):!0):a&&s&&Za.includes(h)&&(o=!0),!o}),(0,Xe.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Xe.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Xe.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},eo=n=>{if((0,Xe.isNullable)(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},to=(n,e)=>{let t=!1,i=!1,r=o=>(0,Xe.isNonNullable)(o.time)&&(0,Xe.isNonNullable)(o.position),a=[],s;return yt(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Ve(d,u));break;case 183:break;case 241:s&&(s.position=Ve(d,u));break;default:t&&Za.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:l}=o,c=a[u+1];return{status:"none",time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},io=n=>{let e=0,t=!1;try{yt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Xn.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},es={validateData:Xa,parseInit:Zn,getIndexRange:eo,parseSegments:to,parseFeedableSegmentChunk:io};var Ot=require("@vkontakte/videoplayer-shared");var ts=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var is=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Tt=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>(0,Ot.isNullable)(a)?o:(0,Ot.isNullable)(u)?a:a.padStart(parseInt(u,10),"0"))}return t},as=(n,e)=>{var I,E,Y,W,Q,te,Z,O,R,ee,se,M,A,X,ne,de,me,We,Hi,Ut,z,ge,xe,Ae,rt,Lt,at,ht,$t,Ht,oa,ua,da,la,ca,pa,ha,ma,fa,ba,ga,Sa;let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=(Y=(E=(I=a.querySelector("BaseURL"))==null?void 0:I.textContent)==null?void 0:E.trim())!=null?Y:"",u=s.children,d=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,h,m=a.getAttribute("mediaPresentationDuration"),f=s.getAttribute("duration"),b=a.getElementsByTagName("vk:Attrs")[0],y=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=is(m);else if(f){let we=is(f);(0,Ot.isNonNullable)(we)&&(h=we)}else y&&(h=parseInt(y,10));let T=0,g=(Q=(W=a.getAttribute("profiles"))==null?void 0:W.split(","))!=null?Q:[],D=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let we of u){let Gi=we.getAttribute("mimeType"),Js=we.getAttribute("codecs"),va=(te=we.getAttribute("contentType"))!=null?te:Gi==null?void 0:Gi.split("/")[0],Xs=(O=(Z=we.getAttribute("profiles"))==null?void 0:Z.split(","))!=null?O:[],ya=we.querySelectorAll("Representation"),Zs=we.querySelector("SegmentTemplate");if(va==="text"){for(let ue of ya){let st=ue.getAttribute("id")||"",Qi=we.getAttribute("lang"),Rt=we.getAttribute("label"),kr=(se=(ee=(R=ue.querySelector("BaseURL"))==null?void 0:R.textContent)==null?void 0:ee.trim())!=null?se:"",Ar=new URL(kr||o,e).toString(),Wi=st.includes("_auto");r.text.push({id:st,lang:Qi,label:Rt,isAuto:Wi,kind:"text",url:Ar})}continue}for(let ue of ya){let st=(M=ue.getAttribute("mimeType"))!=null?M:Gi,Qi=(X=(A=ue.getAttribute("codecs"))!=null?A:Js)!=null?X:"",Rt=(de=(ne=ue.getAttribute("contentType"))!=null?ne:st==null?void 0:st.split("/")[0])!=null?de:va,kr=(We=(me=we.getAttribute("profiles"))==null?void 0:me.split(","))!=null?We:[],Ar=parseInt((Hi=ue.getAttribute("width"))!=null?Hi:"",10),Wi=parseInt((Ut=ue.getAttribute("height"))!=null?Ut:"",10),Ta=parseInt((z=ue.getAttribute("bandwidth"))!=null?z:"",10)/1e3,Ia=(ge=ue.getAttribute("frameRate"))!=null?ge:"",en=(xe=ue.getAttribute("quality"))!=null?xe:void 0,tn=Ia?ts(Ia):void 0,rn=(Ae=ue.getAttribute("id"))!=null?Ae:(T++).toString(10),an=Rt==="video"?`${Wi}p`:Rt==="audio"?`${Ta}Kbps`:Qi,sn=`${rn}@${an}`,nn=(at=(Lt=(rt=ue.querySelector("BaseURL"))==null?void 0:rt.textContent)==null?void 0:Lt.trim())!=null?at:"",Ea=new URL(nn||o,e).toString(),on=[...g,...Xs,...kr],wr,un=ue.querySelector("SegmentBase"),mt=(ht=ue.querySelector("SegmentTemplate"))!=null?ht:Zs;if(un){let ft=(Ht=($t=ue.querySelector("SegmentBase Initialization"))==null?void 0:$t.getAttribute("range"))!=null?Ht:"",[bt,$r]=ft.split("-").map(Dt=>parseInt(Dt,10)),nt={from:bt,to:$r},Gt=(oa=ue.querySelector("SegmentBase"))==null?void 0:oa.getAttribute("indexRange"),[Rr,ji]=Gt?Gt.split("-").map(Dt=>parseInt(Dt,10)):[],Qt=Gt?{from:Rr,to:ji}:void 0;wr={type:"byteRange",url:Ea,initRange:nt,indexRange:Qt}}else if(mt){let ft={representationId:(ua=ue.getAttribute("id"))!=null?ua:void 0,bandwidth:(da=ue.getAttribute("bandwidth"))!=null?da:void 0},bt=parseInt((la=mt.getAttribute("timescale"))!=null?la:"",10),$r=(ca=mt.getAttribute("initialization"))!=null?ca:"",nt=mt.getAttribute("media"),Gt=(ha=parseInt((pa=mt.getAttribute("startNumber"))!=null?pa:"",10))!=null?ha:1,Rr=Tt($r,ft);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let ji=(ma=mt.querySelectorAll("SegmentTimeline S"))!=null?ma:[],Qt=[],Dt=0,Dr="",Mr=0;if(ji.length){let Yi=Gt,Be=0;for(let Mt of ji){let Ne=parseInt((fa=Mt.getAttribute("d"))!=null?fa:"",10),gt=parseInt((ba=Mt.getAttribute("r"))!=null?ba:"",10)||0,qi=parseInt((ga=Mt.getAttribute("t"))!=null?ga:"",10);Be=Number.isFinite(qi)?qi:Be;let Cr=Ne/bt*1e3,Br=Be/bt*1e3;for(let zi=0;zi<gt+1;zi++){let ln=Tt(nt,q(C({},ft),{segmentNumber:Yi.toString(10),segmentTime:(Be+zi*Ne).toString(10)})),xa=(Br!=null?Br:0)+zi*Cr,cn=xa+Cr;Yi++,Qt.push({time:{from:xa,to:cn},url:ln})}Be+=(gt+1)*Ne,Dt+=(gt+1)*Cr}Mr=Be/bt*1e3,Dr=Tt(nt,q(C({},ft),{segmentNumber:Yi.toString(10),segmentTime:Be.toString(10)}))}else if((0,Ot.isNonNullable)(h)){let Be=parseInt((Sa=mt.getAttribute("duration"))!=null?Sa:"",10)/bt*1e3,Mt=Math.ceil(h/Be),Ne=0;for(let gt=1;gt<Mt;gt++){let qi=Tt(nt,q(C({},ft),{segmentNumber:gt.toString(10),segmentTime:Ne.toString(10)}));Qt.push({time:{from:Ne,to:Ne+Be},url:qi}),Ne+=Be}Mr=Ne,Dr=Tt(nt,q(C({},ft),{segmentNumber:Mt.toString(10),segmentTime:Ne.toString(10)}))}let dn={time:{from:Mr,to:1/0},url:Dr};wr={type:"template",baseUrl:Ea,segmentTemplateUrl:nt,initUrl:Rr,totalSegmentsDurationMs:Dt,segments:Qt,nextSegmentBeyondManifest:dn,timescale:bt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Rt||!st)continue;let Lr={video:"video",audio:"audio",text:"text"}[Rt];Lr&&r[Lr].push({id:sn,kind:Lr,segmentReference:wr,profiles:on,duration:h,bitrate:Ta,mime:st,codecs:Qi,width:Ar,height:Wi,fps:tn,quality:en})}}return{dynamic:d,liveAvailabilityStartTime:c,duration:h,container:D,representations:r}};var ss=require("@vkontakte/videoplayer-shared"),ns=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var o;let s=(o=a?dt(a):void 0)!=null?o:(0,ss.videoSizeToQuality)({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},os=({id:n,bitrate:e})=>({id:n,bitrate:e}),us=(n,e,t)=>{var r;let i=e.indexOf(t);return(r=n.at(Math.round(n.length*i/e.length)))!=null?r:n.at(-1)},ds=({id:n,lang:e,label:t,url:i,isAuto:r})=>({id:n,url:i,isAuto:r,type:"internal",language:e,label:t}),ar=n=>"url"in n,It=n=>n.type==="template",Ii=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Ei=class{constructor(e,t,i,r,{fetcher:a,tuning:s,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,x.abortable)(this.destroyAbortController.signal,function(e){return le(this,null,function*(){let t=this.representations.get(e);(0,x.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ya(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>this.error$.next({id:"SegmentEjection",category:x.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:s}))),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,zr(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=Je(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,d<l)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);(0,x.assertNonNullable)(i,"No init buffer for starting representation"),(0,x.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=(0,x.abortable)(this.destroyAbortController.signal,function(e){return le(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);(0,x.assertNonNullable)(t,`No such representation ${e}`);let i=this.segments.get(e),r=this.initData.get(e);if((0,x.isNullable)(r)||(0,x.isNullable)(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),(0,x.assertNonNullable)(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);let a=this.getCurrentPosition();(0,x.isNonNullable)(a)&&(this.isLive||(i.forEach(s=>s.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e})}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,function(e){return le(this,null,function*(){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let d=e.find(h=>h.id===u);d&&this.representations.set(u,d);let l=this.representations.get(u);if(!l||!It(l.segmentReference))return;let c=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,c)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,i=this.representations.get(t);(0,x.assertNonNullable)(i);let r=this.segments.get(t);(0,x.assertNonNullable)(r,"No segments for starting representation");let a=this.initData.get(t);if((0,x.assertNonNullable)(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let s=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),s&&(yield this.sourceBufferTaskQueue.remove(s.from*1e3,s.to*1e3,this.destroyAbortController.signal)),this.searchGaps(r,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));switch(this.fetcher=a,this.tuning=s,this.compatibilityMode=d,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.dynamic),this.container=i,i){case"mp4":this.containerParser=qa;break;case"webm":this.containerParser=es;break;default:(0,x.assertNever)(i)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var d,l;if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||!(0,x.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((d=r==null?void 0:r.time.to)!=null?d:0)-((l=r==null?void 0:r.time.from)!=null?l:0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=Je(this.sourceBuffer.buffered,e),m=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=r.time.to-e+100&&(a=m)}if(isFinite(this.bufferLimit)&&zr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Je(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))c="high";else{let h=o.at(0);h&&h.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&Je(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=i.at(-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(let s of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!s||!It(s.segmentReference))return;let o=s.segmentReference.segments.map(c=>q(C({},c),{status:"none",size:void 0})),u=(i=this.segments.get(s.id))!=null?i:[],d=(a=(r=u.at(-1))==null?void 0:r.time.to)!=null?a:0,l=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(s.segmentReference);this.segments.set(s.id,c)}else{let c=o.slice(l+1);this.segments.set(s.id,[...u,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,x.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!It(r))return;let a=(t=this.segments.get(i.id))!=null?t:[],s=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),d=Tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}}findSegmentStartTime(e){var a,s,o;let t=(s=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?s:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,y=h>i||b||f===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&h<=i+T||m<=i+T;return(c==="none"||c==="partially_ejected"&&y&&g&&this.sourceBuffer&&!ti(this.sourceBuffer.buffered,i))&&y&&g});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=d||o<=l);c++){let h=a[c];if(s+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return B(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return B(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,x.abortable)(o,function(){return le(this,null,function*(){let l=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;let c=new DataView(l);if(!isFinite(r.segment.time.to)){let h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&d?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Ii(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,i="auto"){return B(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(yield(0,x.abortable)(s,function(){return le(this,null,function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ii(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(It(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!It(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!a.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(s){return B(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(d.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,d=e.byteLength;for(let l of this.activeSegments){let{segment:c}=l,h=u==="byteRange",m=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let b=h?c.byte.from-i:0,y=h?c.byte.to-i:e.byteLength,T=b<r,g=y<=r;if(c.status==="downloading"&&T&&g){c.status="downloaded";let D=new DataView(e.buffer,e.byteOffset+b,m);this.sourceBufferTaskQueue.append(D,a).then(I=>I&&!a.aborted?this.onSegmentFullyAppended(l,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(l.loadedBytes=Math.min(m,r-b),l.loadedBytes>l.feedingBytes)){let D=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),I=l.loadedBytes===m?D:this.containerParser.parseFeedableSegmentChunk(D);I!=null&&I.byteLength&&(c.status="partially_fed",l.feedingBytes+=I.byteLength,this.sourceBufferTaskQueue.append(I,a).then(E=>{if(a.aborted)s();else if(E)l.fedBytes+=I.byteLength,l.fedBytes===m&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<m)return;s()}}))}}}onSomeByteRangesDataLoadedNew(o){return B(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let d of this.activeSegments){let{segment:l}=d;if(d.representationId!==t)continue;if(a.aborted){s();continue}let c=l.byte.from-i,h=l.byte.to-i,m=h-c+1,f=c<r,b=h<=r;if(f){if(l.status==="downloading"&&b){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+c,m);(yield this.sourceBufferTaskQueue.append(y,a))&&!a.aborted?this.onSegmentFullyAppended(d,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(d.loadedBytes=Math.min(m,r-c),d.loadedBytes>d.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+c+d.feedingBytes,d.loadedBytes-d.feedingBytes),T=d.loadedBytes===m?y:this.containerParser.parseFeedableSegmentChunk(y);T!=null&&T.byteLength&&(l.status="partially_fed",d.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,a))&&!a.aborted?(d.fedBytes+=T.byteLength,d.fedBytes===m&&this.onSegmentFullyAppended(d,t)):s())}}}})}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ar(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;t||(t=s),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return B(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,function(){return le(this,null,function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>B(this,null,function*(){if(!o)return;let{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&It(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,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s})}pruneBuffer(e,t,i=!1){return B(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)})}pruneBufferNew(e,t,i=!1){return B(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((l,c)=>l.from-c.from);let d=[u[0]];for(let l=1;l<u.length;l++){let{from:c,to:h}=u[l],m=d[d.length-1];m.to>=c?m.to=Math.max(m.to,h):d.push(u[l])}return d},o=u=>{var l;if(a>=t)return r;r.push(u.time),r=s(r);let d=ar(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&d.status==="fed"&&o(d)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let m of h)m.status==="none"&&Math.round(m.time.from)<=Math.round(d)&&Math.round(m.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let h={time:{from:d,to:l},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+u&&l.status==="fed"&&o(l)}return r.length?(yield Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||l,!1):!1})}pruneBufferOld(e,t,i=!1){return B(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,u=d=>{var c;a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let l=ar(d)?(c=d.size)!=null?c:0:d.byte.to-d.byte.from;r+=l};for(let d of this.segments.values())for(let l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(a)&&isFinite(s),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(let h of this.segments.values())for(let m of h)if(m.status==="none"&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(c)){a=l,s=c;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>e+d&&c.status==="fed"&&u(c)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=1;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=s&&l.to+t>=o),d=e.filter(l=>s>=l.from-t&&s<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var xi=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var ls=n=>{var a;let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};var ie=require("@vkontakte/videoplayer-shared");var sr=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new ie.ValueSubject(void 0);this.lastConnectionReused$=new ie.ValueSubject(void 0);this.lastRequestFirstBytes$=new ie.ValueSubject(void 0);this.abortAllController=new AbortController;this.subscription=new ie.Subscription;this.fetchManifest=(0,ie.abortable)(this.abortAllController.signal,function(e){return le(this,null,function*(){let t=e;this.requestQuic&&(t=xi(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(Pi);return i?(this.onHeadersReceived(i.headers),i.text()):null})}.bind(this));this.fetch=(0,ie.abortable)(this.abortAllController.signal,function(d){return le(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){var te,Z;let l=e,c=new Headers;if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let O=new URL(l,location.href);O.searchParams.append("bytes",`${i.from}-${i.to}`),l=O.toString();break}default:(0,ie.assertNever)(t)}this.requestQuic&&(l=xi(l));let h=this.abortAllController.signal,m;if(s){let O=new AbortController;if(m=(0,ie.merge)((0,ie.fromEvent)(this.abortAllController.signal,"abort"),(0,ie.fromEvent)(s,"abort")).subscribe(()=>{try{O.abort()}catch(R){Pi(R)}}),this.abortAllController.signal.aborted||s.aborted)try{O.abort()}catch(R){Pi(R)}h=O.signal}let f=(0,ie.now)(),b=yield fetch(l,{priority:a,headers:c,signal:h}).catch(Pi),y=(0,ie.now)();if(!b)return m==null||m.unsubscribe(),null;if((te=this.throughputEstimator)==null||te.addRawRtt(y-f),!b.ok||!b.body)return m==null||m.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!r&&!o)return m==null||m.unsubscribe(),b.arrayBuffer();let[T,g]=b.body.tee(),D=T.getReader();o&&((Z=this.throughputEstimator)==null||Z.trackStream(g,u));let I=0,E=new Uint8Array(0),Y=!1,W=O=>{m==null||m.unsubscribe(),Y=!0,Pi(O)},Q=(0,ie.abortable)(h,function(ee){return le(this,arguments,function*({done:O,value:R}){if(I===0&&this.lastRequestFirstBytes$.next((0,ie.now)()-f),h.aborted){m==null||m.unsubscribe();return}if(!O&&R){let se=new Uint8Array(E.length+R.length);se.set(E),se.set(R,E.length),E=se,I+=R.byteLength,r==null||r(new DataView(E.buffer),I),yield D==null?void 0:D.read().then(Q,W)}})}.bind(this));return yield D==null?void 0:D.read().then(Q,W),m==null||m.unsubscribe(),Y?null:E.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,ie.abortable)(this.abortAllController.signal,function(e,t,i){return le(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(l,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-s,a-s+1);if(!t.validateData(h))throw new Error("Invalid media file");let m=t.parseInit(h),f=(T=e.indexRange)!=null?T:t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-s,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let y=t.parseSegments(b,m,f);return{init:m,dataView:new DataView(c),segments:y}})}.bind(this));this.fetchTemplateRepresentation=(0,ie.abortable)(this.abortAllController.signal,function(e,t){return le(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(s=>q(C({},s),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){let{type:t,reused:i}=ls(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return B(this,null,function*(){var a,s;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(s=yield this.fetchTemplateRepresentation(e,i))!=null?s:null;default:(0,ie.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Pi=n=>{if(!Ii(n))throw n};var Et=(n,e,t)=>t*e+(1-t)*n,Xr=(n,e)=>n.reduce((t,i)=>t+i,0)/e,cs=(n,e,t,i)=>{let r=0,a=t,s=Xr(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};var ki=require("@vkontakte/videoplayer-shared");var ct=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ki.ValueSubject(e.initial),this.debounced$=new ki.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=_e(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&((0,ki.isNullable)(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 nr=class extends ct{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Et(this.slow,t,this.params.emaAlphaSlow),this.fast=Et(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var or=class extends ct{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=Xr(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Et(this.emaSmoothed,t,this.params.emaAlpha);let r=cs(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var ur=class extends ct{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?Et(this.smoothed,t,this.params.emaAlpha):t}};var xt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new nr({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new or({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ur(C({initial:e,label:"liveEdgeDelay"},t))}};var Zr=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var Ze=()=>window.ManagedMediaSource||window.MediaSource,dr=()=>{var n,e;return!!(window.ManagedMediaSource&&((e=(n=window.ManagedSourceBuffer)==null?void 0:n.prototype)!=null&&e.appendBuffer))},ps=()=>{var n,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(n=window.SourceBuffer)==null?void 0:n.prototype)!=null&&e.appendBuffer))},hs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var fs=["timeupdate","progress","play","seeked","stalled","waiting"];var lr=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new G("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new S.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=(0,S.abortable)(this.destroyController.signal,function(e,t,i){return le(this,null,function*(){var r;this.element=e,this.manifestUrlString=he(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,function(){return le(this,null,function*(){var r;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=as(e!=null?e:"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let i=({kind:a,mime:s,codecs:o})=>{var u,d,l,c;return!!((d=(u=this.element)==null?void 0:u.canPlayType)!=null&&d.call(u,s)&&((c=(l=Ze())==null?void 0:l.isTypeSupported)!=null&&c.call(l,`${s}; codecs="${o}"`))||a==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((r=t.duration)!=null?r:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),q(C({},t),{representations:Object.fromEntries(Object.entries(t.representations).map(([a,s])=>[a,s.filter(i)]))})})}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,function(e,t,i){return le(this,null,function*(){var m;(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=f=>{this.representationSubscription.add((0,S.fromEvent)(f,"error").pipe((0,S.filter)(b=>{var y;return!!((y=this.element)!=null&&y.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?hs():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&dr())if(i){let f=document.createElement("source");r(f),f.type="application/x-mpegurl",f.src=i.url,this.element.appendChild(f)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest};if(this.videoBufferManager=new Ei("video",this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)&&(this.audioBufferManager=new Ei("audio",this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(f=>{var b;if((b=this.element)!=null&&b.paused){let y=Nr(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,y+1e3,2)}})),this.representationSubscription.add((0,S.merge)(...fs.filter(f=>f!=="waiting").map(f=>(0,S.fromEvent)(this.element,f))).pipe((0,S.map)(f=>this.element?Je(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.filter)(f=>!!f),(0,S.tap)(f=>{var b;(b=this.stallWatchdogSubscription)==null||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(b=>Zr(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:b,isActiveLowLatency:y})=>y&&!!b)).subscribe(({bufferLength:b})=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add((0,S.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:b,isActiveLowLatency:y})=>{if(!y)return;let T=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,D=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=b-T,E=1;Math.abs(I)>g&&(E=1+Math.sign(I)*D),Zr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var T,g;let y=0;if(b){let D=((g=(T=this.element)==null?void 0:T.currentTime)!=null?g:0)*1e3;y=Math.min(...this.bufferManagers.map(E=>{var Y,W;return(W=(Y=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:Y.to)!=null?W:D}))-D}this.liveLoadBufferLength$.getValue()!==y&&this.liveLoadBufferLength$.next(y)}));let f=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(T=>B(this,[T],function*({liveLoadBufferLength:b,bufferLength:y}){if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,D=Nr(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),Y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,W=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,Q=isFinite(b)?b:y,te=this.isActiveLowLatency$.getValue(),Z=I<=this.tuning.live.activeLiveDelay&&D===0;this.isActiveLowLatency$.next(te&&Z);let O="none";if(te?O="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&Z?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),O="active_low_latency"):D!==0&&Q<E?O="live_forward_buffering":Q<E+W&&(O="live_with_target_offset"),isFinite(b)&&(f=b>f?b:f),O==="live_forward_buffering"||O==="live_with_target_offset"){let R=f-(E+Y),ee=this.normolizeLiveOffset(Math.trunc(D+R/g)),se=Math.abs(ee-D),M;!b||se<=this.tuning.dashCmafLive.offsetCalculationError?M=D:ee>0&&se>this.tuning.dashCmafLive.offsetCalculationError?M=ee:M=0,this.manifestUrlString=he(this.manifestUrlString,M,2)}O!=="none"&&O!=="active_low_latency"&&(f=0,this.updateLive())})))}let o=(0,S.merge)(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),u=(0,S.merge)(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:o,someBufferEnded:u}).pipe((0,S.filter)(({allBuffersFull:f,someBufferEnded:b})=>f&&b))).subscribe(()=>{var f;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(f=this.source)==null||f.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(f=>f.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(f=>{var b;return(b=this.source)==null?void 0:b.addEventListener("sourceopen",f)}));let d=(m=this.manifest.duration)!=null?m:0,l=(f,b)=>{var y;return Math.max(f,(y=b.duration)!=null?y:0)},c=this.manifest.representations.audio.reduce(l,d),h=this.manifest.representations.video.reduce(l,d);(c||h)&&(this.source.duration=Math.max(c,h)/1e3),this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),r=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:r})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new sr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=xt.getLiveEstimatedDelaySmoothedValue(0,C({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return B(this,null,function*(){var i,r,a,s;(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=he(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive((i=this.manifest)==null?void 0:i.representations.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive((a=this.manifest)==null?void 0:a.representations.audio))})}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...fs.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ti(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var i,r;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue())this.seekLive(this.liveLastSeekOffset);else{let a=this.element.currentTime*1e3;(i=this.videoBufferManager)==null||i.maintain(a),(r=this.audioBufferManager)==null||r.maintain(a)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(1e3).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return B(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var r,a,s,o,u;(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(s=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?s:e),ti(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3}stop(){var e,t,i;(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return B(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,i=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let a of this.bufferManagers)for(let s of a.gaps)a.playingRepresentation$.getValue()===s.representation&&s.from-r<=t&&s.to+r>t&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?i.push(1/0):i.push(s.to));if(i.length){let a=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,a===1/0?this.forceEnded$.next():this.element.currentTime=a/1e3}}};var cr=class{constructor(e,t){this.fov=e,this.orientation=t}};var pr=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/_e(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=C({},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*_e(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 bs=`attribute vec2 a_vertex;
|
|
38
38
|
attribute vec2 a_texel;
|
|
39
39
|
|
|
40
40
|
varying vec2 v_texel;
|
|
@@ -45,7 +45,7 @@ void main(void) {
|
|
|
45
45
|
// save texel vector to pass to fragment shader
|
|
46
46
|
v_texel = a_texel;
|
|
47
47
|
}
|
|
48
|
-
`;var
|
|
48
|
+
`;var gs=`#ifdef GL_ES
|
|
49
49
|
precision highp float;
|
|
50
50
|
precision highp int;
|
|
51
51
|
#else
|
|
@@ -88,5 +88,5 @@ void main(void) {
|
|
|
88
88
|
// sample using new coordinates
|
|
89
89
|
gl_FragColor = texture2D(u_texture, tc);
|
|
90
90
|
}
|
|
91
|
-
`;var dr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new or(this.params.fov,this.params.orientation),this.cameraRotationManager=new ur(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(ds,this.gl.VERTEX_SHADER),i=this.createShader(ls,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,d=e+i,c=t+r,l=e-i,h=t+r;return[a,s,o,u,d,c,l,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}};var xt=class{constructor(e){this.subscription=new R.Subscription;this.videoState=new G("stopped");this.elementSize$=new R.ValueSubject(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new Xi;this.videoTracks$=new R.ValueSubject([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Ki;this.textTracks=[];this.syncPlayback=()=>{var s,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let d=(o=(s=this.liveOffset)==null?void 0:s.getTotalPausedTime())!=null?o:0;this.seek(r.position-d,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,R.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Se(e.container),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(ce(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new nr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Te(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.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$:this.videoTracks$.pipe((0,R.map)(d=>d.map(({track:c})=>c)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,R.filter)(R.isNonNullable),(0,R.once)()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Fe(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(we(this.video,t.playbackRate,i.playbackRateState$,r)),a((0,R.observeElementSize)(this.video),this.elementSize$),a($e(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var c;if(d==="manifest_ready"){let l=[];this.audioTracks=[],this.textTracks=[];let h=this.player.getRepresentations();(0,R.assertNonNullable)(h,"Manifest not loaded or empty");let m=Array.from(h.audio).sort((T,g)=>g.bitrate-T.bitrate),f=Array.from(h.video).sort((T,g)=>g.bitrate-T.bitrate),b=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(let T of m){let g=es(T);g&&this.audioTracks.push({track:g,representation:T})}for(let T of f){let g=Za(T);if(g){l.push({track:g,representation:T});let _=!this.params.tuning.isAudioDisabled&&ts(m,f,T);_&&this.audioRepresentations.set(T.id,_)}}this.videoTracks$.next(l);for(let T of b){let g=is(T);g&&this.textTracks.push({track:g,representation:T})}this.params.output.availableVideoTracks$.next(l.map(({track:T})=>T)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:T})=>T)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:T})=>T));let v=this.selectVideoRepresentation();(0,R.assertNonNullable)(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))==null?void 0:c.id,this.params.sourceHls)}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:R.ErrorCategory.WTF,message:"Switching representations threw",thrown:d});this.subscription.add((0,R.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,R.fromEvent)(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let l=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);let m=this.params.desiredState.autoVideoTrackSwitching.getState(),f=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(l){let b=l.id;!this.params.output.elementVisible$.getValue()&&m&&(b=this.videoTracks$.getValue().map(T=>T.representation).sort((T,g)=>g.bitrate-T.bitrate).filter(T=>{let g=(0,R.videoSizeToQuality)(T),_=(0,R.videoSizeToQuality)(l);if(g&&_)return(0,R.isLowerOrEqual)(g,_)&&(0,R.isLowerOrEqual)(g,f)}).map(T=>T.id)[0]),this.player.switchRepresentation("video",b).catch(s);let v=this.audioRepresentations.get(l.id);v&&this.player.switchRepresentation("audio",v.id).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,R.filterChanged)(),(0,R.map)(d=>{var c;return d&&((c=this.videoTracks$.getValue().find(({representation:{id:l}})=>l===d))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var c,l;if(d!=null&&d.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(l=this.params.tuning.spherical)!=null&&l.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,R.map)(({to:d})=>d==="ready"),(0,R.filterChanged)());this.subscription.add((0,R.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),l=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(l)})),this.subscription.add((0,R.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,R.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,R.observableFrom)(["init"])).pipe((0,R.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var l,h,m,f,b,v,T;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(l=this.params.desiredState.videoTrack.getState())==null?void 0:l.id,i=(h=this.videoTracks$.getValue().find(({track:{id:g}})=>g===t))==null?void 0:h.track,r=this.params.output.currentVideoTrack$.getValue(),a=ze(this.video.buffered,this.video.currentTime*1e3),s=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(s,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(i&&!e&&(f=(m=this.audioRepresentations.get(i.id))==null?void 0:m.bitrate)!=null?f:0,r&&(v=(b=this.audioRepresentations.get(r.id))==null?void 0:b.bitrate)!=null?v:0),d=dt(this.videoTracks$.getValue().map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:o,current:r,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?d!=null?d:i:i!=null?i:d;return c&&((T=this.videoTracks$.getValue().find(({track:g})=>g===c))==null?void 0:T.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ie(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ve(this.video)}};var ki=class extends xt{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)}};var Pt=require("@vkontakte/videoplayer-shared");var Ai=class extends xt{constructor(e){super(e),this.liveOffset=new je}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Pt.combine)({interval:(0,Pt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(r-1);s<=0&&e.position$.next(s),(a=this.liveOffset)==null||a.resetTo(-s*1e3)}})).add((0,Pt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Pt.map)(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(s,r)})}};var H=require("@vkontakte/videoplayer-shared");var Ve={};var Ot=(n,e)=>new H.Observable(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),wi=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new G("initializing");this.textTracksManager=new Le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,H.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,H.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,H.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,H.assertNever)(e)}break;default:(0,H.assertNever)(t)}};this.video=Se(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ce(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ve(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:H.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(Ve.Hls=r.default,Ve.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){(0,H.assertNonNullable)(Ve.Hls,"hls.js not loaded"),this.hls=new Ve.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,H.assertNonNullable)(Ve.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:H.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Te(this.video),a=(d,c)=>this.subscription.add(d.subscribe(c,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Fe(this.video,e.isLooped,i)),this.subscription.add(ye(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(we(this.video,e.playbackRate,r.playbackRateState$,i)),a($e(this.video),t.elementVisible$),this.subscription.add(Ot(this.hls,Ve.Events.ERROR).subscribe(d=>{var c;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:H.ErrorCategory.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(c=d.err)==null?void 0:c.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())==null?void 0:d.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Ot(this.hls,Ve.Events.MANIFEST_PARSED).pipe((0,H.map)(({levels:d})=>d.reduce((c,l)=>{var g,_;let h=l.name||l.height.toString(10),{width:m,height:f}=l,b=(_=ut((g=l.attrs.QUALITY)!=null?g:""))!=null?_:(0,H.videoSizeToQuality)({width:m,height:f});if(!b)return c;let v=l.attrs["FRAME-RATE"]?parseFloat(l.attrs["FRAME-RATE"]):void 0,T={id:h.toString(),quality:b,bitrate:l.bitrate/1e3,size:{width:m,height:f},fps:v};return this.trackLevels.set(h,{track:T,level:l}),c.push(T),c},[]))),t.availableVideoTracks$),a(Ot(this.hls,Ve.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let c=[];for(let l of d.subtitleTracks){let h=l.name,m=l.attrs.URI||"",f=l.lang,b="internal";c.push({id:h,url:m,language:f,type:b})}e.internalTextTracks.startTransitionTo(c)}}),a(Ot(this.hls,Ve.Events.LEVEL_LOADING).pipe((0,H.map)(({url:d})=>ce(d))),t.hostname$),a(Ot(this.hls,Ve.Events.FRAG_CHANGED),d=>{var h,m,f,b;let{video:c,audio:l}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((m=c==null?void 0:c.startPTS)!=null?m:0))*1e3),t.currentAudioSegmentLength$.next((((f=l==null?void 0:l.endPTS)!=null?f:0)-((b=l==null?void 0:l.startPTS)!=null?b:0))*1e3)}),this.subscription.add(ot(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:l})=>l===d))==null?void 0:c.track},o=Ot(this.hls,Ve.Events.LEVEL_SWITCHED).pipe((0,H.map)(({level:d})=>s(this.hls.levels[d])));o.pipe((0,H.filter)(H.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ot(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{var f;if((0,H.isNullable)(d))return;let c=(f=this.trackLevels.get(d.id))==null?void 0:f.level;if(!c)return;let l=this.hls.levels.indexOf(c),h=this.hls.currentLevel,m=this.hls.levels[h];!m||c.bitrate>m.bitrate?this.hls.nextLevel=l:(this.hls.loadLevel=l,this.hls.loadLevel=l)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,H.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return V(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ie(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0)}};var cs="X-Playback-Duration",qr=n=>V(void 0,null,function*(){var r;let e=yield fetch(n),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(cs)?parseInt(e.headers.get(cs),10):void 0});var F=require("@vkontakte/videoplayer-shared");var lr=require("@vkontakte/videoplayer-shared");var io=n=>{let e=null;if(n.QUALITY&&(e=ut(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,lr.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},ro=(n,e)=>{var a,s;let t=n.split(`
|
|
92
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!c)){if(d){let l=Object.fromEntries(d[1].split(",").map(g=>g.split("="))),h=(a=l.QUALITY)!=null?a:`stream-${l.BANDWIDTH}`,m=io(l),f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,v;if(l.RESOLUTION){let[g,_]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&_&&(v={width:g,height:_})}let T=new URL(t[++o],e).toString();m&&i.push({id:h,quality:m,url:T,bandwidth:f,size:v,fps:b})}if(c){let l=Object.fromEntries(c[1].split(",").map(b=>b.split("=")).map(([b,v])=>[b,v.replace(/^"|"$/g,"")])),h=(s=l.URI)==null?void 0:s.replace(/playlist$/,"subtitles.vtt"),m=l.LANGUAGE,f=l.NAME;h&&m&&r.push({type:"internal",id:m,label:f,language:m,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},ao=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),zr=0,ps=(i,...r)=>V(void 0,[i,...r],function*(n,e=n,t){let s=yield(yield fetch(n)).text();zr+=1;try{let{qualityManifests:o,textTracks:u}=ro(s,e);return{qualityManifests:o,textTracks:u}}catch(o){if(zr<=t.manifestRetryMaxCount)return yield ao((0,lr.getExponentialDelay)(zr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ps(n,e,t)}return{qualityManifests:[],textTracks:[]}}),cr=ps;var Li=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new G("stopped");this.textTracksManager=new Le;this.manifests$=new F.ValueSubject([]);this.liveOffset=new je;this.manifestStartTime$=new F.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,F.assertNever)(t)}};var t;this.params=e,this.video=Se(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:F.VideoQuality.INVARIANT,url:this.params.source.url},cr(he(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:F.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:F.ErrorCategory.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(ce(this.params.source.url)),this.maxSeekBackTime$=new F.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,d,c,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(l=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(d=t.getState())==null?void 0:d.id)!=null?l:"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:F.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Te(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(we(this.video,t.playbackRate,r.playbackRateState$,i)),a($e(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,F.filterChanged)(),(0,F.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(0,F.isNonNullable)(d.to)){let l=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(m=>m.id===l);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ce(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,d,c;let o=(c=(d=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:d.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,F.combine)({startTime:this.manifestStartTime$.pipe((0,F.filter)(F.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,F.map)(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let s=(0,F.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,F.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[l,h]of[[d,"mq"],[c,"lq"]]){let m=String(parseFloat(l||""));h&&l&&r.searchParams.set(h,m)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=he(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),qr(s).then(d=>{var c;if(!(0,F.isNullable)(d))this.maxSeekBackTime$.next(d);else{let l=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,F.isNullable)(l)||!isFinite(l))try{fetch(s).then(h=>h.text()).then(h=>{var f;let m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(m){let b=new URL(m,s).toString();qr(b).then(v=>{(0,F.isNullable)(v)||this.maxSeekBackTime$.next(v)})}})}catch(h){}}})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.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()}};var j=require("@vkontakte/videoplayer-shared");var $i=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new G("stopped");this.textTracksManager=new Le;this.manifests$=new j.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,j.assertNever)(t)}};this.params=e,this.video=Se(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:j.VideoQuality.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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),cr(he(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:j.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,d,c,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(l=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(d=t.getState())==null?void 0:d.id)!=null?l:"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:j.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Te(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Fe(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(we(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var l;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(0,j.isNonNullable)(d.to)){let h=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let m=this.manifests$.getValue().find(f=>f.id===h);if(m){this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(ce(m.url));let f=this.params.desiredState.playbackRate.getState(),b=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(f!==b){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(f),v.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,j.map)(o=>o.map(({id:u,quality:d,size:c,bandwidth:l,fps:h})=>({id:u,quality:d,size:c,fps:h,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!(0,j.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,j.merge)((0,j.fromEvent)(o,"addtrack"),(0,j.fromEvent)(o,"removetrack"),(0,j.fromEvent)(o,"change"),(0,j.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=(0,j.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){var a,s;let e=this.selectManifest();if((0,j.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(s=(a=t==null?void 0:t.to)!=null?a:i)!=null?s:{};for(let[d,c]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(d||""));c&&d&&r.searchParams.set(c,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var X=require("@vkontakte/videoplayer-shared");var Ri=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new G("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{var u,d,c;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"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),s.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(d=this.trackUrls[s.to.id])==null?void 0:d.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,X.assertNever)(e)}};this.params=e,this.video=Se(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:X.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Te(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Fe(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(we(this.video,t.playbackRate,r.playbackRateState$,i)),a($e(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,d;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,X.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),l=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(c!==l){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=(0,X.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ve(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,X.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,X.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ii(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ce(t))}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,a,s,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(a=Object.values(this.trackUrls).find(l=>!(0,X.isInvariantQuality)(l.track.quality)&&(0,X.isLowerOrEqual)(l.track.quality,e)))==null?void 0:a.track,d=(s=this.params.desiredState.videoTrack.getState())==null?void 0:s.id,c=(o=this.trackUrls[d!=null?d:"0"])==null?void 0:o.track;if(u&&c&&(0,X.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let l=Object.values(this.trackUrls).filter(m=>!(0,X.isInvariantQuality)(m.track.quality)&&(0,X.isHigher)(m.track.quality,e)),h=l.length;h&&(t=l[h-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(d=>d.track);t=dt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};var re=require("@vkontakte/videoplayer-shared");var ms=require("@vkontakte/videoplayer-shared");var hs=["stun:videostun.mycdn.me:80"],so=1e3,no=3,Kr=()=>null,pr=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=Kr;this.externalStopCallback=Kr;this.externalErrorCallback=Kr;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}}handleUpdateMessage(e){return V(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return V(this,null,function*(){try{let e={iceServers:[{urls:hs}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return V(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return V(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:ms.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return V(this,null,function*(){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()))}}createOffer(){return V(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),so)}normalizeOptions(e={}){let t={stunServerList:hs,maxRetryNumber:no,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Di=class{constructor(e){this.videoState=new G("stopped");this.maxSeekBackTime$=new re.ValueSubject(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"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.subscription=new re.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Se(e.container),this.liveStreamClient=new pr(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:re.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};(0,re.merge)(this.videoState.stateChangeStarted$.pipe((0,re.map)(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,re.map)(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=Te(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a($e(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())==null?void 0:s.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ye(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,re.assertNever)(s.to)}},i)).add((0,re.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(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(ce(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:re.VideoQuality.INVARIANT}),this.video.srcObject=e,P(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:re.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Mi=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}};var y=require("@vkontakte/videoplayer-shared");var Ee=require("@vkontakte/videoplayer-shared");var Ps=(0,Ee.isAndroid)(),Me=document.createElement("video"),lo='video/mp4; codecs="avc1.42000a,mp4a.40.2"',co='video/mp4; codecs="hev1.1.6.L93.B0"',ks='video/webm; codecs="vp09.00.10.08"',As='video/webm; codecs="av01.0.00M.08"',po='audio/mp4; codecs="mp4a.40.2"',ho='audio/webm; codecs="opus"',fs,bs,kt={mms:sr(),mse:ss(),hls:!!((fs=Me.canPlayType)!=null&&fs.call(Me,"application/x-mpegurl")||(bs=Me.canPlayType)!=null&&bs.call(Me,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},gs,Ss,De={mp4:!!((gs=Me.canPlayType)!=null&&gs.call(Me,"video/mp4")),webm:!!((Ss=Me.canPlayType)!=null&&Ss.call(Me,"video/webm")),cmaf:!0},hr,vs,mr,ys,fr,Ts,br,Is,gr,Es,Sr,xs,He={h264:!!((vs=(hr=Je())==null?void 0:hr.isTypeSupported)!=null&&vs.call(hr,lo)),h265:!!((ys=(mr=Je())==null?void 0:mr.isTypeSupported)!=null&&ys.call(mr,co)),vp9:!!((Ts=(fr=Je())==null?void 0:fr.isTypeSupported)!=null&&Ts.call(fr,ks)),av1:!!((Is=(br=Je())==null?void 0:br.isTypeSupported)!=null&&Is.call(br,As)),aac:!!((Es=(gr=Je())==null?void 0:gr.isTypeSupported)!=null&&Es.call(gr,po)),opus:!!((xs=(Sr=Je())==null?void 0:Sr.isTypeSupported)!=null&&xs.call(Sr,ho))},Ci=(He.h264||He.h265)&&He.aac,At,mo=()=>V(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(q(M({},n),{video:q(M({},n.video),{contentType:As})})),window.navigator.mediaCapabilities.decodingInfo(q(M({},n),{video:q(M({},n.video),{contentType:ks})}))]);At={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{mo()}catch(n){console.error(n)}var _t=kt.hls&&De.mp4,ws=()=>Object.keys(He).filter(n=>He[n]),Ls=(n,e=!1,t=!1)=>{let i=kt.mse||kt.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&De.mp4&&Ci;case"DASH_WEBM":return i&&De.webm&&He.vp9&&He.opus;case"DASH_WEBM_AV1":return i&&De.webm&&He.av1&&He.opus;case"DASH_LIVE":return kt.mse&&De.mp4&&Ci;case"DASH_LIVE_CMAF":return i&&De.mp4&&Ci&&De.cmaf;case"DASH_ONDEMAND":return i&&De.mp4&&Ci;case"HLS":case"HLS_ONDEMAND":return _t||e&&kt.mse&&De.mp4&&Ci;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _t;case"MPEG":return De.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return kt.webrtc&&kt.ws&&He.h264&&(De.mp4||De.webm);default:return(0,Ee.assertNever)(r)}})},ct=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return At?At[t].smooth?[t,e]:At[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return At?At[t].powerEfficient?[t,e]:At[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Ee.assertNever)(n)}return[e,t]},$s=({webmCodec:n,androidPreferredFormat:e})=>{if(Ps)switch(e){case"mpeg":return["MPEG",...ct(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...ct(n),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...ct(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...ct(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ct(n),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ct(n),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:(0,Ee.assertNever)(e)}return _t?[...ct(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...ct(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Rs=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=(0,Ee.getCurrentBrowser)().device===Ee.CurrentClientDevice.Mac&&(0,Ee.getCurrentBrowser)().browser===Ee.CurrentClientBrowser.Safari;if(Ps)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:(0,Ee.assertNever)(n)}else _t&&!u?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Jr=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];var Xe=require("@vkontakte/videoplayer-shared"),Ds=n=>new Xe.Observable(e=>{let t=new Xe.Subscription,i=n.desiredPlaybackState$.stateChangeStarted$.pipe((0,Xe.map)(({from:d,to:c})=>`${d}-${c}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe((0,Xe.map)(({type:d})=>d!==void 0)),s=new Xe.Subject,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var fo={chunkDuration:5e3,maxParallelRequests:5},Bi=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new y.ValueSubject(void 0),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),availableVideoTracks$:new y.ValueSubject([]),availableAudioTracks$:new y.ValueSubject([]),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1)};this.subscription=new y.Subscription;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Ls([...Rs(this.params.tuning),...$s(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>(0,y.isNonNullable)(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Mi(a);let s=[...Jr(!0),...Jr(!1)];this.chromecastFormatsIterator=new Mi(s.filter(o=>(0,y.isNonNullable)(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}e.destroy();let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new ki(q(M({},s),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ai(q(M({},s),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),_t||!this.params.tuning.useHlsJs?new $i(q(M({},s),{source:o})):new wi(q(M({},s),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Li(q(M({},s),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ri(q(M({},s),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Va(q(M({},s),{source:o,config:q(M({},fo),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Di({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Wt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(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(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return q(M({},e),{url:i(e.url)})}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,i=0;return e.add((0,y.merge)(this.providerOutput.error$,Ds({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(r=>({id:`ProviderHangup:${r}`,category:y.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:a})=>a==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let s=r.category===y.ErrorCategory.NETWORK,o=r.category===y.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:"SCREEN")}})),e}};var C=require("@vkontakte/videoplayer-shared");var bo=5e3,Ms="one_video_throughput",Cs="one_video_rtt",Ze=window.navigator.connection,Bs=()=>{let n=Ze==null?void 0:Ze.downlink;if((0,C.isNonNullable)(n)&&n!==10)return n*1e3},Vs=()=>{let n=Ze==null?void 0:Ze.rtt;if((0,C.isNonNullable)(n)&&n!==3e3)return n},Os=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Xr=class n{constructor(e){this.subscription=new C.Subscription;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=n.load(Ms)||(e.useBrowserEstimation?Bs():void 0)||bo,i=(a=(r=n.load(Cs))!=null?r:e.useBrowserEstimation?Vs():void 0)!=null?a:0;if(this.throughput$=new C.ValueSubject(t),this.rtt$=new C.ValueSubject(i),this.rttAdjustedThroughput$=new C.ValueSubject(Os(t,i,e.rttPenaltyRequestSize)),this.throughput=Et.getSmoothedValue(t,-1,e),this.rtt=Et.getSmoothedValue(i,1,e),e.useBrowserEstimation){let s=()=>{let u=Bs();u&&this.throughput.next(u);let d=Vs();(0,C.isNonNullable)(d)&&this.rtt.next(d)};Ze&&"onchange"in Ze&&this.subscription.add((0,C.fromEvent)(Ze,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{C.safeStorage.set(Ms,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{C.safeStorage.set(Cs,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,C.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,C.map)(({throughput:s,rtt:o})=>Os(s,o,e.rttPenaltyRequestSize)),(0,C.filter)(s=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,C.now)(),r=new C.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,C.fromEvent)(e,"progress").pipe((0,C.once)()).subscribe(a=>{t=a.loaded,i=(0,C.now)()}));break;case 1:case 0:r.add((0,C.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,C.now)()}));break}r.add((0,C.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=(0,C.now)(),u=s-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=(0,C.now)(),s=0,o=(0,C.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},d=h=>V(this,[h],function*({done:c,value:l}){if(c)!t&&this.addRawSpeed(r,(0,C.now)()-a,1),this.concurrentDownloads.delete(e);else if(l){if(t){let m=(0,C.now)();if(m-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||m-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-a;b&&this.addRawSpeed(s,b,1,t),s=l.byteLength,a=(0,C.now)()}else s+=l.byteLength;o=(0,C.now)()}else r+=l.byteLength,s+=l.byteLength,s>=this.tuningConfig.streamMinSampleSize&&(0,C.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,(0,C.now)()-o,this.concurrentDownloads.size),s=0,o=(0,C.now)());yield i==null?void 0:i.read().then(d,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=C.safeStorage.get(e);if((0,C.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},_s=Xr;var Vi=require("@vkontakte/videoplayer-shared");var Ns={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Vi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Vi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:200,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Fs=n=>{var e;return q(M({},(0,Vi.fillWithDefault)(n,Ns)),{configName:[...(e=n.configName)!=null?e:[],...Ns.configName]})};var p=require("@vkontakte/videoplayer-shared");var et=require("@vkontakte/videoplayer-shared"),Zr=({seekState:n,position$:e})=>(0,et.merge)(n.stateChangeEnded$.pipe((0,et.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,et.filter)(et.isNonNullable)),e.pipe((0,et.filter)(()=>n.getState().state==="none")));var Us=require("@vkontakte/videoplayer-shared"),Hs=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return(0,Us.assertNonNullable)(e,`Wrong container or containerId {${n.container}}`),e};var vr=require("@vkontakte/videoplayer-shared"),Gs=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,vr.filter)(r=>r.length>0),(0,vr.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(n)};var Oi=class{constructor(e={configName:[]}){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new G("stopped"),seekState:new G({state:"none"}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),internalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({}),cameraOrientation:new G({x:0,y:0})};this.info={playbackState$:new p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,firstBytes$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:Da};if(this.initLogs(),this.tuning=Fs(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new qi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _s(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...s)=>{try{return a.apply(t,s)}catch(o){let u=s.map(l=>JSON.stringify(l,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:p.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=Hs(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Bi({sources:e.sources,meta:(i=e.meta)!=null?i:{},failoverHosts:(r=e.failoverHosts)!=null?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Jt()?(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;(0,p.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>M({type:"external"},t))),this}selectTextTrack(e){var t;return Gs(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();s.state==="requested"?this.desiredState.seekState.setState(q(M({},s),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(s=>s.destination),(0,p.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe((0,p.map)(s=>s.map(({quality:o})=>o).sort((o,u)=>(0,p.isInvariantQuality)(o)?1:(0,p.isInvariantQuality)(u)?-1:(0,p.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s==null?void 0:s.quality),this.info.videoBitrate$.next(s==null?void 0:s.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(s=>{this.desiredState.autoVideoTrackLimits.setState(s!=null?s:{})})).add(e.providerOutput.currentBuffer$.pipe((0,p.map)(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(s=>s.to),(0,p.filterChanged)(),(0,p.map)(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),(0,p.filterChanged)(),(0,p.tap)(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(s=>s.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(s=>s.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(Zr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.filterChanged)()).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.noAvailableProvidersError$.pipe((0,p.map)(s=>({id:s?`No${s}`:"NoProviders",category:p.ErrorCategory.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,p.once)(),(0,p.map)(s=>s!=null?s:(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-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 p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:s})=>s==="playing"),(0,p.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,p.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,p.map)(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),(0,p.filterChanged)());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,p.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s==null?void 0:s.videoWidth,height:s==null?void 0:s.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{var u,d;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=s==null?void 0:s.size)==null?void 0:u.width,height:(d=s==null?void 0:s.size)==null?void 0:d.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,p.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),l;c==="CONNECTED"?l="second_screen":u?d?s?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,p.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=dt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),Ra(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>$a(i)),this.providerContainer.current$.subscribe(({type:i})=>Yt("provider",i)),e.duration$.subscribe(i=>Yt("duration",i)),e.availableVideoTracks$.pipe((0,p.filter)(i=>!!i.length),(0,p.once)()).subscribe(i=>Yt("tracks",i)),this.events.fatalError$.subscribe(new fe("fatalError")),this.events.managedError$.subscribe(new fe("managedError")),e.position$.subscribe(new fe("position")),e.currentVideoTrack$.pipe((0,p.map)(i=>i==null?void 0:i.quality)).subscribe(new fe("quality")),this.info.currentBuffer$.subscribe(new fe("buffer")),e.isBuffering$.subscribe(new fe("isBuffering"))].forEach(i=>this.subscription.add(i)),Yt("codecs",ws())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>V(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:p.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!(e!=null&&e.released);r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var Ge=require("@vkontakte/videoplayer-shared"),go=`@vkontakte/videoplayer-core@${$r}`;
|
|
91
|
+
`;var hr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new cr(this.params.fov,this.params.orientation),this.cameraRotationManager=new pr(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(bs,this.gl.VERTEX_SHADER),i=this.createShader(gs,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,s,o,u,d,l,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}};var Pt=class{constructor(e){this.subscription=new $.Subscription;this.videoState=new G("stopped");this.elementSize$=new $.ValueSubject(void 0);this.textTracksManager=new $e;this.droppedFramesManager=new ir;this.videoTracks$=new $.ValueSubject([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new er;this.textTracks=[];this.syncPlayback=()=>{var s,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let d=(o=(s=this.liveOffset)==null?void 0:s.getTotalPausedTime())!=null?o:0;this.seek(r.position-d,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,$.assertNever)(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new hr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Se(e.container),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(ce(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new lr({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Te(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:$.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.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$:this.videoTracks$.pipe((0,$.map)(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe((0,$.filter)($.isNonNullable),(0,$.once)()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe((0,$.map)(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ue(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(Le(this.video,t.playbackRate,i.playbackRateState$,r)),a((0,$.observeElementSize)(this.video),this.elementSize$),a(Re(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d==="manifest_ready"){let c=[];this.audioTracks=[],this.textTracks=[];let h=this.player.getRepresentations();(0,$.assertNonNullable)(h,"Manifest not loaded or empty");let m=Array.from(h.audio).sort((T,g)=>g.bitrate-T.bitrate),f=Array.from(h.video).sort((T,g)=>g.bitrate-T.bitrate),b=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(let T of m){let g=os(T);g&&this.audioTracks.push({track:g,representation:T})}for(let T of f){let g=ns(T);if(g){c.push({track:g,representation:T});let D=!this.params.tuning.isAudioDisabled&&us(m,f,T);D&&this.audioRepresentations.set(T.id,D)}}this.videoTracks$.next(c);for(let T of b){let g=ds(T);g&&this.textTracks.push({track:g,representation:T})}this.params.output.availableVideoTracks$.next(c.map(({track:T})=>T)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:T})=>T)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:T})=>T));let y=this.selectVideoRepresentation();(0,$.assertNonNullable)(y),this.player.initRepresentations(y.id,(l=this.audioRepresentations.get(y.id))==null?void 0:l.id,this.params.sourceHls)}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:$.ErrorCategory.WTF,message:"Switching representations threw",thrown:d});this.subscription.add((0,$.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,$.fromEvent)(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="running"||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);let m=this.params.desiredState.autoVideoTrackSwitching.getState(),f=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let b=c.id;!this.params.output.elementVisible$.getValue()&&m&&(b=this.videoTracks$.getValue().map(T=>T.representation).sort((T,g)=>g.bitrate-T.bitrate).filter(T=>{let g=(0,$.videoSizeToQuality)(T),D=(0,$.videoSizeToQuality)(c);if(g&&D)return(0,$.isLowerOrEqual)(g,D)&&(0,$.isLowerOrEqual)(g,f)}).map(T=>T.id)[0]),this.player.switchRepresentation("video",b).catch(s);let y=this.audioRepresentations.get(c.id);y&&this.player.switchRepresentation("audio",y.id).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,$.filterChanged)(),(0,$.map)(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))==null?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,$.map)(({to:d})=>d==="ready"),(0,$.filterChanged)());this.subscription.add((0,$.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add((0,$.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,$.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var c,h,m,f,b,y,T;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(c=this.params.desiredState.videoTrack.getState())==null?void 0:c.id,i=(h=this.videoTracks$.getValue().find(({track:{id:g}})=>g===t))==null?void 0:h.track,r=this.params.output.currentVideoTrack$.getValue(),a=Je(this.video.buffered,this.video.currentTime*1e3),s=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(s,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(i&&!e&&(f=(m=this.audioRepresentations.get(i.id))==null?void 0:m.bitrate)!=null?f:0,r&&(y=(b=this.audioRepresentations.get(r.id))==null?void 0:b.bitrate)!=null?y:0),d=lt(this.videoTracks$.getValue().map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:o,current:r,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),l=e?d!=null?d:i:i!=null?i:d;return l&&((T=this.videoTracks$.getValue().find(({track:g})=>g===l))==null?void 0:T.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ie(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ve(this.video)}};var wi=class extends Pt{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)}};var kt=require("@vkontakte/videoplayer-shared");var Li=class extends Pt{constructor(e){super(e),this.liveOffset=new qe}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,kt.combine)({interval:(0,kt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(r-1);s<=0&&e.position$.next(s),(a=this.liveOffset)==null||a.resetTo(-s*1e3)}})).add((0,kt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,kt.map)(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(s,r)})}};var U=require("@vkontakte/videoplayer-shared");var Oe={};var Nt=(n,e)=>new U.Observable(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),$i=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new G("initializing");this.textTracksManager=new $e;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,U.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,U.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,U.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,U.assertNever)(e)}break;default:(0,U.assertNever)(t)}};this.video=Se(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ce(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ve(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:U.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(Oe.Hls=r.default,Oe.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){(0,U.assertNonNullable)(Oe.Hls,"hls.js not loaded"),this.hls=new Oe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,U.assertNonNullable)(Oe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:U.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Te(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ue(this.video,e.isLooped,i)),this.subscription.add(ye(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Le(this.video,e.playbackRate,r.playbackRateState$,i)),a(Re(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe((0,U.map)(d=>d.to)),this.params.output.playbackState$),this.subscription.add(Nt(this.hls,Oe.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:U.ErrorCategory.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)==null?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())==null?void 0:d.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(Nt(this.hls,Oe.Events.MANIFEST_PARSED).pipe((0,U.map)(({levels:d})=>d.reduce((l,c)=>{var g,D;let h=c.name||c.height.toString(10),{width:m,height:f}=c,b=(D=dt((g=c.attrs.QUALITY)!=null?g:""))!=null?D:(0,U.videoSizeToQuality)({width:m,height:f});if(!b)return l;let y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,T={id:h.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:m,height:f},fps:y};return this.trackLevels.set(h,{track:T,level:c}),l.push(T),l},[]))),t.availableVideoTracks$),a(Nt(this.hls,Oe.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let l=[];for(let c of d.subtitleTracks){let h=c.name,m=c.attrs.URI||"",f=c.lang,b="internal";l.push({id:h,url:m,language:f,type:b})}e.internalTextTracks.startTransitionTo(l)}}),a(Nt(this.hls,Oe.Events.LEVEL_LOADING).pipe((0,U.map)(({url:d})=>ce(d))),t.hostname$),a(Nt(this.hls,Oe.Events.FRAG_CHANGED),d=>{var h,m,f,b;let{video:l,audio:c}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=l==null?void 0:l.endPTS)!=null?h:0)-((m=l==null?void 0:l.startPTS)!=null?m:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((b=c==null?void 0:c.startPTS)!=null?b:0))*1e3)}),this.subscription.add(ut(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))==null?void 0:l.track},o=Nt(this.hls,Oe.Events.LEVEL_SWITCHED).pipe((0,U.map)(({level:d})=>s(this.hls.levels[d])));o.pipe((0,U.filter)(U.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ut(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{var f;if((0,U.isNullable)(d))return;let l=(f=this.trackLevels.get(d.id))==null?void 0:f.level;if(!l)return;let c=this.hls.levels.indexOf(l),h=this.hls.currentLevel,m=this.hls.levels[h];!m||l.bitrate>m.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,U.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return B(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ie(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Ss="X-Playback-Duration",ea=n=>B(void 0,null,function*(){var r;let e=yield fetch(n),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Ss)?parseInt(e.headers.get(Ss),10):void 0});var F=require("@vkontakte/videoplayer-shared");var mr=require("@vkontakte/videoplayer-shared");var lo=n=>{let e=null;if(n.QUALITY&&(e=dt(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,mr.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},co=(n,e)=>{var a,s;let t=n.split(`
|
|
92
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!l)){if(d){let c=Object.fromEntries(d[1].split(",").map(g=>g.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,m=lo(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,y;if(c.RESOLUTION){let[g,D]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&D&&(y={width:g,height:D})}let T=new URL(t[++o],e).toString();m&&i.push({id:h,quality:m,url:T,bandwidth:f,size:y,fps:b})}if(l){let c=Object.fromEntries(l[1].split(",").map(b=>b.split("=")).map(([b,y])=>[b,y.replace(/^"|"$/g,"")])),h=(s=c.URI)==null?void 0:s.replace(/playlist$/,"subtitles.vtt"),m=c.LANGUAGE,f=c.NAME;h&&m&&r.push({type:"internal",id:m,label:f,language:m,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},po=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),ta=0,vs=(i,...r)=>B(void 0,[i,...r],function*(n,e=n,t){let s=yield(yield fetch(n)).text();ta+=1;try{let{qualityManifests:o,textTracks:u}=co(s,e);return{qualityManifests:o,textTracks:u}}catch(o){if(ta<=t.manifestRetryMaxCount)return yield po((0,mr.getExponentialDelay)(ta-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),vs(n,e,t)}return{qualityManifests:[],textTracks:[]}}),fr=vs;var Ri=class{constructor(e){this.subscription=new F.Subscription;this.videoState=new G("stopped");this.textTracksManager=new $e;this.manifests$=new F.ValueSubject([]);this.liveOffset=new qe;this.manifestStartTime$=new F.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,F.assertNever)(t)}};var t;this.params=e,this.video=Se(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:F.VideoQuality.INVARIANT,url:this.params.source.url},fr(he(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:F.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:F.ErrorCategory.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(ce(this.params.source.url)),this.maxSeekBackTime$=new F.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:F.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Te(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ye(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Le(this.video,t.playbackRate,r.playbackRateState$,i)),a(Re(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,F.filterChanged)(),(0,F.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(0,F.isNonNullable)(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let h=this.manifests$.getValue().find(m=>m.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ce(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,d,l;let o=(l=(d=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:d.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,F.combine)({startTime:this.manifestStartTime$.pipe((0,F.filter)(F.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,F.map)(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=(0,F.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,F.observableFrom)(["init"])).pipe((0,F.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,F.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[c,h]of[[d,"mq"],[l,"lq"]]){let m=String(parseFloat(c||""));h&&c&&r.searchParams.set(h,m)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=he(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),ea(s).then(d=>{var l;if(!(0,F.isNullable)(d))this.maxSeekBackTime$.next(d);else{let c=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if((0,F.isNullable)(c)||!isFinite(c))try{fetch(s).then(h=>h.text()).then(h=>{var f;let m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(m){let b=new URL(m,s).toString();ea(b).then(y=>{(0,F.isNullable)(y)||this.maxSeekBackTime$.next(y)})}})}catch(h){}}})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:F.ErrorCategory.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()}};var j=require("@vkontakte/videoplayer-shared");var Di=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new G("stopped");this.textTracksManager=new $e;this.manifests$=new j.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,j.assertNever)(t)}};this.params=e,this.video=Se(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:j.VideoQuality.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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),fr(he(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:j.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:j.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Te(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,j.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ue(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(Le(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var c;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(0,j.isNonNullable)(d.to)){let h=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let m=this.manifests$.getValue().find(f=>f.id===h);if(m){this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(ce(m.url));let f=this.params.desiredState.playbackRate.getState(),b=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(f!==b){let y=this.params.output.element$.getValue();y&&(this.params.desiredState.playbackRate.setState(f),y.playbackRate=f)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,j.map)(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!(0,j.isIOS)()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,j.merge)((0,j.fromEvent)(o,"addtrack"),(0,j.fromEvent)(o,"removetrack"),(0,j.fromEvent)(o,"change"),(0,j.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=(0,j.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ve(this.video)}prepare(){var a,s;let e=this.selectManifest();if((0,j.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(s=(a=t==null?void 0:t.to)!=null?a:i)!=null?s:{};for(let[d,l]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(d||""));l&&d&&r.searchParams.set(l,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:j.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var J=require("@vkontakte/videoplayer-shared");var Mi=class{constructor(e){this.subscription=new J.Subscription;this.videoState=new G("stopped");this.trackUrls={};this.textTracksManager=new $e;this.syncPlayback=()=>{var u,d,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),s.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(d=this.trackUrls[s.to.id])==null?void 0:d.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,J.assertNever)(e)}};this.params=e,this.video=Se(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:J.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Te(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe((0,J.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ue(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(Le(this.video,t.playbackRate,r.playbackRateState$,i)),a(Re(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,d;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,J.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),c=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(l!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(l),h.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=(0,J.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,J.observableFrom)(["init"])).pipe((0,J.debounce)(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ve(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,J.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,J.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=xi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ce(t))}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:J.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,a,s,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(a=Object.values(this.trackUrls).find(c=>!(0,J.isInvariantQuality)(c.track.quality)&&(0,J.isLowerOrEqual)(c.track.quality,e)))==null?void 0:a.track,d=(s=this.params.desiredState.videoTrack.getState())==null?void 0:s.id,l=(o=this.trackUrls[d!=null?d:"0"])==null?void 0:o.track;if(u&&l&&(0,J.isHigherOrEqual)(l.quality,u.quality)&&(t=u),!t){let c=Object.values(this.trackUrls).filter(m=>!(0,J.isInvariantQuality)(m.track.quality)&&(0,J.isHigher)(m.track.quality,e)),h=c.length;h&&(t=c[h-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(d=>d.track);t=lt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};var re=require("@vkontakte/videoplayer-shared");var Ts=require("@vkontakte/videoplayer-shared");var ys=["stun:videostun.mycdn.me:80"],ho=1e3,mo=3,ia=()=>null,br=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=ia;this.externalStopCallback=ia;this.externalErrorCallback=ia;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}}handleUpdateMessage(e){return B(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return B(this,null,function*(){try{let e={iceServers:[{urls:ys}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return B(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return B(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:Ts.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return B(this,null,function*(){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()))}}createOffer(){return B(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),ho)}normalizeOptions(e={}){let t={stunServerList:ys,maxRetryNumber:mo,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ci=class{constructor(e){this.videoState=new G("stopped");this.maxSeekBackTime$=new re.ValueSubject(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"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.subscription=new re.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Se(e.container),this.liveStreamClient=new br(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:re.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};(0,re.merge)(this.videoState.stateChangeStarted$.pipe((0,re.map)(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,re.map)(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=Te(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Re(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())==null?void 0:s.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ye(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,re.assertNever)(s.to)}},i)).add((0,re.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(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(ce(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:re.VideoQuality.INVARIANT}),this.video.srcObject=e,P(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:re.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ie(this.video).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Bi=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}};var v=require("@vkontakte/videoplayer-shared");var Ee=require("@vkontakte/videoplayer-shared");var Ds=(0,Ee.isAndroid)(),Ce=document.createElement("video"),go='video/mp4; codecs="avc1.42000a,mp4a.40.2"',So='video/mp4; codecs="hev1.1.6.L93.B0"',Ms='video/webm; codecs="vp09.00.10.08"',Cs='video/webm; codecs="av01.0.00M.08"',vo='audio/mp4; codecs="mp4a.40.2"',yo='audio/webm; codecs="opus"',Is,Es,At={mms:dr(),mse:ps(),hls:!!((Is=Ce.canPlayType)!=null&&Is.call(Ce,"application/x-mpegurl")||(Es=Ce.canPlayType)!=null&&Es.call(Ce,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},xs,Ps,Me={mp4:!!((xs=Ce.canPlayType)!=null&&xs.call(Ce,"video/mp4")),webm:!!((Ps=Ce.canPlayType)!=null&&Ps.call(Ce,"video/webm")),cmaf:!0},gr,ks,Sr,As,vr,ws,yr,Ls,Tr,$s,Ir,Rs,Ge={h264:!!((ks=(gr=Ze())==null?void 0:gr.isTypeSupported)!=null&&ks.call(gr,go)),h265:!!((As=(Sr=Ze())==null?void 0:Sr.isTypeSupported)!=null&&As.call(Sr,So)),vp9:!!((ws=(vr=Ze())==null?void 0:vr.isTypeSupported)!=null&&ws.call(vr,Ms)),av1:!!((Ls=(yr=Ze())==null?void 0:yr.isTypeSupported)!=null&&Ls.call(yr,Cs)),aac:!!(($s=(Tr=Ze())==null?void 0:Tr.isTypeSupported)!=null&&$s.call(Tr,vo)),opus:!!((Rs=(Ir=Ze())==null?void 0:Ir.isTypeSupported)!=null&&Rs.call(Ir,yo))},Vi=(Ge.h264||Ge.h265)&&Ge.aac,wt,To=()=>B(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(q(C({},n),{video:q(C({},n.video),{contentType:Cs})})),window.navigator.mediaCapabilities.decodingInfo(q(C({},n),{video:q(C({},n.video),{contentType:Ms})}))]);wt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{To()}catch(n){console.error(n)}var _t=At.hls&&Me.mp4,Bs=()=>Object.keys(Ge).filter(n=>Ge[n]),Vs=(n,e=!1,t=!1)=>{let i=At.mse||At.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&Me.mp4&&Vi;case"DASH_WEBM":return i&&Me.webm&&Ge.vp9&&Ge.opus;case"DASH_WEBM_AV1":return i&&Me.webm&&Ge.av1&&Ge.opus;case"DASH_LIVE":return At.mse&&Me.mp4&&Vi;case"DASH_LIVE_CMAF":return i&&Me.mp4&&Vi&&Me.cmaf;case"DASH_ONDEMAND":return i&&Me.mp4&&Vi;case"HLS":case"HLS_ONDEMAND":return _t||e&&At.mse&&Me.mp4&&Vi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _t;case"MPEG":return Me.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return At.webrtc&&At.ws&&Ge.h264&&(Me.mp4||Me.webm);default:return(0,Ee.assertNever)(r)}})},pt=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return wt?wt[t].smooth?[t,e]:wt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return wt?wt[t].powerEfficient?[t,e]:wt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Ee.assertNever)(n)}return[e,t]},Os=({webmCodec:n,androidPreferredFormat:e})=>{if(Ds)switch(e){case"mpeg":return["MPEG",...pt(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...pt(n),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...pt(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...pt(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...pt(n),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...pt(n),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:(0,Ee.assertNever)(e)}return _t?[...pt(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...pt(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Ns=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=(0,Ee.getCurrentBrowser)().device===Ee.CurrentClientDevice.Mac&&(0,Ee.getCurrentBrowser)().browser===Ee.CurrentClientBrowser.Safari;if(Ds)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:(0,Ee.assertNever)(n)}else _t&&!u?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ra=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];var et=require("@vkontakte/videoplayer-shared"),_s=n=>new et.Observable(e=>{let t=new et.Subscription,i=n.desiredPlaybackState$.stateChangeStarted$.pipe((0,et.map)(({from:d,to:l})=>`${d}-${l}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe((0,et.map)(({type:d})=>d!==void 0)),s=new et.Subject,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var ke=require("@vkontakte/videoplayer-shared");var Oi=null,Er=null;function aa(){return Oi||(Oi=new(window.AudioContext||window.webkitAudioContext)),Er||(Er=new GainNode(Oi,{gain:1}),Er.connect(Oi.destination)),{audioCtx:Oi,gainNode:Er}}var xr=require("@vkontakte/videoplayer-shared");var Ft=class Ft{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new ke.Subscription;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe((0,ke.filter)(s=>!!s.type),(0,ke.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){let{browser:t}=(0,xr.getCurrentBrowser)();t===xr.CurrentClientBrowser.Safari&&e!=="MPEG"||this.subscriptions.add((0,ke.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,ke.filter)(({playbackState:i,video:r,volume:{muted:a,volume:s}})=>i==="playing"&&!!r&&!a&&!!s),(0,ke.once)()).subscribe(({video:i})=>this.initAudioContextOnce(i)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=aa(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{var s;if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Ft.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(o){this.volumeMultiplierError$.next({id:Ft.errorId,category:ke.ErrorCategory.VIDEO_PIPELINE,message:(s=o==null?void 0:o.message)!=null?s:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(s=>{var o;this.volumeMultiplierError$.next({id:Ft.errorId,category:ke.ErrorCategory.VIDEO_PIPELINE,message:(o=s==null?void 0:s.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=aa();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Ft.errorId="VolumeMultiplierManager";var Ni=Ft;var Io={chunkDuration:5e3,maxParallelRequests:5},_i=class{constructor(e){this.current$=new v.ValueSubject({type:void 0});this.providerError$=new v.Subject;this.noAvailableProvidersError$=new v.Subject;this.volumeMultiplierError$=new v.Subject;this.providerOutput={position$:new v.ValueSubject(0),duration$:new v.ValueSubject(1/0),volume$:new v.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new v.ValueSubject(void 0),currentVideoSegmentLength$:new v.ValueSubject(0),currentAudioSegmentLength$:new v.ValueSubject(0),availableVideoTracks$:new v.ValueSubject([]),availableAudioTracks$:new v.ValueSubject([]),isAudioAvailable$:new v.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new v.ValueSubject(!1),autoVideoTrackLimits$:new v.ValueSubject(void 0),currentBuffer$:new v.ValueSubject(void 0),isBuffering$:new v.ValueSubject(!0),error$:new v.Subject,warning$:new v.Subject,willSeekEvent$:new v.Subject,seekedEvent$:new v.Subject,loopedEvent$:new v.Subject,endedEvent$:new v.Subject,firstBytesEvent$:new v.Subject,firstFrameEvent$:new v.Subject,canplay$:new v.Subject,isLive$:new v.ValueSubject(void 0),isLowLatency$:new v.ValueSubject(!1),canChangePlaybackSpeed$:new v.ValueSubject(!0),liveTime$:new v.ValueSubject(void 0),liveBufferTime$:new v.ValueSubject(void 0),availableTextTracks$:new v.ValueSubject([]),currentTextTrack$:new v.ValueSubject(void 0),hostname$:new v.ValueSubject(void 0),httpConnectionType$:new v.ValueSubject(void 0),httpConnectionReused$:new v.ValueSubject(void 0),inPiP$:new v.ValueSubject(!1),inFullscreen$:new v.ValueSubject(!1),element$:new v.ValueSubject(void 0),elementVisible$:new v.ValueSubject(!0),availableSources$:new v.ValueSubject(void 0),is3DVideo$:new v.ValueSubject(!1),playbackState$:new v.ValueSubject("")};this.subscription=new v.Subscription;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Vs([...Ns(this.params.tuning),...Os(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>(0,v.isNonNullable)(e.sources[u])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(u=>!r.includes(u)),...t.filter(u=>r.includes(u))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Bi(a);let s=[...ra(!0),...ra(!1)];this.chromecastFormatsIterator=new Bi(s.filter(u=>(0,v.isNonNullable)(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Ni(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,v.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:v.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}e.destroy();let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,v.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,v.assertNonNullable)(o),new wi(q(C({},s),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Li(q(C({},s),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),_t||!this.params.tuning.useHlsJs?new Di(q(C({},s),{source:o})):new $i(q(C({},s),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Ri(q(C({},s),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Mi(q(C({},s),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Ga(q(C({},s),{source:o,config:q(C({},Io),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,v.assertNonNullable)(o),new Ci({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return(0,v.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,v.assertNonNullable)(o),new Yt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,v.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,v.assertNever)(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(0,v.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return q(C({},e),{url:i(e.url)})}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new v.Subscription,t=!1,i=0;return e.add((0,v.merge)(this.providerOutput.error$,_s({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,v.map)(r=>({id:`ProviderHangup:${r}`,category:v.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,v.filter)(({to:a})=>a==="playing"),(0,v.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let s=r.category===v.ErrorCategory.NETWORK,o=r.category===v.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:"SCREEN")}})),e}};var V=require("@vkontakte/videoplayer-shared");var Eo=5e3,Fs="one_video_throughput",Us="one_video_rtt",tt=window.navigator.connection,Hs=()=>{let n=tt==null?void 0:tt.downlink;if((0,V.isNonNullable)(n)&&n!==10)return n*1e3},Gs=()=>{let n=tt==null?void 0:tt.rtt;if((0,V.isNonNullable)(n)&&n!==3e3)return n},Qs=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},sa=class n{constructor(e){this.subscription=new V.Subscription;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=n.load(Fs)||(e.useBrowserEstimation?Hs():void 0)||Eo,i=(a=(r=n.load(Us))!=null?r:e.useBrowserEstimation?Gs():void 0)!=null?a:0;if(this.throughput$=new V.ValueSubject(t),this.rtt$=new V.ValueSubject(i),this.rttAdjustedThroughput$=new V.ValueSubject(Qs(t,i,e.rttPenaltyRequestSize)),this.throughput=xt.getSmoothedValue(t,-1,e),this.rtt=xt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let s=()=>{let u=Hs();u&&this.throughput.next(u);let d=Gs();(0,V.isNonNullable)(d)&&this.rtt.next(d)};tt&&"onchange"in tt&&this.subscription.add((0,V.fromEvent)(tt,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{V.safeStorage.set(Fs,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{V.safeStorage.set(Us,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,V.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,V.map)(({throughput:s,rtt:o})=>Qs(s,o,e.rttPenaltyRequestSize)),(0,V.filter)(s=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,V.now)(),r=new V.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,V.fromEvent)(e,"progress").pipe((0,V.once)()).subscribe(a=>{t=a.loaded,i=(0,V.now)()}));break;case 1:case 0:r.add((0,V.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,V.now)()}));break}r.add((0,V.fromEvent)(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=(0,V.now)(),u=s-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=(0,V.now)(),s=0,o=(0,V.now)(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=h=>B(this,[h],function*({done:l,value:c}){if(l)!t&&this.addRawSpeed(r,(0,V.now)()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let m=(0,V.now)();if(m-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||m-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-a;b&&this.addRawSpeed(s,b,1,t),s=c.byteLength,a=(0,V.now)()}else s+=c.byteLength;o=(0,V.now)()}else r+=c.byteLength,s+=c.byteLength,s>=this.tuningConfig.streamMinSampleSize&&(0,V.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,(0,V.now)()-o,this.concurrentDownloads.size),s=0,o=(0,V.now)());yield i==null?void 0:i.read().then(d,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=V.safeStorage.get(e);if((0,V.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},Ws=sa;var Fi=require("@vkontakte/videoplayer-shared");var js={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Fi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Fi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:200,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,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},Ys=n=>{var e;return q(C({},(0,Fi.fillWithDefault)(n,js)),{configName:[...(e=n.configName)!=null?e:[],...js.configName]})};var p=require("@vkontakte/videoplayer-shared");var it=require("@vkontakte/videoplayer-shared"),na=({seekState:n,position$:e})=>(0,it.merge)(n.stateChangeEnded$.pipe((0,it.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,it.filter)(it.isNonNullable)),e.pipe((0,it.filter)(()=>n.getState().state==="none")));var qs=require("@vkontakte/videoplayer-shared"),zs=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return(0,qs.assertNonNullable)(e,`Wrong container or containerId {${n.container}}`),e};var Pr=require("@vkontakte/videoplayer-shared"),Ks=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Pr.filter)(r=>r.length>0),(0,Pr.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(n)};var Ui=class{constructor(e={configName:[]}){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new G("stopped"),seekState:new G({state:"none"}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),internalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({}),cameraOrientation:new G({x:0,y:0})};this.info={playbackState$:new p.ValueSubject("stopped"),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,firstBytes$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:_a};if(this.initLogs(),this.tuning=Ys(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Xi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ws(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...s)=>{try{return a.apply(t,s)}catch(o){let u=s.map(c=>JSON.stringify(c,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:p.ErrorCategory.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=zs(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new _i({sources:e.sources,meta:(i=e.meta)!=null?i:{},failoverHosts:(r=e.failoverHosts)!=null?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Zt()?(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;(0,p.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>C({type:"external"},t))),this}selectTextTrack(e){var t;return Ks(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,p.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let s=this.desiredState.seekState.getState();s.state==="requested"?this.desiredState.seekState.setState(q(C({},s),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(s=>s.destination),(0,p.filterChanged)()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe((0,p.map)(s=>s.map(({quality:o})=>o).sort((o,u)=>(0,p.isInvariantQuality)(o)?1:(0,p.isInvariantQuality)(u)?-1:(0,p.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s==null?void 0:s.quality),this.info.videoBitrate$.next(s==null?void 0:s.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(s=>{this.desiredState.autoVideoTrackLimits.setState(s!=null?s:{})})).add(e.providerOutput.currentBuffer$.pipe((0,p.map)(s=>s?{start:s.from,end:s.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add((0,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(s=>s.to),(0,p.filterChanged)(),(0,p.map)(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:na({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),(0,p.filterChanged)(),(0,p.tap)(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(s=>s.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(s=>s.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(na({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,p.map)(s=>({id:s?`No${s}`:"NoProviders",category:p.ErrorCategory.VIDEO_PIPELINE,message:s?`${s} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,p.once)(),(0,p.map)(s=>s!=null?s:(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-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 p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:s})=>s==="playing"),(0,p.once)()).subscribe(()=>i.next(!1)));let r=0,a=(0,p.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,p.map)(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),(0,p.filterChanged)());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,p.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s==null?void 0:s.videoWidth,height:s==null?void 0:s.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{var u,d;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=s==null?void 0:s.size)==null?void 0:u.width,height:(d=s==null?void 0:s.size)==null?void 0:d.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,p.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),c;l==="CONNECTED"?c="second_screen":u?d?s?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,p.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(i=>i.length>0),(0,p.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=lt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),Na(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Oa(i)),this.providerContainer.current$.subscribe(({type:i})=>zt("provider",i)),e.duration$.subscribe(i=>zt("duration",i)),e.availableVideoTracks$.pipe((0,p.filter)(i=>!!i.length),(0,p.once)()).subscribe(i=>zt("tracks",i)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe((0,p.map)(i=>i==null?void 0:i.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(i=>this.subscription.add(i)),zt("codecs",Bs())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>B(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:p.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!(e!=null&&e.released);r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var Qe=require("@vkontakte/videoplayer-shared"),xo=`@vkontakte/videoplayer-core@${Vr}`;
|