@vkontakte/videoplayer-core 2.0.143-dev.d2cefd48.0 → 2.0.143-dev.e771e267.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 +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +5 -5
- package/es2024.cjs.js +11 -11
- package/es2024.esm.js +13 -13
- package/esnext.cjs.js +11 -11
- package/esnext.esm.js +13 -13
- package/evergreen.esm.js +5 -5
- package/package.json +2 -2
- package/types/providers/utils/StallsManager.d.ts +0 -2
- package/types/utils/tuningConfig.d.ts +0 -1
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.143-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.143-dev.e771e267.0
|
|
3
|
+
* Tue, 21 Oct 2025 08:07:03 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-143/doc/
|
|
5
5
|
*/
|
|
6
|
-
var io="2.0.143-dev.d2cefd48.0";var ye=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ye||{}),et=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_FMP4="HLS_FMP4",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(et||{});var ns=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ns||{}),Pa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Pa||{});var La=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(La||{}),os=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(os||{});import{assertNever as uo,assertNonNullable as nd,isNonNullable as us,ValueSubject as Ra,Subject as od,Subscription as ud,merge as ld,observableFrom as dd,fromEvent as so,map as ao,tap as no,filterChanged as cd,isNullable as Ma,ErrorCategory as oo}from"@vkontakte/videoplayer-shared/evergreen";var ro=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ls=class{constructor(e){this.connection$=new Ra(void 0);this.castState$=new Ra("NOT_AVAILABLE");this.errorEvent$=new od;this.realCastState$=new Ra("NOT_AVAILABLE");this.subscription=new ud;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=us(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||ro("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oo.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){us(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ma(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ma(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(so(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return uo(r.sessionState)}})).add(ld(so(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(no(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),ao(r=>r.castState)),dd([i.getCastState()])).pipe(cd(),ao(hd),no(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=us(this.connection$.getValue());if(s&&!a){let u=i.getCurrentSession();nd(u);let n=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Ma(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:n}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?us(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:oo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},hd=o=>{switch(o){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return uo(o)}};import{assertNever as lo}from"@vkontakte/videoplayer-shared/evergreen";var J=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:lo(t)}return o},pt=(o,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(o);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(o);return Number(t.searchParams.get("offset_p")??0)}default:lo(e)}};var k=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as pd,Subject as ds,merge as co}from"@vkontakte/videoplayer-shared/evergreen";var C=class{constructor(e){this.transitionStarted$=new ds;this.transitionEnded$=new ds;this.transitionUpdated$=new ds;this.forceChanged$=new ds;this.stateChangeStarted$=co(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=co(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||pd(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as go}from"@vkontakte/videoplayer-shared/evergreen";var cs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,n=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||n||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Li=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var hs=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Li()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var ps=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ae=()=>window.ManagedMediaSource||window.MediaSource,Jt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),ho=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ms=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var md=document.createElement("video"),fd='video/mp4; codecs="avc1.42000a,mp4a.40.2"',bd='video/mp4; codecs="hev1.1.6.L93.B0"',po='video/webm; codecs="vp09.00.10.08"',mo='video/webm; codecs="av01.0.00M.08"',gd='audio/mp4; codecs="mp4a.40.2"',Sd='audio/webm; codecs="opus"',fo,vd=async()=>{if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:mo}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:po}})]);fo={DASH_WEBM_AV1:e,DASH_WEBM:t}};vd().catch(o=>{console.log(md),console.error(o)});var fs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return fo}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:Jt(),mse:ho(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ae()?.isTypeSupported?.(fd),t=!!Ae()?.isTypeSupported?.(bd),i=!!Ae()?.isTypeSupported?.(gd);this._codecs={h264:e,h265:t,vp9:!!Ae()?.isTypeSupported?.(po),av1:!!Ae()?.isTypeSupported?.(mo),aac:i,opus:!!Ae()?.isTypeSupported?.(Sd),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var bo="audio/mpeg",bs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(bo)},this._codecs={mp3:!!Ae()?.isTypeSupported?.(bo)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as yd}from"@vkontakte/videoplayer-shared/evergreen";var Da=class{constructor(){this.isInited$=new yd(!1);this._displayChecker=new ps,this._deviceChecker=new hs(this._displayChecker),this._browserChecker=new cs,this._videoChecker=new fs(this._deviceChecker,this._browserChecker),this._audioChecker=new bs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},D=new Da;var Ba=o=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=D.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return o.filter(u=>{switch(u){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return go(u)}})},Va=o=>{switch(o){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":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 go(o)}},Td=o=>{let t=Object.keys(o).filter(i=>!Va(i));return Ba(t).length>0};import{assertNever as Zt,assertNonNullable as Mt,debounce as So,ErrorCategory as vo,fromEvent as Dt,isNonNullable as yo,map as To,merge as Io,observableFrom as Id,Subject as Ed,Subscription as Ca,timeout as xd,getHighestQuality as wd}from"@vkontakte/videoplayer-shared/evergreen";var kd=5,Ad=5,$d=500,Eo=7e3,Ri=class{constructor(e){this.subscription=new Ca;this.loadMediaTimeoutSubscription=new Ca;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Zt(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:Zt(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:Zt(e)}break}default:Zt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Va(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 Ca;this.subscription.add(e),this.subscription.add(Io(this.videoState.stateChangeStarted$.pipe(To(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(To(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new Ed;e.add(r.pipe(So($d)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let u=a.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>kd)&&r.next(u),s=u})),e.add(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,u=this.params.output.isBuffering$.getValue(),n=a===chrome.cast.media.PlayerState.BUFFERING;switch(u!==n&&this.params.output.isBuffering$.next(n),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Ad&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:Zt(a)}}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Io(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Id(["init"])).pipe(So(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];Mt(l);let h=wd(Object.keys(l));Mt(h);let d=l[h];Mt(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];Mt(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Mt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Mt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Mt(l),i=J(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",h=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:vo.VIDEO_PIPELINE,message:l,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Zt(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:n}=this.params.meta;return yo(u)&&(a.metadata.title=u),yo(n)&&(a.metadata.subtitle=n),a}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(xd(Eo).subscribe(()=>s(`timeout(${Eo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:vo.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as wo}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Pd}from"@vkontakte/videoplayer-shared/evergreen";var xo=o=>{try{o.pause(),o.playbackRate=0,Pd(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as Ld,Subscription as Rd}from"@vkontakte/videoplayer-shared/evergreen";var Oa=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)}},Fa=window.WeakMap?new WeakMap:new Oa,_a=window.WeakMap?new WeakMap:new Map,Md=(o,e=20)=>{let t=0;return Ld(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},Te=(o,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=o.querySelector("video"),r=!!i;i?wo(i):(i=document.createElement("video"),o.appendChild(i)),Fa.set(i,r);let s=new Rd;return s.add(Md(i,e)),_a.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ie=o=>{_a.get(o)?.unsubscribe(),_a.delete(o);let t=Fa.get(o);Fa.delete(o),t?wo(o):xo(o)};import{assertNonNullable as Di,isNonNullable as ze,isNullable as Vd,fromEvent as ei,merge as ko,observableFrom as Ao,filterChanged as $o,map as Bi,Subject as Po,Subscription as Cd,ValueSubject as Od,ErrorCategory as Fd}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Na,isNullable as Dd,Subscription as Bd}from"@vkontakte/videoplayer-shared/evergreen";var gs=(o,e,t,{equal:i=(a,u)=>a===u,changed$:r,onError:s}={})=>{let a=o.getState(),u=e(),n=Dd(r),l=new Bd;return r&&l.add(r.subscribe(h=>{let d=o.getState();i(h,d)&&o.setState(h)},s)),i(u,a)||(t(a),n&&o.setState(a)),l.add(o.stateChangeStarted$.subscribe(h=>{t(h.to),n&&o.setState(h.to)},s)),l},qe=(o,e,t)=>gs(e,()=>o.loop,i=>{Na(i)&&(o.loop=i)},{onError:t}),Ee=(o,e,t,i)=>gs(e,()=>({muted:o.muted,volume:o.volume}),r=>{Na(r)&&(o.muted=r.muted,o.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(o,e,t,i)=>gs(e,()=>o.playbackRate,r=>{Na(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Mi=gs;var _d=o=>["__",o.language,o.label].join("|"),Nd=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},Ua=class o{constructor(e){this.available$=new Po;this.current$=new Od(void 0);this.error$=new Po;this.subscription=new Cd;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:Fd.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Mi(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{ze(s)&&this.setInternal(s)},{equal:(s,a)=>ze(s)&&ze(a)&&s.length===a.length&&s.every(({id:u},n)=>u===a[n].id),changed$:this.available$.pipe(Bi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Mi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{ze(s)&&this.setExternal(s)},{equal:(s,a)=>ze(s)&&ze(a)&&s.length===a.length&&s.every(({id:u},n)=>u===a[n].id),changed$:this.available$.pipe(Bi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Mi(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Mi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Di(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ko(ei(e,"addtrack"),ei(e,"removetrack"),Ao(["init"])).pipe(Bi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),$o((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(ko(ei(e,"change"),Ao(["init"])).pipe(Bi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Bi(i=>i&&this.htmlTextTrackToITextTrack(i).id),$o()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ei(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ei(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;ze(t.align)&&(r.align=t.align),ze(t.position)&&(r.position=t.position),ze(t.size)&&(r.size=t.size),ze(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Di(this.video);let t=[...this.video.textTracks];return e?t:t.filter(o.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:_d(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Di(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Vd(e)||!Nd(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Di(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Di(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)}},Be=Ua;var Bt=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 Lo=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ha=o=>{let e=Lo(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},Ro=o=>{let e=Lo(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as fe,map as Ge,merge as Ss,filterChanged as Do,isNonNullable as Bo,Subject as Hd,filter as ja,mapTo as Qa,combine as jd,once as Qd,shareReplay as be,throttle as Wd,ErrorCategory as qd,ValueSubject as Vo,Subscription as zd}from"@vkontakte/videoplayer-shared/evergreen";var Ud=3,Mo=(o,e,t=Ud)=>{let i=0,r=0;for(let s=0;s<o.length;s++){let a=o.start(s),u=o.end(s);if(a<=e&&e<=u){if(i=a,r=u,!t)return{from:i,to:r};for(let n=s-1;n>=0;n--)o.end(n)+t>=i&&(i=o.start(n));for(let n=s+1;n<o.length;n++)o.start(n)-t<=r&&(r=o.end(n))}}return{from:i,to:r}};var xe=o=>{let e=E=>fe(o,E).pipe(Qa(void 0),be(1)),t=new zd,i=()=>t.unsubscribe(),r=Ss(fe(o,"progress"),fe(o,"timeupdate")).pipe(Ge(()=>Mo(o.buffered,o.currentTime)),be(1)),s=D.browser.isSafari?jd({play:e("play").pipe(Qd()),playing:e("playing")}).pipe(Qa(void 0),be(1)):e("playing"),a=fe(o,"volumechange").pipe(Ge(()=>({muted:o.muted,volume:o.volume})),be(1)),u=fe(o,"ratechange").pipe(Ge(()=>o.playbackRate),be(1)),n=fe(o,"error").pipe(ja(()=>!!(o.error||o.played.length)),Ge(()=>{let E=o.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:qd.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:o.error??void 0}}),be(1)),l=fe(o,"timeupdate").pipe(Ge(()=>o.currentTime),be(1)),h=["waiting","seeking","seeked","timeupdate"],d=new Hd,c=.3,p;t.add(Ss(...h.map(E=>fe(o,E))).subscribe(E=>{let O=o.currentTime;o.loop&&Bo(p)&&Bo(O)&&p>=o.duration-c&&O<=c&&d.next(p),p=O}));let m=e("pause").pipe(ja(()=>!o.error&&p!==o.duration),be(1)),f=fe(o,"enterpictureinpicture").pipe(be(1)),b=fe(o,"leavepictureinpicture").pipe(be(1)),g=new Vo(Ro(o));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let y=new Vo(Ha(o)),T=fe(o,"fullscreenchange").pipe(be(1));t.add(T.pipe(Ge(()=>Ha(o))).subscribe(y));let S=.1,x=1e3,P=fe(o,"timeupdate").pipe(Ge(E=>o.duration-o.currentTime<S),Do(),be(1)),A=Ss(P.pipe(ja(E=>!o.loop&&E)),fe(o,"ended")).pipe(Wd(x),Qa(void 0),be(1)),R=Ss(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>fe(o,E)),P.pipe(Ge(E=>({type:E?"ended":"unknown"})))).pipe(Ge(E=>D.browser.isFirefox&&E.type==="ended"?o.readyState<2:o.readyState<3),Do(),be(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:A,looped$:d,error$:n,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:fe(o,"durationchange").pipe(Ge(()=>o.duration),be(1)),isBuffering$:R,currentBuffer$:r,volumeState$:a,playbackRateState$:u,inPiP$:g,inFullscreen$:y,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as mt}from"@vkontakte/videoplayer-shared/evergreen";var ft=o=>{switch(o){case"mobile":return mt.Q_144P;case"lowest":return mt.Q_240P;case"low":return mt.Q_360P;case"sd":case"medium":return mt.Q_480P;case"hd":case"high":return mt.Q_720P;case"fullhd":case"full":return mt.Q_1080P;case"quadhd":case"quad":return mt.Q_1440P;case"ultrahd":case"ultra":return mt.Q_2160P}};import{isNonNullable as q,isNullable as Is,now as qo,isHigher as Es,isHigherOrEqual as Vt,isInvariantQuality as xs,isLowerOrEqual as ii,videoSizeToQuality as zo,assertNotEmptyArray as ws,assertNonNullable as Go}from"@vkontakte/videoplayer-shared/evergreen";var Wa=!1,it={},Co=o=>{Wa=o},Oo=()=>{it={}},Fo=o=>{o(it)},Vi=(o,e)=>{Wa&&(it.meta=it.meta??{},it.meta[o]=e)},ge=class{constructor(e){this.name=e}next(e){if(!Wa)return;it.series=it.series??{};let t=it.series[this.name]??[];t.push([Date.now(),e]),it.series[this.name]=t}};import{isHigher as Gd,isHigherOrEqual as qb,isLower as _o,isLowerOrEqual as zb,isNonNullable as vs,isNullable as Yd,videoHeightToQuality as ys}from"@vkontakte/videoplayer-shared/evergreen";function No(o,e,t){return!o.max&&o.min===e?"high_quality":!o.min&&o.max===t?"traffic_saving":"unknown"}function ti(o,e,t){return Yd(o)||vs(o.min)&&vs(o.max)&&_o(o.max,o.min)||vs(o.min)&&e&&Gd(o.min,e)||vs(o.max)&&t&&_o(o.max,t)}function Uo({limits:o,highestAvailableHeight:e,lowestAvailableHeight:t}){return ti({max:o?.max?ys(o.max):void 0,min:o?.min?ys(o.min):void 0},e?ys(e):void 0,t?ys(t):void 0)}var Yo=new ge("best_bitrate"),ks=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t;var ri=o=>(e,t)=>o*(Number(e.bitrate)-Number(t.bitrate)),bt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=qo()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},As='Assertion "ABR Tracks is empty array" failed',Ts=new WeakMap,Ho=new WeakMap,jo=new WeakMap,Ci=(o,e,t,i)=>{let r=[...e].sort(ri(1)),s=[...t].sort(ri(1)),a=s.filter(n=>q(n.bitrate)&&q(o.bitrate)?o.bitrate/n.bitrate>i:!0),u=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Oi=(o,e,t,i)=>{let r=Ts.get(e);r||(r=[...e].sort(ri(1)),Ts.set(e,r));let s=Ts.get(t);s||(s=[...t].sort(ri(1)),Ts.set(t,s));let a=jo.get(o);a||(a=s.filter(n=>q(n.bitrate)&&q(o.bitrate)?o.bitrate/n.bitrate>i:!0),jo.set(o,a));let u=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Qo=o=>"quality"in o,$s=(o,e,t,i)=>{let r=q(i?.last?.bitrate)&&q(t?.bitrate)&&i.last.bitrate<t.bitrate?o.trackCooldownIncreaseQuality:o.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&qo()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let u=Qo(a)?"video":"audio",n=Qo(a)?a.quality:a.bitrate;return e({message:`
|
|
6
|
+
var io="2.0.143-dev.e771e267.0";var ye=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ye||{}),et=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_FMP4="HLS_FMP4",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(et||{});var ns=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ns||{}),Pa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Pa||{});var La=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(La||{}),os=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(os||{});import{assertNever as uo,assertNonNullable as nd,isNonNullable as us,ValueSubject as Ra,Subject as od,Subscription as ud,merge as ld,observableFrom as dd,fromEvent as so,map as ao,tap as no,filterChanged as cd,isNullable as Ma,ErrorCategory as oo}from"@vkontakte/videoplayer-shared/evergreen";var ro=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ls=class{constructor(e){this.connection$=new Ra(void 0);this.castState$=new Ra("NOT_AVAILABLE");this.errorEvent$=new od;this.realCastState$=new Ra("NOT_AVAILABLE");this.subscription=new ud;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=us(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||ro("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oo.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){us(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ma(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ma(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(so(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return uo(r.sessionState)}})).add(ld(so(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(no(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),ao(r=>r.castState)),dd([i.getCastState()])).pipe(cd(),ao(hd),no(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=us(this.connection$.getValue());if(s&&!a){let u=i.getCurrentSession();nd(u);let n=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Ma(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:n}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?us(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:oo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},hd=o=>{switch(o){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return uo(o)}};import{assertNever as lo}from"@vkontakte/videoplayer-shared/evergreen";var J=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:lo(t)}return o},pt=(o,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(o);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(o);return Number(t.searchParams.get("offset_p")??0)}default:lo(e)}};var k=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as pd,Subject as ds,merge as co}from"@vkontakte/videoplayer-shared/evergreen";var C=class{constructor(e){this.transitionStarted$=new ds;this.transitionEnded$=new ds;this.transitionUpdated$=new ds;this.forceChanged$=new ds;this.stateChangeStarted$=co(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=co(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||pd(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as go}from"@vkontakte/videoplayer-shared/evergreen";var cs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,n=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||n||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Li=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var hs=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Li()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var ps=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ae=()=>window.ManagedMediaSource||window.MediaSource,Jt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),ho=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ms=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var md=document.createElement("video"),fd='video/mp4; codecs="avc1.42000a,mp4a.40.2"',bd='video/mp4; codecs="hev1.1.6.L93.B0"',po='video/webm; codecs="vp09.00.10.08"',mo='video/webm; codecs="av01.0.00M.08"',gd='audio/mp4; codecs="mp4a.40.2"',Sd='audio/webm; codecs="opus"',fo,vd=async()=>{if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:mo}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:po}})]);fo={DASH_WEBM_AV1:e,DASH_WEBM:t}};vd().catch(o=>{console.log(md),console.error(o)});var fs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return fo}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:Jt(),mse:ho(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ae()?.isTypeSupported?.(fd),t=!!Ae()?.isTypeSupported?.(bd),i=!!Ae()?.isTypeSupported?.(gd);this._codecs={h264:e,h265:t,vp9:!!Ae()?.isTypeSupported?.(po),av1:!!Ae()?.isTypeSupported?.(mo),aac:i,opus:!!Ae()?.isTypeSupported?.(Sd),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var bo="audio/mpeg",bs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(bo)},this._codecs={mp3:!!Ae()?.isTypeSupported?.(bo)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as yd}from"@vkontakte/videoplayer-shared/evergreen";var Da=class{constructor(){this.isInited$=new yd(!1);this._displayChecker=new ps,this._deviceChecker=new hs(this._displayChecker),this._browserChecker=new cs,this._videoChecker=new fs(this._deviceChecker,this._browserChecker),this._audioChecker=new bs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},D=new Da;var Ba=o=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=D.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return o.filter(u=>{switch(u){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return go(u)}})},Va=o=>{switch(o){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":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 go(o)}},Td=o=>{let t=Object.keys(o).filter(i=>!Va(i));return Ba(t).length>0};import{assertNever as Zt,assertNonNullable as Mt,debounce as So,ErrorCategory as vo,fromEvent as Dt,isNonNullable as yo,map as To,merge as Io,observableFrom as Id,Subject as Ed,Subscription as Ca,timeout as xd,getHighestQuality as wd}from"@vkontakte/videoplayer-shared/evergreen";var kd=5,Ad=5,$d=500,Eo=7e3,Ri=class{constructor(e){this.subscription=new Ca;this.loadMediaTimeoutSubscription=new Ca;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Zt(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:Zt(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:Zt(e)}break}default:Zt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Va(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 Ca;this.subscription.add(e),this.subscription.add(Io(this.videoState.stateChangeStarted$.pipe(To(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(To(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new Ed;e.add(r.pipe(So($d)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(a=>{this.logRemoteEvent(a);let u=a.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>kd)&&r.next(u),s=u})),e.add(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,a=r.value,u=this.params.output.isBuffering$.getValue(),n=a===chrome.cast.media.PlayerState.BUFFERING;switch(u!==n&&this.params.output.isBuffering$.next(n),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Ad&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:Zt(a)}}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Io(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Id(["init"])).pipe(So(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];Mt(l);let h=wd(Object.keys(l));Mt(h);let d=l[h];Mt(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];Mt(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Mt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Mt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Mt(l),i=J(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",h=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:vo.VIDEO_PIPELINE,message:l,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Zt(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:n}=this.params.meta;return yo(u)&&(a.metadata.title=u),yo(n)&&(a.metadata.subtitle=n),a}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(xd(Eo).subscribe(()=>s(`timeout(${Eo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:vo.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as wo}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Pd}from"@vkontakte/videoplayer-shared/evergreen";var xo=o=>{try{o.pause(),o.playbackRate=0,Pd(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as Ld,Subscription as Rd}from"@vkontakte/videoplayer-shared/evergreen";var Oa=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)}},Fa=window.WeakMap?new WeakMap:new Oa,_a=window.WeakMap?new WeakMap:new Map,Md=(o,e=20)=>{let t=0;return Ld(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},Te=(o,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=o.querySelector("video"),r=!!i;i?wo(i):(i=document.createElement("video"),o.appendChild(i)),Fa.set(i,r);let s=new Rd;return s.add(Md(i,e)),_a.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ie=o=>{_a.get(o)?.unsubscribe(),_a.delete(o);let t=Fa.get(o);Fa.delete(o),t?wo(o):xo(o)};import{assertNonNullable as Di,isNonNullable as ze,isNullable as Vd,fromEvent as ei,merge as ko,observableFrom as Ao,filterChanged as $o,map as Bi,Subject as Po,Subscription as Cd,ValueSubject as Od,ErrorCategory as Fd}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Na,isNullable as Dd,Subscription as Bd}from"@vkontakte/videoplayer-shared/evergreen";var gs=(o,e,t,{equal:i=(a,u)=>a===u,changed$:r,onError:s}={})=>{let a=o.getState(),u=e(),n=Dd(r),l=new Bd;return r&&l.add(r.subscribe(h=>{let d=o.getState();i(h,d)&&o.setState(h)},s)),i(u,a)||(t(a),n&&o.setState(a)),l.add(o.stateChangeStarted$.subscribe(h=>{t(h.to),n&&o.setState(h.to)},s)),l},qe=(o,e,t)=>gs(e,()=>o.loop,i=>{Na(i)&&(o.loop=i)},{onError:t}),Ee=(o,e,t,i)=>gs(e,()=>({muted:o.muted,volume:o.volume}),r=>{Na(r)&&(o.muted=r.muted,o.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(o,e,t,i)=>gs(e,()=>o.playbackRate,r=>{Na(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Mi=gs;var _d=o=>["__",o.language,o.label].join("|"),Nd=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},Ua=class o{constructor(e){this.available$=new Po;this.current$=new Od(void 0);this.error$=new Po;this.subscription=new Cd;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:Fd.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Mi(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{ze(s)&&this.setInternal(s)},{equal:(s,a)=>ze(s)&&ze(a)&&s.length===a.length&&s.every(({id:u},n)=>u===a[n].id),changed$:this.available$.pipe(Bi(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Mi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{ze(s)&&this.setExternal(s)},{equal:(s,a)=>ze(s)&&ze(a)&&s.length===a.length&&s.every(({id:u},n)=>u===a[n].id),changed$:this.available$.pipe(Bi(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(Mi(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:a})=>a==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Mi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Di(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ko(ei(e,"addtrack"),ei(e,"removetrack"),Ao(["init"])).pipe(Bi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),$o((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(ko(ei(e,"change"),Ao(["init"])).pipe(Bi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Bi(i=>i&&this.htmlTextTrackToITextTrack(i).id),$o()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ei(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let a=s.target?.cues??null;a&&a.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(ei(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;ze(t.align)&&(r.align=t.align),ze(t.position)&&(r.position=t.position),ze(t.size)&&(r.size=t.size),ze(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Di(this.video);let t=[...this.video.textTracks];return e?t:t.filter(o.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:_d(e),s=this.externalTracks.has(r),a=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{id:r,type:"external",isAuto:a,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:a,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,a])=>a.language===r&&a.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Di(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Vd(e)||!Nd(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Di(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Di(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)}},Be=Ua;var Bt=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 Lo=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ha=o=>{let e=Lo(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},Ro=o=>{let e=Lo(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as fe,map as Ge,merge as Ss,filterChanged as Do,isNonNullable as Bo,Subject as Hd,filter as ja,mapTo as Qa,combine as jd,once as Qd,shareReplay as be,throttle as Wd,ErrorCategory as qd,ValueSubject as Vo,Subscription as zd}from"@vkontakte/videoplayer-shared/evergreen";var Ud=3,Mo=(o,e,t=Ud)=>{let i=0,r=0;for(let s=0;s<o.length;s++){let a=o.start(s),u=o.end(s);if(a<=e&&e<=u){if(i=a,r=u,!t)return{from:i,to:r};for(let n=s-1;n>=0;n--)o.end(n)+t>=i&&(i=o.start(n));for(let n=s+1;n<o.length;n++)o.start(n)-t<=r&&(r=o.end(n))}}return{from:i,to:r}};var xe=o=>{let e=E=>fe(o,E).pipe(Qa(void 0),be(1)),t=new zd,i=()=>t.unsubscribe(),r=Ss(fe(o,"progress"),fe(o,"timeupdate")).pipe(Ge(()=>Mo(o.buffered,o.currentTime)),be(1)),s=D.browser.isSafari?jd({play:e("play").pipe(Qd()),playing:e("playing")}).pipe(Qa(void 0),be(1)):e("playing"),a=fe(o,"volumechange").pipe(Ge(()=>({muted:o.muted,volume:o.volume})),be(1)),u=fe(o,"ratechange").pipe(Ge(()=>o.playbackRate),be(1)),n=fe(o,"error").pipe(ja(()=>!!(o.error||o.played.length)),Ge(()=>{let E=o.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:qd.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:o.error??void 0}}),be(1)),l=fe(o,"timeupdate").pipe(Ge(()=>o.currentTime),be(1)),h=["waiting","seeking","seeked","timeupdate"],d=new Hd,c=.3,p;t.add(Ss(...h.map(E=>fe(o,E))).subscribe(E=>{let O=o.currentTime;o.loop&&Bo(p)&&Bo(O)&&p>=o.duration-c&&O<=c&&d.next(p),p=O}));let m=e("pause").pipe(ja(()=>!o.error&&p!==o.duration),be(1)),f=fe(o,"enterpictureinpicture").pipe(be(1)),b=fe(o,"leavepictureinpicture").pipe(be(1)),g=new Vo(Ro(o));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let y=new Vo(Ha(o)),T=fe(o,"fullscreenchange").pipe(be(1));t.add(T.pipe(Ge(()=>Ha(o))).subscribe(y));let S=.1,x=1e3,P=fe(o,"timeupdate").pipe(Ge(E=>o.duration-o.currentTime<S),Do(),be(1)),A=Ss(P.pipe(ja(E=>!o.loop&&E)),fe(o,"ended")).pipe(Wd(x),Qa(void 0),be(1)),R=Ss(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>fe(o,E)),P.pipe(Ge(E=>({type:E?"ended":"unknown"})))).pipe(Ge(E=>D.browser.isFirefox&&E.type==="ended"?o.readyState<2:o.readyState<3),Do(),be(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:A,looped$:d,error$:n,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:fe(o,"durationchange").pipe(Ge(()=>o.duration),be(1)),isBuffering$:R,currentBuffer$:r,volumeState$:a,playbackRateState$:u,inPiP$:g,inFullscreen$:y,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as mt}from"@vkontakte/videoplayer-shared/evergreen";var ft=o=>{switch(o){case"mobile":return mt.Q_144P;case"lowest":return mt.Q_240P;case"low":return mt.Q_360P;case"sd":case"medium":return mt.Q_480P;case"hd":case"high":return mt.Q_720P;case"fullhd":case"full":return mt.Q_1080P;case"quadhd":case"quad":return mt.Q_1440P;case"ultrahd":case"ultra":return mt.Q_2160P}};import{isNonNullable as q,isNullable as Is,now as qo,isHigher as Es,isHigherOrEqual as Vt,isInvariantQuality as xs,isLowerOrEqual as ii,videoSizeToQuality as zo,assertNotEmptyArray as ws,assertNonNullable as Go}from"@vkontakte/videoplayer-shared/evergreen";var Wa=!1,it={},Co=o=>{Wa=o},Oo=()=>{it={}},Fo=o=>{o(it)},Vi=(o,e)=>{Wa&&(it.meta=it.meta??{},it.meta[o]=e)},ge=class{constructor(e){this.name=e}next(e){if(!Wa)return;it.series=it.series??{};let t=it.series[this.name]??[];t.push([Date.now(),e]),it.series[this.name]=t}};import{isHigher as Gd,isHigherOrEqual as qb,isLower as _o,isLowerOrEqual as zb,isNonNullable as vs,isNullable as Yd,videoHeightToQuality as ys}from"@vkontakte/videoplayer-shared/evergreen";function No(o,e,t){return!o.max&&o.min===e?"high_quality":!o.min&&o.max===t?"traffic_saving":"unknown"}function ti(o,e,t){return Yd(o)||vs(o.min)&&vs(o.max)&&_o(o.max,o.min)||vs(o.min)&&e&&Gd(o.min,e)||vs(o.max)&&t&&_o(o.max,t)}function Uo({limits:o,highestAvailableHeight:e,lowestAvailableHeight:t}){return ti({max:o?.max?ys(o.max):void 0,min:o?.min?ys(o.min):void 0},e?ys(e):void 0,t?ys(t):void 0)}var Yo=new ge("best_bitrate"),ks=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t;var ri=o=>(e,t)=>o*(Number(e.bitrate)-Number(t.bitrate)),bt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=qo()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},As='Assertion "ABR Tracks is empty array" failed',Ts=new WeakMap,Ho=new WeakMap,jo=new WeakMap,Ci=(o,e,t,i)=>{let r=[...e].sort(ri(1)),s=[...t].sort(ri(1)),a=s.filter(n=>q(n.bitrate)&&q(o.bitrate)?o.bitrate/n.bitrate>i:!0),u=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Oi=(o,e,t,i)=>{let r=Ts.get(e);r||(r=[...e].sort(ri(1)),Ts.set(e,r));let s=Ts.get(t);s||(s=[...t].sort(ri(1)),Ts.set(t,s));let a=jo.get(o);a||(a=s.filter(n=>q(n.bitrate)&&q(o.bitrate)?o.bitrate/n.bitrate>i:!0),jo.set(o,a));let u=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Qo=o=>"quality"in o,$s=(o,e,t,i)=>{let r=q(i?.last?.bitrate)&&q(t?.bitrate)&&i.last.bitrate<t.bitrate?o.trackCooldownIncreaseQuality:o.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&qo()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let u=Qo(a)?"video":"audio",n=Qo(a)?a.quality:a.bitrate;return e({message:`
|
|
7
7
|
[last ${u} selected] ${n}
|
|
8
8
|
`}),a}return i?.recordSwitch(t),t},Kd=(o,e)=>Math.log(e)/Math.log(o),Ko=({tuning:o,container:e,limits:t,panelSize:i})=>{let r=o.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(o.usePixelRatio&&D.display.pixelRatio){let s=D.display.pixelRatio;if(o.pixelRatioMultiplier)r*=o.pixelRatioMultiplier*(s-1)+1;else{let a=o.pixelRatioLogBase,[u=0,n=0,l=0]=o.pixelRatioLogCoefficients,h=Kd(a,u*s+n)+l;Number.isFinite(h)&&(r*=h)}}return q(t?.min)&&Vt(t.min,o.highQualityLimit)&&(r*=2),{containerSizeLimit:o.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Wo=new WeakMap,Ye=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:n,history:l,visible:h,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{ws(o,As);let{containerSizeFactor:b,containerSizeLimit:g}=Ko({container:e,tuning:i,limits:r,panelSize:f}),y=i.considerPlaybackRate&&q(u)?u:1,T=Wo.get(o);T||(T=o.filter(v=>!xs(v.quality)).sort((v,I)=>Es(v.quality,I.quality)?-1:1),Wo.set(o,T));let S=T.at(-1)?.quality,x=T.at(0)?.quality,P=ti(r,x,S),A=y*ks(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},R=null;for(let v of T){let I=!0;if(g)if(v.size)I=v.size.width<=g.width&&v.size.height<=g.height;else{let N=g&&zo(g);I=N?ii(v.quality,N):!0}if(!I){w[v.quality]="FitsContainer";continue}let Q=p||t,L=q(Q)&&isFinite(Q)&&q(v.bitrate)?Q-s>=v.bitrate*A:!0,_=r?.min===v.quality;if(!L&&!_){w[v.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&n&&!xs(n.quality)&&(a??0)<i.minBufferToSwitchUp&&Es(v.quality,n.quality)){w[v.quality]="Buffer";continue}if(!!d&&Vt(v.quality,d)&&!_){w[v.quality]="DroppedFramesLimit";continue}if(!!c&&Vt(v.quality,c)&&!_){w[v.quality]="StallsLimit";continue}let ne=P||(Is(r?.max)||ii(v.quality,r.max))&&(Is(r?.min)||Vt(v.quality,r.min)),oe=q(h)&&!h?ii(v.quality,i.backgroundVideoQualityLimit):!0;if(!ne||!oe){w[v.quality]="FitsQualityLimits";continue}R||(R=v)}R&&R.bitrate&&Yo.next(R.bitrate);let E=R??T.at(-1)??o[0],O=l?.last,M=$s(i,m,E,l);return q(l)&&M.quality!==O?.quality&&m({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
@@ -174,6 +174,6 @@ void main(void) {
|
|
|
174
174
|
// sample using new coordinates
|
|
175
175
|
gl_FragColor = texture2D(u_texture, tc);
|
|
176
176
|
}
|
|
177
|
-
`;var gi=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 ea(this.params.fov,this.params.orientation),this.cameraRotationManager=new ta(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Ou,this.gl.VERTEX_SHADER),i=this.createShader(Fu,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,u=e+i,n=t-r,l=e+i,h=t+r,d=e-i,c=t+r;return[s,a,u,n,l,h,d,c]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as yh,now as wr,once as Th,Subscription as Ih,ValueSubject as pn,isNonNullable as Eh,safeStorage as mn,filterChanged as xh}from"@vkontakte/videoplayer-shared/evergreen";var ia="stalls_manager_metrics",fn="stalls_manager_abr_params",_u="stalls_manager_default_tuning_abr_params",bn=class{constructor(){this.isSeeked$=new pn(!1);this.isBuffering$=new pn(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ih;this.severeStallOccurred$=new pn(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(fn):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=wr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(wr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(_u)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(fn),this.setStoredData(_u,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(ia,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((u,n)=>u+n.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,u)=>a+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(ia,[]),this.setStoredData(fn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:u}=this.tuning,n=a*Math.min(t/u,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-n,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-n,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+n,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+n,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+n,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-n,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(mn.get(e)??t)}setStoredData(e,t){mn.set(e,JSON.stringify(t))}removeStoredData(e){mn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(ia,"[]"),r=t/e,s=i.length?at(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(ia,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(Th()).subscribe(t=>this.providerStartWatchingTimestamp=wr())),this.subscription.add(this.currentStallDuration$.pipe(xh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(yh(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),n=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),h=wr(),d=r&&this.currentStallsCount>=r,c=i&&h-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&h-l>=i+u&&t>=i;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,Eh(this.lastUniqueVideoTrackSelected.bitrate)&&n>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&wr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},ra=bn;import{combine as wh,map as kh,observeElementSize as Ah,Subscription as $h,ValueSubject as gn,noop as Ph}from"@vkontakte/videoplayer-shared/evergreen";var sa=class{constructor(){this.subscription=new $h;this.pipSize$=new gn(void 0);this.videoSize$=new gn(void 0);this.elementSize$=new gn(void 0);this.pictureInPictureWindowRemoveEventListener=Ph}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Ah(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(wh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(kh(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as Nu,map as Lh,once as Uu}from"@vkontakte/videoplayer-shared/evergreen";var Si=({subscription:o,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!D.browser.isSafari)return;let r=0,s=!1;o.add(e.volume.stateChangeStarted$.pipe(Lh(()=>{let a=e.volume.getTransition(),u=t.getValue();return!u||!a?!1:!a.to.muted&&u.muted}),Nu(a=>!!a),Uu()).subscribe(()=>{r=performance.now(),s=!0})),o.add(i.playbackRateState$.pipe(Nu(()=>s),Uu()).subscribe(()=>{let a=t.getValue(),u=e.playbackRate.getState();a&&u!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=u)}))};var Nt=class{constructor(e){this.subscription=new Fh;this.videoState=new C("stopped");this.observableVideo=null;this.droppedFramesManager=new ai;this.stallsManager=new ra;this.elementSizeManager=new sa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return Mh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new gi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Zs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;Oh(this.observableVideo)&&(this.observableVideo=xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Hu.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,u)=>this.subscription.add(a.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Sn(d=>!!d.length),Qu()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ar(d=>d.to.state!=="none"),kr());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Sn(ju),Qu()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ar(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(Dh(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of c.audio){f.push(tn(b));let g=[];for(let y of b.representations){let T=xu(y);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:y})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of c.video){m.push(rn(f));let b=[];for(let g of f.representations){let y=br({...g,streamId:f.id});y&&(b.push(y),this.videoTracksMap.set(y,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of c.text)for(let b of f.representations){let g=wu(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let u=$r(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ch(this.video,"progress")).pipe(Sn(()=>this.videoTracksMap.size>0)),{abrThrottle:n}=this.params.tuning.dash;n&&(u=u.pipe(_h(n))),this.subscription.add(u.subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(y=>this.videoTracksMap.get(y)?.representation.id===m.id);ju(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let y=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,y)}},r)),this.subscription.add(Bh({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:$r(aa([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Ar(d=>d.to)))}).pipe(Ar(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),kr()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(kr()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(rn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(kr()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(tn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Ar(({to:d})=>d==="ready"),kr());this.subscription.add($r(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,aa(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add($r(l,this.player.state$.stateChangeEnded$,aa(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=$r(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,aa(["init"])).pipe(Vh(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Oi:Ci,t=this.params.tuning.useNewAutoSelectVideoTrack?Rs:Ls,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:Ps,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:w})=>w===u),l=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:w})=>w===h.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let p=de(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(y){if(n&&!a){let w=e(n,c,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,c,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let S=n;(a||!S)&&(S=i(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=y&&t(S,c,this.audioStreamsMap.get(y)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(S)?.representation,A=x&&this.audioTracksMap.get(x)?.representation;if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var Pr=class extends Nt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as vn,merge as Wu,filter as qu,filterChanged as zu,isNullable as yn,map as Gu,ValueSubject as Tn,isNonNullable as Nh}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class extends Nt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let u=new Tn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zu()).subscribe(n=>{let l=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!n&&!l&&d?e=!0:n&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Gu(n=>n.to)).subscribe(this.player.isLowLatency$)).add(vn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Gu(({liveBufferTime:n,liveAvailabilityStartTime:l})=>n&&l?n+l:void 0)).subscribe(i.liveTime$)).add(vn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Wu(r.playbackRateState$,new Tn(1))}).pipe(qu(({liveStreamStatus:n,liveDuration:l})=>n==="active"&&!!l)).subscribe(({liveDuration:n,playbackRate:l})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||yn(h)||(t=n-h)})).add(vn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Wu(r.playbackRateState$,new Tn(1))}).pipe(zu((n,l)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===l.liveDuration:n.time===l.time)).subscribe(({time:n,liveDuration:l,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-c||yn(n)||yn(l))return;let p=-1*(l-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let l=ku(n);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(qu(n=>Nh(n))).subscribe(n=>i.isLiveEnded$.next(n==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as mp,assertNonNullable as fp,combine as bp,debounce as gp,ErrorCategory as ll,filter as Vn,filterChanged as Nr,fromEvent as Sp,isNonNullable as dl,isNullable as vp,map as Ur,merge as Hr,observableFrom as ma,once as cl,Subscription as yp}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as Ln,assertNonNullable as Ti,combine as Ii,ErrorCategory as Ue,filter as ca,filterChanged as Or,flattenObject as Fr,fromEvent as Je,getTraceSubscriptionMethod as rp,interval as Rn,isNonNullable as _r,isNullable as ol,map as Ei,merge as Qt,now as Mn,Subject as wt,Subscription as Dn,SubscriptionRemovable as sp,tap as ap,throttle as ul,ValueSubject as K}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Uh,ErrorCategory as Yu,Subject as Ku}from"@vkontakte/videoplayer-shared/evergreen";var Hh=18,Xu=!1;try{Xu=D.browser.isSafari&&!!D.browser.safariVersion&&D.browser.safariVersion<=Hh}catch(o){console.error(o)}var In=class{constructor(e){this.bufferFull$=new Ku;this.error$=new Ku;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Yu.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Xu&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Yu.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Uh(t)}}},Ju=In;import{abortable as Et,assertNonNullable as ve,ErrorCategory as Ht,fromEvent as kn,getExponentialDelay as An,isHigher as zh,isNonNullable as xt,isNullable as ie,now as ua,once as Gh,Subject as Yh,Subscription as Kh,ValueSubject as jt}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as jh,throttleFn as Qh}from"@vkontakte/videoplayer-shared/evergreen";var Rr=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??jh({width:e,height:t});return u&&{id:o,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Zu=({id:o,bitrate:e})=>({id:o,bitrate:e}),el=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),tl=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),En=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),xn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),wn=o=>"url"in o,Pe=o=>o.type==="template";var il=o=>{o.sort((t,i)=>t.from-i.from);let e=[o[0]];for(let t=1;t<o.length;t++){let{from:i,to:r}=o[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(o[t])}return e},Ut=(o,e)=>{for(let t of o)if(e(t))return t;return null},rl=o=>{let e=!1,t=Qh(()=>{e=!0},o);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Wh,Subscription as qh}from"@vkontakte/videoplayer-shared/evergreen";var na=o=>{let e=[];for(let t=0;t<o.length;t++){let i=Math.floor(o.start(t)*1e3),r=Math.ceil(o.end(t)*1e3);e.push(i,r)}return e};var oa=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new qh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Wh(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!B(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=na(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],u=t[i+1];if(a>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Mr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:n=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new jt(0);this.currentLowLatencySegmentLength$=new jt(0);this.currentSegmentLength$=new jt(0);this.onLastSegment$=new jt(!1);this.fullyBuffered$=new jt(!1);this.playingRepresentation$=new jt(void 0);this.playingRepresentationInit$=new jt(void 0);this.error$=new Yh;this.gaps=[];this.subscription=new Kh;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Et(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ju(this.sourceBuffer),this.sourceBufferBufferedDiff=new oa(this.mediaSource,this.sourceBuffer),this.subscription.add(kn(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(kn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ht.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!B(this.mediaSource,this.sourceBuffer))return;let n=Math.min(this.bufferLimit,ni(this.sourceBuffer.buffered)*.8);this.bufferLimit=n;let l=de(this.sourceBuffer.buffered,u),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,l<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ve(i,"No init buffer for starting representation"),ve(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Et(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();xt(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Et(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();xt(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Et(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(n=>n.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let n of this.representations.keys()){let l=t.find(c=>c.id===n);l&&this.representations.set(n,l);let h=this.representations.get(n);if(!h||!Pe(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ve(r,`Representation not found by id ${i}`);let s=this.segments.get(i);ve(s,"No segments for starting representation");let a=this.initData.get(i);if(ve(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Et(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ve(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(ie(u)||ie(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),ve(a,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let n=this.getCurrentPosition();xt(n)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(n,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ie(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ie(e)||ie(this.downloadingRepresentationId)||ie(this.playingRepresentationId)||ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||xt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(ve(t,`No such representation ${this.downloadingRepresentationId}`),ve(i,`No such representation ${this.playingRepresentationId}`),ie(r)||ie(s))return;let a=r.find(c=>e>=c.time.from&&e<c.time.to);xt(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let u=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=Rr(i),m=Rr(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&xt(p)&&xt(m)&&zh(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+n&&(u=a?a.time.to+n:-1/0),this.tuning.dash.useNewRepresentationSwitch){let y=[...this.segments.entries()].map(([T,S])=>{let x=S.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;y&&(this.playingRepresentationId=y,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ni(this.sourceBuffer.buffered)>=this.bufferLimit){let c=de(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=null;if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,u),h?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))c="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(h,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h?.length&&de(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-de(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;xt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Pe(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,n=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(n===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(n+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ve(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Pe(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(n=>Math.floor(n.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(n=>Math.floor(n.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let n=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Ne(r.segmentTemplateUrl,{segmentTime:n});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:c,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+y||r<y&&m-p>=y||m<=i+y;return(c==="none"||c==="partially_ejected"&&g&&T&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(ce(this.sourceBuffer.buffered,p)&&ce(this.sourceBuffer.buffered,m)))&&g&&T});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,n=0,l=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<a.length&&(u<=h||n<=d);c++){let p=a[c];if(u+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Pe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:u,onProgress:n,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Et(u,async function*(){let h=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:n,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=ua(),!h)return;let d=new DataView(h),c=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(d,f)}n&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Xe(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Pe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let n of e)n.status="downloading",this.activeSegments.add({segment:n,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Et(a,async function*(){let n=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,n),kn(window,"online").pipe(Gh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=ua(),this.failedDownloads=0}catch(n){this.abortActiveSegments(e),Xe(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Pe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,n)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ua(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:n,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Pe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],n=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ua();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:n,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let u of this.activeSegments){let{segment:n}=u;if(u.representationId===t){if(s.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),h=Ke(a.mime).parseFeedableSegmentChunk(l,this.isLive);h?.byteLength&&(n.status="partially_fed",u.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),u.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let n of this.activeSegments){if(n.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=n,h=l.byte.from-i,d=l.byte.to-i,c=d-h+1,p=h<r,m=d<=r;if(p){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+h,c);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(n,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(n.loadedBytes=Math.min(c,r-h),n.loadedBytes>n.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+h+n.feedingBytes,n.loadedBytes-n.feedingBytes),b=n.loadedBytes===c?f:Ke(u.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(l.status="partially_fed",n.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(n.fedBytes+=b.byteLength,n.fedBytes===c&&this.onSegmentFullyAppended(n,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&D.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ce(this.sourceBuffer.buffered,e.segment.time.from,100)&&ce(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ht.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",wn(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?Et(this.destroyAbortController.signal,async function*(){let u=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(n=>setTimeout(n,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(u=>{if(!u)return;let{init:n,dataView:l,segments:h}=u,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let c=h;this.isLive&&Pe(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),n&&this.parsedInitData.set(e.id,n)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ht.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ie(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=u=>{if(s>=t)return;r.push({...u.time});let n=wn(u)?u.size??0:u.byte.to-u.byte.from;s+=n};for(let u of this.segments.values())for(let n of u){let l=n.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=n.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||h)&&n.status==="fed"&&a(n)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let n=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,h=0;for(let d of this.segments.values())for(let c of d)["none","partially_ejected"].includes(c.status)&&Math.round(c.time.from)<=Math.round(n)&&Math.round(c.time.to)>=Math.round(l)&&h++;if(h===this.segments.size){let d={time:{from:n,to:l},url:"",status:"none"};a(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let n of this.segments.values())for(let l of n)l.time.from>=e+u&&l.status==="fed"&&a(l)}return r.length?(r=il(r),(await Promise.all(r.map(n=>this.sourceBufferTaskQueue.remove(n.from,n.to)))).reduce((n,l)=>n||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ie(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),a=Math.round(r.to);for(let u=0;u<i.length;u++)if(s>=Math.round(i.start(u)*1e3)&&a<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ht.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ie(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=na(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),n=!1,l=0;for(let h=0;h<e.length;h+=2){let d=e[h],c=e[h+1];n||(n=d-t<=a&&c+t>=u),(a>=d&&a<c-t||u>d+t&&u<=c)&&(l+=1)}n||(l===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Ht.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}};import{abortable as Dr,assertNever as sl,fromEvent as al,merge as Xh,now as Br,Subject as vi,ValueSubject as $n,flattenObject as yi,ErrorCategory as Vr,SubscriptionRemovable as Jh}from"@vkontakte/videoplayer-shared/evergreen";var da=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new vi;this.manifestReceived=new vi;this.firstBytesRequested=new vi;this.firstBytesReceived=new vi;this.lastConnectionType$=new $n(void 0);this.lastConnectionReused$=new $n(void 0);this.lastRequestFirstBytes$=new $n(void 0);this.recoverableError$=new vi;this.error$=new vi;this.abortAllController=new AbortController;this.subscription=new Jh;this.fetchManifest=Dr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=yt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Us(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(la);return r?(t.log("success",yi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",yi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Dr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:u=!0,isLowLatency:n=!1,bufferOptimisation:l=!1}={}){let h=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(h,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),h=v.toString();break}default:sl(t)}this.requestQuic&&(h=yt(h));let p=this.abortAllController.signal,m;if(a){let v=new AbortController;if(m=Xh(al(this.abortAllController.signal,"abort"),al(a,"abort")).subscribe(()=>{try{v.abort()}catch(I){la(I)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{v.abort()}catch(I){la(I)}p=v.signal}let f=0,b=Br();c.log("startRequest",yi({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:n,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),y=Br();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(y-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let v=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let v=Br(),I={requestStartedAt:b,requestEndedAt:v,duration:v-b};return c.log("endRequest",yi(I)),c.end(),g.arrayBuffer()}let T=g.body;if(u){let v;[T,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,n)}let S=T.getReader(),x,P=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(P)&&(x=P),!x&&i&&(x=i.to-i.from+1);let A=x?new Uint8Array(x):new Uint8Array(0),w=!1,R=v=>{this.unsubscribeAbortSubscription(m),w=!0,la(v)},E=Dr(p,async function*({done:v,value:I}){if(f===0&&(this.lastRequestFirstBytes$.next(Br()-b),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!v&&I){if(l&&x)A.set(I,f),f+=I.byteLength;else{let Q=new Uint8Array(A.length+I.length);Q.set(A),Q.set(I,A.length),A=Q,f+=I.byteLength}r?.(new DataView(A.buffer),f),yield S?.read().then(E,R)}}.bind(this));yield S?.read().then(E,R),this.unsubscribeAbortSubscription(m);let O=Br(),M={failed:w,requestStartedAt:b,requestEndedAt:O,duration:O-b};return w?(c.error("endRequest",yi(M)),c.end(),null):(c.log("endRequest",yi(M)),c.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=Dr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,u=s,n=!1,l,h;e.indexRange&&(l=e.indexRange.from,h=e.indexRange.to,n=s+1===l,n&&(a=Math.min(l,r),u=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!d)return null;let c=new DataView(d,r-a,s-a+1);if(!t.validateData(c))throw new Error("Invalid media file");let p=t.parseInit(c),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(n)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=Dr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ns(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:sl(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Vr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Vr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Vr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Vr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Vr.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},la=o=>{if(!Xe(o))throw o};import{isNullable as Zh,ValueSubject as ep}from"@vkontakte/videoplayer-shared/evergreen";var Cr=class o{constructor(e,t){this.currentRepresentation$=new ep(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Zh(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<a||e>u)continue;let n=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!n||this.currentSegment?.time.from===n.time.from&&this.currentSegment.time.to===n.time.to||(this.currentSegment=n,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(n.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=o.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Pe(t.segmentReference))}};var np=["progress","play","seeked","stalled","waiting"],op=["timeupdate","progress","loadeddata","playing","seeked"];var ha=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Dn;this.subscriptionRemovable=new sp;this.representationSubscription=new Dn;this.state$=new C("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new wt;this.manifestRequested=new wt;this.manifestReceived=new wt;this.firstBytesRequested=new wt;this.firstBytesReceived=new wt;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new wt;this.fetcherError$=new wt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new wt;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Ln(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=J(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ue.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ln(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ue.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Fs(e??"",this.manifestUrlString)}catch(n){let l=Cs(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(l)}if(!t)return null;let i=(n,l,h)=>!!(this.element?.canPlayType?.(l)&&Ae()?.isTypeSupported?.(`${l}; codecs="${h}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:l,streamIsUnpublished:h,streamIsAlive:d}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let n of["video","audio"]){let h=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p));r[n]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=h.map(({codecs:p})=>p);n==="audio"&&(a=Xs(c),d=a[0]),n==="video"&&(s=Ks(c),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[n]=h.filter(({codecs:p})=>pi(p)===d))}else{let c=new Set(h.map(({codecs:p})=>p));d=Ys(c),d&&(r[n]=h.filter(({codecs:p})=>p.startsWith(d)))}if(n==="video"){let c=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);D.display.isHDR&&c&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Fr(u)),u}.bind(this));this.initRepresentations=Ln(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Fr({initialVideo:e,initialAudio:t,sourceHls:i})),Ti(this.manifest),Ti(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Dn,this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Je(c,"error").pipe(ca(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ue.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=ms();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Jt())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new Mr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],_r(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new Mr("audio",this.source,c,a),this.bufferManagers.push(this.audioBufferManager)}Cr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Cr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let n=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Qt(...op.map(c=>Je(this.element,c))).pipe(Ei(c=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),Or(),ap(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&n()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Qt(Je(this.element,"ended"),this.forceEnded$).subscribe(()=>{n()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Or()).subscribe(p=>this.liveStreamEndTimestamp=Mn())),this.subscription.add(Je(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Rn(1e3).subscribe(p=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Je(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ii({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ei(({isActiveLive:p,isLowLatency:m})=>p&&m),Or()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||hi(this.element,1)})),this.representationSubscription.add(Ii({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ca(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(Ii({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ca(({isLive:p})=>p),Or((p,m)=>m.bufferLength<p.bufferLength),Ei(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=pt(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ii({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=p-b;if(this.isManualDecreasePlaybackInLive())return;let S=1;Math.abs(T)>g&&(S=1+Math.sign(T)*y),hi(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(Ii({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ul(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=pt(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,x=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let w="none";if(P?w="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),w="active_low_latency"):b!==0&&x<y?w="live_forward_buffering":x<y+S&&(w="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),w==="live_forward_buffering"||w==="live_with_target_offset"){let R=c-(y+T),E=this.normolizeLiveOffset(Math.trunc(b+R/f)),O=Math.abs(E-b),M=0;!p||O<=this.tuning.dashCmafLive.offsetCalculationError?M=b:E>0&&O>this.tuning.dashCmafLive.offsetCalculationError&&(M=E),this.manifestUrlString=J(this.manifestUrlString,M,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(c=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ue.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Qt(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Ei(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),h=Qt(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Ei(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),d=Ii({allBuffersFull:l,someBufferEnded:h}).pipe(Or(),Ei(({allBuffersFull:c,someBufferEnded:p})=>c&&p),ca(c=>c));if(this.representationSubscription.add(Qt(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Qt(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Pe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&_r(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Rn(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ue.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new da({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=nt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Ti(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Mn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=J(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Ti(this.element),this.state$.setState("running");let e=Je(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(ul(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Qt(...np.map(t=>Je(this.element,t)),Je(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ue.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Je(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Je(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&ce(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=Mn(),a=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,h=this.audioBufferManager?.getForwardBufferDuration()??0,d=l<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&h<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:Ue.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Fr(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Rn(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Ti(this.element),Ti(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),ce(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ol(this.element)||ol(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Fr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){_r(this.element)&&_r(this.source)&&_r(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=rp(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let l of n.gaps)(l.persistent||n.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?a=1/0:(a===null||l.to>a)&&(a=l.to));if(a!==null){let n=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,this.tracer.log("jumpGap",Fr({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:n,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as up,map as lp,observeElementSize as dp,Subscription as cp,ValueSubject as Bn,noop as hp}from"@vkontakte/videoplayer-shared/evergreen";var pa=class{constructor(){this.subscription=new cp;this.pipSize$=new Bn(void 0);this.videoSize$=new Bn(void 0);this.elementSize$=new Bn(void 0);this.pictureInPictureWindowRemoveEventListener=hp}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(dp(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(up({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(lp(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Wt=class{constructor(e){this.subscription=new yp;this.videoState=new C("stopped");this.observableVideo=null;this.droppedFramesManager=new ai;this.stallsManager=new ra;this.elementSizeManager=new pa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return mp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new gi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ha({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;vp(this.observableVideo)&&(this.observableVideo=xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:ll.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,u)=>this.subscription.add(a.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Vn(d=>!!d.length),cl()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ur(d=>d.to.state!=="none"),Nr());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Vn(dl),cl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ur(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(fp(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of c.audio){f.push(En(b));let g=[];for(let y of b.representations){let T=Zu(y);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:y})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of c.video){m.push(xn(f));let b=[];for(let g of f.representations){let y=Rr({...g,streamId:f.id});y&&(b.push(y),this.videoTracksMap.set(y,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of c.text)for(let b of f.representations){let g=el(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,n=u&&rl(u)||null;this.subscription.add(Hr(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Sp(this.video,"progress")).pipe(Vn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c||d==="running"&&n&&!n())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=Ut(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);dl(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(bp({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Hr(ma([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Ur(d=>d.to)))}).pipe(Ur(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),Nr()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Nr()).subscribe(d=>{let c=Ut(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(xn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Nr()).subscribe(d=>{let c=Ut(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(En(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Ur(({to:d})=>d==="ready"),Nr());this.subscription.add(Hr(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ma(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Hr(l,this.player.state$.stateChangeEnded$,ma(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Hr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ma(["init"])).pipe(gp(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Oi:Ci,t=this.params.tuning.useNewAutoSelectVideoTrack?Rs:Ls,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:Ps,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,n=Ut(this.videoTracksMap.keys(),w=>w.id===u),l=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=Ut(this.videoStreamsMap.keys(),w=>w.id===h.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let p=de(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=g?.id&&Ut(this.audioStreamsMap.keys(),w=>w.id===g.id)||this.audioStreamsMap.keys().next().value,T=0;if(y){if(n&&!a){let w=e(n,c,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,c,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let S=n;(a||!S)&&(S=i(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=y&&t(S,c,this.audioStreamsMap.get(y)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(S)?.representation,A=x&&this.audioTracksMap.get(x)?.representation;P&&A?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=A):P&&!A&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ll.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var jr=class extends Wt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Cn,merge as hl,filter as pl,filterChanged as ml,isNullable as On,map as fl,ValueSubject as Fn,isNonNullable as Tp}from"@vkontakte/videoplayer-shared/evergreen";var Qr=class extends Wt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let u=new Fn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(ml()).subscribe(n=>{let l=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!n&&!l&&d?e=!0:n&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(fl(n=>n.to)).subscribe(this.player.isLowLatency$)).add(Cn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fl(({liveBufferTime:n,liveAvailabilityStartTime:l})=>n&&l?n+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(pl(n=>Tp(n))).subscribe(n=>i.isLiveEnded$.next(n!=="active"&&i.position$.getValue()===0))).add(Cn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:hl(r.playbackRateState$,new Fn(1))}).pipe(pl(({liveStreamStatus:n,liveDuration:l})=>n==="active"&&!!l)).subscribe(({liveDuration:n,playbackRate:l})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||On(h)||(t=n-h)})).add(Cn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:hl(r.playbackRateState$,new Fn(1))}).pipe(ml((n,l)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===l.liveDuration:n.time===l.time)).subscribe(({time:n,liveDuration:l,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-c||On(n)||On(l))return;let p=-1*(l-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let l=tl(n);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var bl="X-Playback-Duration",_n=async o=>{let e=await fetch(o),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(bl)?parseInt(e.headers.get(bl),10):void 0};import{assertNever as Mp,combine as Dp,debounce as Bp,ErrorCategory as ga,filter as Vp,filterChanged as Cp,isNonNullable as vl,isNullable as Sa,map as yl,merge as Op,observableFrom as Fp,Subscription as _p,ValueSubject as Un,VideoQuality as Np}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Ip,getExponentialDelay as Ep}from"@vkontakte/videoplayer-shared/evergreen";var xp=o=>{let e=null;if(o.QUALITY&&(e=ft(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Ip({width:t,height:i})}return e??null},wp=(o,e)=>{let t=o.split(`
|
|
177
|
+
`;var gi=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 ea(this.params.fov,this.params.orientation),this.cameraRotationManager=new ta(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Ou,this.gl.VERTEX_SHADER),i=this.createShader(Fu,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,u=e+i,n=t-r,l=e+i,h=t+r,d=e-i,c=t+r;return[s,a,u,n,l,h,d,c]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as yh,now as wr,once as Th,Subscription as Ih,ValueSubject as pn,isNonNullable as Eh,safeStorage as mn,filterChanged as xh}from"@vkontakte/videoplayer-shared/evergreen";var ia="stalls_manager_metrics",fn="stalls_manager_abr_params",_u="stalls_manager_default_tuning_abr_params",bn=class{constructor(){this.isSeeked$=new pn(!1);this.isBuffering$=new pn(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ih;this.severeStallOccurred$=new pn(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(fn):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=wr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(wr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(_u)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(fn),this.setStoredData(_u,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(ia,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((u,n)=>u+n.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,u)=>a+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(ia,[]),this.setStoredData(fn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:u,stallsMetricsHistoryLength:n}=this.tuning,l=a*Math.min(t/(u*n),1),h=this.abrTuningParams;return e<i-r?h={bitrateFactorAtEmptyBuffer:Math.max(h.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(h.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(h.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(h={bitrateFactorAtEmptyBuffer:Math.min(h.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(h.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(h.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(h={bitrateFactorAtEmptyBuffer:Math.max(h.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(h.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(h.containerSizeFactor,this.abrParams.containerSizeFactor)}),h}getStoredData(e,t="{}"){return JSON.parse(mn.get(e)??t)}setStoredData(e,t){mn.set(e,JSON.stringify(t))}removeStoredData(e){mn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(ia,"[]"),r=t/e,s=i.length?at(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(ia,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(Th()).subscribe(t=>this.providerStartWatchingTimestamp=wr())),this.subscription.add(this.currentStallDuration$.pipe(xh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(yh(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),n=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),h=wr(),d=r&&this.currentStallsCount>=r,c=i&&h-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&h-l>=i+u&&t>=i;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,Eh(this.lastUniqueVideoTrackSelected.bitrate)&&n>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&wr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},ra=bn;import{combine as wh,map as kh,observeElementSize as Ah,Subscription as $h,ValueSubject as gn,noop as Ph}from"@vkontakte/videoplayer-shared/evergreen";var sa=class{constructor(){this.subscription=new $h;this.pipSize$=new gn(void 0);this.videoSize$=new gn(void 0);this.elementSize$=new gn(void 0);this.pictureInPictureWindowRemoveEventListener=Ph}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Ah(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(wh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(kh(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as Nu,map as Lh,once as Uu}from"@vkontakte/videoplayer-shared/evergreen";var Si=({subscription:o,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!D.browser.isSafari)return;let r=0,s=!1;o.add(e.volume.stateChangeStarted$.pipe(Lh(()=>{let a=e.volume.getTransition(),u=t.getValue();return!u||!a?!1:!a.to.muted&&u.muted}),Nu(a=>!!a),Uu()).subscribe(()=>{r=performance.now(),s=!0})),o.add(i.playbackRateState$.pipe(Nu(()=>s),Uu()).subscribe(()=>{let a=t.getValue(),u=e.playbackRate.getState();a&&u!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=u)}))};var Nt=class{constructor(e){this.subscription=new Fh;this.videoState=new C("stopped");this.observableVideo=null;this.droppedFramesManager=new ai;this.stallsManager=new ra;this.elementSizeManager=new sa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return Mh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new gi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Zs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;Oh(this.observableVideo)&&(this.observableVideo=xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Hu.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,u)=>this.subscription.add(a.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Sn(d=>!!d.length),Qu()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ar(d=>d.to.state!=="none"),kr());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Sn(ju),Qu()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ar(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(Dh(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of c.audio){f.push(tn(b));let g=[];for(let y of b.representations){let T=xu(y);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:y})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of c.video){m.push(rn(f));let b=[];for(let g of f.representations){let y=br({...g,streamId:f.id});y&&(b.push(y),this.videoTracksMap.set(y,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of c.text)for(let b of f.representations){let g=wu(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let u=$r(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ch(this.video,"progress")).pipe(Sn(()=>this.videoTracksMap.size>0)),{abrThrottle:n}=this.params.tuning.dash;n&&(u=u.pipe(_h(n))),this.subscription.add(u.subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(y=>this.videoTracksMap.get(y)?.representation.id===m.id);ju(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let y=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,y)}},r)),this.subscription.add(Bh({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:$r(aa([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Ar(d=>d.to)))}).pipe(Ar(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),kr()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(kr()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(rn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(kr()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(tn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Ar(({to:d})=>d==="ready"),kr());this.subscription.add($r(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,aa(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add($r(l,this.player.state$.stateChangeEnded$,aa(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=$r(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,aa(["init"])).pipe(Vh(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Oi:Ci,t=this.params.tuning.useNewAutoSelectVideoTrack?Rs:Ls,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:Ps,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:w})=>w===u),l=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:w})=>w===h.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let p=de(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(y){if(n&&!a){let w=e(n,c,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,c,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let S=n;(a||!S)&&(S=i(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=y&&t(S,c,this.audioStreamsMap.get(y)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(S)?.representation,A=x&&this.audioTracksMap.get(x)?.representation;if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var Pr=class extends Nt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as vn,merge as Wu,filter as qu,filterChanged as zu,isNullable as yn,map as Gu,ValueSubject as Tn,isNonNullable as Nh}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class extends Nt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let u=new Tn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zu()).subscribe(n=>{let l=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!n&&!l&&d?e=!0:n&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Gu(n=>n.to)).subscribe(this.player.isLowLatency$)).add(vn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Gu(({liveBufferTime:n,liveAvailabilityStartTime:l})=>n&&l?n+l:void 0)).subscribe(i.liveTime$)).add(vn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Wu(r.playbackRateState$,new Tn(1))}).pipe(qu(({liveStreamStatus:n,liveDuration:l})=>n==="active"&&!!l)).subscribe(({liveDuration:n,playbackRate:l})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||yn(h)||(t=n-h)})).add(vn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Wu(r.playbackRateState$,new Tn(1))}).pipe(zu((n,l)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===l.liveDuration:n.time===l.time)).subscribe(({time:n,liveDuration:l,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-c||yn(n)||yn(l))return;let p=-1*(l-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let l=ku(n);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(qu(n=>Nh(n))).subscribe(n=>i.isLiveEnded$.next(n==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as mp,assertNonNullable as fp,combine as bp,debounce as gp,ErrorCategory as ll,filter as Vn,filterChanged as Nr,fromEvent as Sp,isNonNullable as dl,isNullable as vp,map as Ur,merge as Hr,observableFrom as ma,once as cl,Subscription as yp}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as Ln,assertNonNullable as Ti,combine as Ii,ErrorCategory as Ue,filter as ca,filterChanged as Or,flattenObject as Fr,fromEvent as Je,getTraceSubscriptionMethod as rp,interval as Rn,isNonNullable as _r,isNullable as ol,map as Ei,merge as Qt,now as Mn,Subject as wt,Subscription as Dn,SubscriptionRemovable as sp,tap as ap,throttle as ul,ValueSubject as K}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Uh,ErrorCategory as Yu,Subject as Ku}from"@vkontakte/videoplayer-shared/evergreen";var Hh=18,Xu=!1;try{Xu=D.browser.isSafari&&!!D.browser.safariVersion&&D.browser.safariVersion<=Hh}catch(o){console.error(o)}var In=class{constructor(e){this.bufferFull$=new Ku;this.error$=new Ku;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Yu.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Xu&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Yu.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Uh(t)}}},Ju=In;import{abortable as Et,assertNonNullable as ve,ErrorCategory as Ht,fromEvent as kn,getExponentialDelay as An,isHigher as zh,isNonNullable as xt,isNullable as ie,now as ua,once as Gh,Subject as Yh,Subscription as Kh,ValueSubject as jt}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as jh,throttleFn as Qh}from"@vkontakte/videoplayer-shared/evergreen";var Rr=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??jh({width:e,height:t});return u&&{id:o,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Zu=({id:o,bitrate:e})=>({id:o,bitrate:e}),el=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),tl=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),En=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),xn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),wn=o=>"url"in o,Pe=o=>o.type==="template";var il=o=>{o.sort((t,i)=>t.from-i.from);let e=[o[0]];for(let t=1;t<o.length;t++){let{from:i,to:r}=o[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(o[t])}return e},Ut=(o,e)=>{for(let t of o)if(e(t))return t;return null},rl=o=>{let e=!1,t=Qh(()=>{e=!0},o);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Wh,Subscription as qh}from"@vkontakte/videoplayer-shared/evergreen";var na=o=>{let e=[];for(let t=0;t<o.length;t++){let i=Math.floor(o.start(t)*1e3),r=Math.ceil(o.end(t)*1e3);e.push(i,r)}return e};var oa=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new qh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Wh(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!B(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=na(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],u=t[i+1];if(a>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Mr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:n=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new jt(0);this.currentLowLatencySegmentLength$=new jt(0);this.currentSegmentLength$=new jt(0);this.onLastSegment$=new jt(!1);this.fullyBuffered$=new jt(!1);this.playingRepresentation$=new jt(void 0);this.playingRepresentationInit$=new jt(void 0);this.error$=new Yh;this.gaps=[];this.subscription=new Kh;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Et(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ju(this.sourceBuffer),this.sourceBufferBufferedDiff=new oa(this.mediaSource,this.sourceBuffer),this.subscription.add(kn(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(kn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ht.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!B(this.mediaSource,this.sourceBuffer))return;let n=Math.min(this.bufferLimit,ni(this.sourceBuffer.buffered)*.8);this.bufferLimit=n;let l=de(this.sourceBuffer.buffered,u),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,l<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ve(i,"No init buffer for starting representation"),ve(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Et(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();xt(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Et(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();xt(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Et(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(n=>n.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let n of this.representations.keys()){let l=t.find(c=>c.id===n);l&&this.representations.set(n,l);let h=this.representations.get(n);if(!h||!Pe(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ve(r,`Representation not found by id ${i}`);let s=this.segments.get(i);ve(s,"No segments for starting representation");let a=this.initData.get(i);if(ve(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,Et(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ve(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(ie(u)||ie(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),ve(a,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let n=this.getCurrentPosition();xt(n)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(n,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ie(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ie(e)||ie(this.downloadingRepresentationId)||ie(this.playingRepresentationId)||ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||xt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(ve(t,`No such representation ${this.downloadingRepresentationId}`),ve(i,`No such representation ${this.playingRepresentationId}`),ie(r)||ie(s))return;let a=r.find(c=>e>=c.time.from&&e<c.time.to);xt(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let u=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=Rr(i),m=Rr(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&xt(p)&&xt(m)&&zh(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+n&&(u=a?a.time.to+n:-1/0),this.tuning.dash.useNewRepresentationSwitch){let y=[...this.segments.entries()].map(([T,S])=>{let x=S.find(P=>e>=P.time.from&&e<P.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;y&&(this.playingRepresentationId=y,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ni(this.sourceBuffer.buffered)>=this.bufferLimit){let c=de(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=null;if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,u),h?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))c="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(h,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h?.length&&de(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-de(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;xt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Pe(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,n=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(n===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(n+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ve(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Pe(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(n=>Math.floor(n.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(n=>Math.floor(n.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let n=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Ne(r.segmentTemplateUrl,{segmentTime:n});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:c,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+y||r<y&&m-p>=y||m<=i+y;return(c==="none"||c==="partially_ejected"&&g&&T&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(ce(this.sourceBuffer.buffered,p)&&ce(this.sourceBuffer.buffered,m)))&&g&&T});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,n=0,l=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<a.length&&(u<=h||n<=d);c++){let p=a[c];if(u+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Pe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:u,onProgress:n,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Et(u,async function*(){let h=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:n,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=ua(),!h)return;let d=new DataView(h),c=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(d,f)}n&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Xe(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Pe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let n of e)n.status="downloading",this.activeSegments.add({segment:n,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await Et(a,async function*(){let n=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,n),kn(window,"online").pipe(Gh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=ua(),this.failedDownloads=0}catch(n){this.abortActiveSegments(e),Xe(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Pe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,n)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ua(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:n,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Pe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],n=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ua();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:n,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let u of this.activeSegments){let{segment:n}=u;if(u.representationId===t){if(s.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),h=Ke(a.mime).parseFeedableSegmentChunk(l,this.isLive);h?.byteLength&&(n.status="partially_fed",u.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),u.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let n of this.activeSegments){if(n.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=n,h=l.byte.from-i,d=l.byte.to-i,c=d-h+1,p=h<r,m=d<=r;if(p){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+h,c);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(n,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(n.loadedBytes=Math.min(c,r-h),n.loadedBytes>n.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+h+n.feedingBytes,n.loadedBytes-n.feedingBytes),b=n.loadedBytes===c?f:Ke(u.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(l.status="partially_fed",n.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(n.fedBytes+=b.byteLength,n.fedBytes===c&&this.onSegmentFullyAppended(n,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&D.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ce(this.sourceBuffer.buffered,e.segment.time.from,100)&&ce(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ht.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",wn(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?Et(this.destroyAbortController.signal,async function*(){let u=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(n=>setTimeout(n,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(u=>{if(!u)return;let{init:n,dataView:l,segments:h}=u,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let c=h;this.isLive&&Pe(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),n&&this.parsedInitData.set(e.id,n)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ht.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ie(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=u=>{if(s>=t)return;r.push({...u.time});let n=wn(u)?u.size??0:u.byte.to-u.byte.from;s+=n};for(let u of this.segments.values())for(let n of u){let l=n.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=n.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||h)&&n.status==="fed"&&a(n)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let n=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,h=0;for(let d of this.segments.values())for(let c of d)["none","partially_ejected"].includes(c.status)&&Math.round(c.time.from)<=Math.round(n)&&Math.round(c.time.to)>=Math.round(l)&&h++;if(h===this.segments.size){let d={time:{from:n,to:l},url:"",status:"none"};a(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let n of this.segments.values())for(let l of n)l.time.from>=e+u&&l.status==="fed"&&a(l)}return r.length?(r=il(r),(await Promise.all(r.map(n=>this.sourceBufferTaskQueue.remove(n.from,n.to)))).reduce((n,l)=>n||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ie(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),a<t.time.to&&a>t.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),a=Math.round(r.to);for(let u=0;u<i.length;u++)if(s>=Math.round(i.start(u)*1e3)&&a<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ht.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ie(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=na(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),n=!1,l=0;for(let h=0;h<e.length;h+=2){let d=e[h],c=e[h+1];n||(n=d-t<=a&&c+t>=u),(a>=d&&a<c-t||u>d+t&&u<=c)&&(l+=1)}n||(l===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Ht.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}};import{abortable as Dr,assertNever as sl,fromEvent as al,merge as Xh,now as Br,Subject as vi,ValueSubject as $n,flattenObject as yi,ErrorCategory as Vr,SubscriptionRemovable as Jh}from"@vkontakte/videoplayer-shared/evergreen";var da=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new vi;this.manifestReceived=new vi;this.firstBytesRequested=new vi;this.firstBytesReceived=new vi;this.lastConnectionType$=new $n(void 0);this.lastConnectionReused$=new $n(void 0);this.lastRequestFirstBytes$=new $n(void 0);this.recoverableError$=new vi;this.error$=new vi;this.abortAllController=new AbortController;this.subscription=new Jh;this.fetchManifest=Dr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=yt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Us(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(la);return r?(t.log("success",yi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",yi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Dr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:u=!0,isLowLatency:n=!1,bufferOptimisation:l=!1}={}){let h=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(h,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),h=v.toString();break}default:sl(t)}this.requestQuic&&(h=yt(h));let p=this.abortAllController.signal,m;if(a){let v=new AbortController;if(m=Xh(al(this.abortAllController.signal,"abort"),al(a,"abort")).subscribe(()=>{try{v.abort()}catch(I){la(I)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{v.abort()}catch(I){la(I)}p=v.signal}let f=0,b=Br();c.log("startRequest",yi({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:n,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),y=Br();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(y-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let v=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let v=Br(),I={requestStartedAt:b,requestEndedAt:v,duration:v-b};return c.log("endRequest",yi(I)),c.end(),g.arrayBuffer()}let T=g.body;if(u){let v;[T,v]=g.body.tee(),this.throughputEstimator?.trackStream(v,n)}let S=T.getReader(),x,P=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(P)&&(x=P),!x&&i&&(x=i.to-i.from+1);let A=x?new Uint8Array(x):new Uint8Array(0),w=!1,R=v=>{this.unsubscribeAbortSubscription(m),w=!0,la(v)},E=Dr(p,async function*({done:v,value:I}){if(f===0&&(this.lastRequestFirstBytes$.next(Br()-b),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!v&&I){if(l&&x)A.set(I,f),f+=I.byteLength;else{let Q=new Uint8Array(A.length+I.length);Q.set(A),Q.set(I,A.length),A=Q,f+=I.byteLength}r?.(new DataView(A.buffer),f),yield S?.read().then(E,R)}}.bind(this));yield S?.read().then(E,R),this.unsubscribeAbortSubscription(m);let O=Br(),M={failed:w,requestStartedAt:b,requestEndedAt:O,duration:O-b};return w?(c.error("endRequest",yi(M)),c.end(),null):(c.log("endRequest",yi(M)),c.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=Dr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,u=s,n=!1,l,h;e.indexRange&&(l=e.indexRange.from,h=e.indexRange.to,n=s+1===l,n&&(a=Math.min(l,r),u=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!d)return null;let c=new DataView(d,r-a,s-a+1);if(!t.validateData(c))throw new Error("Invalid media file");let p=t.parseInit(c),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(n)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=Dr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ns(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:sl(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Vr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Vr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Vr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Vr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Vr.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},la=o=>{if(!Xe(o))throw o};import{isNullable as Zh,ValueSubject as ep}from"@vkontakte/videoplayer-shared/evergreen";var Cr=class o{constructor(e,t){this.currentRepresentation$=new ep(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!Zh(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<a||e>u)continue;let n=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!n||this.currentSegment?.time.from===n.time.from&&this.currentSegment.time.to===n.time.to||(this.currentSegment=n,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(n.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=o.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Pe(t.segmentReference))}};var np=["progress","play","seeked","stalled","waiting"],op=["timeupdate","progress","loadeddata","playing","seeked"];var ha=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Dn;this.subscriptionRemovable=new sp;this.representationSubscription=new Dn;this.state$=new C("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new wt;this.manifestRequested=new wt;this.manifestReceived=new wt;this.firstBytesRequested=new wt;this.firstBytesReceived=new wt;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new wt;this.fetcherError$=new wt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new wt;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Ln(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=J(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ue.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ln(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ue.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Fs(e??"",this.manifestUrlString)}catch(n){let l=Cs(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(l)}if(!t)return null;let i=(n,l,h)=>!!(this.element?.canPlayType?.(l)&&Ae()?.isTypeSupported?.(`${l}; codecs="${h}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:l,streamIsUnpublished:h,streamIsAlive:d}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let n of["video","audio"]){let h=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p));r[n]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=h.map(({codecs:p})=>p);n==="audio"&&(a=Xs(c),d=a[0]),n==="video"&&(s=Ks(c),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[n]=h.filter(({codecs:p})=>pi(p)===d))}else{let c=new Set(h.map(({codecs:p})=>p));d=Ys(c),d&&(r[n]=h.filter(({codecs:p})=>p.startsWith(d)))}if(n==="video"){let c=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);D.display.isHDR&&c&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Fr(u)),u}.bind(this));this.initRepresentations=Ln(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Fr({initialVideo:e,initialAudio:t,sourceHls:i})),Ti(this.manifest),Ti(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Dn,this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Je(c,"error").pipe(ca(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ue.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=ms();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Jt())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new Mr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],_r(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new Mr("audio",this.source,c,a),this.bufferManagers.push(this.audioBufferManager)}Cr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Cr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let n=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Qt(...op.map(c=>Je(this.element,c))).pipe(Ei(c=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),Or(),ap(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&n()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Qt(Je(this.element,"ended"),this.forceEnded$).subscribe(()=>{n()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Or()).subscribe(p=>this.liveStreamEndTimestamp=Mn())),this.subscription.add(Je(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Rn(1e3).subscribe(p=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Je(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ii({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ei(({isActiveLive:p,isLowLatency:m})=>p&&m),Or()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||hi(this.element,1)})),this.representationSubscription.add(Ii({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ca(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(Ii({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ca(({isLive:p})=>p),Or((p,m)=>m.bufferLength<p.bufferLength),Ei(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=pt(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ii({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=p-b;if(this.isManualDecreasePlaybackInLive())return;let S=1;Math.abs(T)>g&&(S=1+Math.sign(T)*y),hi(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(Ii({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ul(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=pt(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,x=isFinite(p)?p:m,P=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let w="none";if(P?w="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),w="active_low_latency"):b!==0&&x<y?w="live_forward_buffering":x<y+S&&(w="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),w==="live_forward_buffering"||w==="live_with_target_offset"){let R=c-(y+T),E=this.normolizeLiveOffset(Math.trunc(b+R/f)),O=Math.abs(E-b),M=0;!p||O<=this.tuning.dashCmafLive.offsetCalculationError?M=b:E>0&&O>this.tuning.dashCmafLive.offsetCalculationError&&(M=E),this.manifestUrlString=J(this.manifestUrlString,M,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(c=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ue.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=Qt(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Ei(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),h=Qt(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Ei(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),d=Ii({allBuffersFull:l,someBufferEnded:h}).pipe(Or(),Ei(({allBuffersFull:c,someBufferEnded:p})=>c&&p),ca(c=>c));if(this.representationSubscription.add(Qt(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Qt(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Pe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&_r(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Rn(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ue.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new da({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=nt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Ti(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Mn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=J(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Ti(this.element),this.state$.setState("running");let e=Je(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(ul(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Qt(...np.map(t=>Je(this.element,t)),Je(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ue.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Je(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Je(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&ce(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=Mn(),a=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,h=this.audioBufferManager?.getForwardBufferDuration()??0,d=l<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&h<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:Ue.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Fr(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Rn(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Ti(this.element),Ti(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),ce(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ol(this.element)||ol(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Fr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){_r(this.element)&&_r(this.source)&&_r(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=rp(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let l of n.gaps)(l.persistent||n.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?a=1/0:(a===null||l.to>a)&&(a=l.to));if(a!==null){let n=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,this.tracer.log("jumpGap",Fr({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:n,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as up,map as lp,observeElementSize as dp,Subscription as cp,ValueSubject as Bn,noop as hp}from"@vkontakte/videoplayer-shared/evergreen";var pa=class{constructor(){this.subscription=new cp;this.pipSize$=new Bn(void 0);this.videoSize$=new Bn(void 0);this.elementSize$=new Bn(void 0);this.pictureInPictureWindowRemoveEventListener=hp}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(dp(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(up({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(lp(({videoSize:r,inPip:s,pipSize:a})=>s?a:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Wt=class{constructor(e){this.subscription=new yp;this.videoState=new C("stopped");this.observableVideo=null;this.droppedFramesManager=new ai;this.stallsManager=new ra;this.elementSizeManager=new pa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new bt;this.audioTrackSwitchHistory=new bt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return mp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new gi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ha({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;vp(this.observableVideo)&&(this.observableVideo=xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:ll.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,u)=>this.subscription.add(a.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Vn(d=>!!d.length),cl()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ur(d=>d.to.state!=="none"),Nr());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Vn(dl),cl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ur(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(fp(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of c.audio){f.push(En(b));let g=[];for(let y of b.representations){let T=Zu(y);g.push(T),this.audioTracksMap.set(T,{stream:b,representation:y})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of c.video){m.push(xn(f));let b=[];for(let g of f.representations){let y=Rr({...g,streamId:f.id});y&&(b.push(y),this.videoTracksMap.set(y,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of c.text)for(let b of f.representations){let g=el(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,n=u&&rl(u)||null;this.subscription.add(Hr(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Sp(this.video,"progress")).pipe(Vn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c||d==="running"&&n&&!n())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=Ut(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);dl(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(bp({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Hr(ma([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Ur(d=>d.to)))}).pipe(Ur(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),Nr()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Nr()).subscribe(d=>{let c=Ut(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(xn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Nr()).subscribe(d=>{let c=Ut(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(En(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Ur(({to:d})=>d==="ready"),Nr());this.subscription.add(Hr(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ma(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Hr(l,this.player.state$.stateChangeEnded$,ma(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Hr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ma(["init"])).pipe(gp(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Oi:Ci,t=this.params.tuning.useNewAutoSelectVideoTrack?Rs:Ls,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:Ps,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,n=Ut(this.videoTracksMap.keys(),w=>w.id===u),l=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=Ut(this.videoStreamsMap.keys(),w=>w.id===h.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let p=de(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),y=g?.id&&Ut(this.audioStreamsMap.keys(),w=>w.id===g.id)||this.audioStreamsMap.keys().next().value,T=0;if(y){if(n&&!a){let w=e(n,c,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,c,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let S=n;(a||!S)&&(S=i(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=y&&t(S,c,this.audioStreamsMap.get(y)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=this.videoTracksMap.get(S)?.representation,A=x&&this.audioTracksMap.get(x)?.representation;P&&A?(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=A):P&&!A&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=P,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ll.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var jr=class extends Wt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Cn,merge as hl,filter as pl,filterChanged as ml,isNullable as On,map as fl,ValueSubject as Fn,isNonNullable as Tp}from"@vkontakte/videoplayer-shared/evergreen";var Qr=class extends Wt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let u=new Fn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(ml()).subscribe(n=>{let l=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!n&&!l&&d?e=!0:n&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(fl(n=>n.to)).subscribe(this.player.isLowLatency$)).add(Cn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fl(({liveBufferTime:n,liveAvailabilityStartTime:l})=>n&&l?n+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(pl(n=>Tp(n))).subscribe(n=>i.isLiveEnded$.next(n!=="active"&&i.position$.getValue()===0))).add(Cn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:hl(r.playbackRateState$,new Fn(1))}).pipe(pl(({liveStreamStatus:n,liveDuration:l})=>n==="active"&&!!l)).subscribe(({liveDuration:n,playbackRate:l})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||On(h)||(t=n-h)})).add(Cn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:hl(r.playbackRateState$,new Fn(1))}).pipe(ml((n,l)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===l.liveDuration:n.time===l.time)).subscribe(({time:n,liveDuration:l,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-c||On(n)||On(l))return;let p=-1*(l-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let l=tl(n);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var bl="X-Playback-Duration",_n=async o=>{let e=await fetch(o),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(bl)?parseInt(e.headers.get(bl),10):void 0};import{assertNever as Mp,combine as Dp,debounce as Bp,ErrorCategory as ga,filter as Vp,filterChanged as Cp,isNonNullable as vl,isNullable as Sa,map as yl,merge as Op,observableFrom as Fp,Subscription as _p,ValueSubject as Un,VideoQuality as Np}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Ip,getExponentialDelay as Ep}from"@vkontakte/videoplayer-shared/evergreen";var xp=o=>{let e=null;if(o.QUALITY&&(e=ft(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Ip({width:t,height:i})}return e??null},wp=(o,e)=>{let t=o.split(`
|
|
178
178
|
`),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],u=a.match(/^#EXT-X-STREAM-INF:(.+)/),n=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!n)){if(u){let l=Object.fromEntries(u[1].split(",").map(b=>b.split("="))),h=l.QUALITY??`stream-${l.BANDWIDTH}`,d=xp(l),c;l.BANDWIDTH&&(c=parseInt(l.BANDWIDTH,10)/1e3||void 0),!c&&l["AVERAGE-BANDWIDTH"]&&(c=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[b,g]=l.RESOLUTION.split("x").map(y=>parseInt(y,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();d&&i.push({id:h,quality:d,url:f,bandwidth:c,size:m,fps:p})}if(n){let l=Object.fromEntries(n[1].split(",").map(p=>{let m=p.indexOf("=");return[p.substring(0,m),p.substring(m+1)]}).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),h=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,c=l.NAME;h&&d&&r.push({type:"internal",id:d,label:c,language:d,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},kp=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),Nn=0,gl=async(o,e=o,t,i)=>{let s=await(await fetch(o,i)).text();Nn+=1;try{let{qualityManifests:a,textTracks:u}=wp(s,e);return{qualityManifests:a,textTracks:u}}catch{if(Nn<=t.manifestRetryMaxCount)return await kp(Ep(Nn-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),gl(o,e,t)}return{qualityManifests:[],textTracks:[]}},fa=gl;import{isNonNullable as Ap,Subscription as $p,throttle as Pp,ValueSubject as Sl,Subject as Lp,ErrorCategory as Rp}from"@vkontakte/videoplayer-shared/evergreen";var ba=class{constructor(e,t,i,r,s){this.subscription=new $p;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Sl(null);this.getCurrentTime$=new Sl(null);this.error$=new Lp;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(Pp(1e3)).subscribe(a=>{this.processLiveTime(a)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),a=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),u=this.parsePlaylist(a,r);return{textTrack:i,playlist:u}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
179
|
-
`),s=0;for(let a=0;a<r.length;++a){let u=r[a];switch(!0){case u.startsWith("#EXTINF:"):{let n=r[++a],l=new URL(n,t).toString(),h=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+h},url:l}),s=s+h,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),c=new Date(i.programDateTime).valueOf();i.segmentStartTime=c-d}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let n=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=n;let l=new Date(n);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Ap(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let a of t)if(a.time.from<=e&&a.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:a.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Rp.WTF,thrown:t,message:e})}};var Wr=class{constructor(e){this.subscription=new _p;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Un([]);this.liveOffset=new Bt;this.manifestStartTime$=new Un(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(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 h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else r?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Mp(t)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Np.INVARIANT,url:this.params.source.url};let t=(i,r)=>fa(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new ba(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Be(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ga.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ga.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(le(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Un(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(n=>n.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:ga.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(Cp(),yl(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),n=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&vl(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let c=this.manifests$.getValue().find(p=>p.id===d);c&&(this.params.output.currentVideoTrack$.next(c),this.params.output.hostname$.next(le(c.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),n&&n.from==="changing_manifest"&&this.videoState.setState(n.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(Dp({startTime:this.manifestStartTime$.pipe(Vp(vl)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:n})=>this.params.output.liveTime$.next(u+n*1e3),i)),this.subscription.add(this.manifests$.pipe(yl(u=>u.map(({id:n,quality:l,size:h,bandwidth:d,fps:c})=>({id:n,quality:l,size:h,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Op(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Fp(["init"])).pipe(Bp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Sa(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:u,min:n}=t?.to??i??{};for(let[l,h]of[[u,"mq"],[n,"lq"]]){let d=String(parseFloat(l||""));h&&l&&r.searchParams.set(h,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=J(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),_n(a).then(u=>{if(!Sa(u))this.maxSeekBackTime$.next(u);else{let n=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Sa(n)||!isFinite(n))&&fetch(a).then(l=>l.text()).then(l=>{let h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(h){let d=new URL(h,a).toString();_n(d).then(c=>{Sa(c)||this.maxSeekBackTime$.next(c)})}}).catch(()=>{})}})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ga.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=J(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as Up,debounce as Hp,ErrorCategory as Hn,fromEvent as jn,isNonNullable as jp,isNullable as Qp,map as Tl,merge as Il,observableFrom as El,Subscription as Wp,ValueSubject as xl,VideoQuality as qp}from"@vkontakte/videoplayer-shared/evergreen";var qr=class{constructor(e){this.subscription=new Wp;this.videoState=new C("stopped");this.manifests$=new xl([]);this.unmuteAfterBrowserResetsHappened=new xl(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h);let{currentTime:d}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Up(t)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:qp.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(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),fa(J(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),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:Hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(n=>n.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:Hn.WTF,message:"HlsProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Tl(u=>u.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),n=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&jp(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(le(m.url)))}let d=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),n&&n.from==="changing_manifest"&&this.videoState.setState(n.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(Tl(u=>u.map(({id:n,quality:l,size:h,bandwidth:d,fps:c})=>({id:n,quality:l,size:h,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!D.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(Il(jn(u,"addtrack"),jn(u,"removetrack"),jn(u,"change"),El(["init"])).subscribe(()=>{for(let n=0;n<u.length;n++)u[n].mode="hidden"},i))}let a=Il(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,El(["init"])).pipe(Hp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Qp(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[u,n]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(u||""));n&&u&&r.searchParams.set(n,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as zp,assertNonNullable as wl,debounce as Gp,ErrorCategory as kl,isHigherOrEqual as Yp,isLowerOrEqual as Kp,isNonNullable as Xp,merge as Jp,observableFrom as Zp,Subscription as em,map as tm}from"@vkontakte/videoplayer-shared/evergreen";var zr=class{constructor(e){this.subscription=new em;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Be;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:n}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:n*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return zp(e)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:kl.WTF,message:"MpegProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(tm(u=>u.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,i)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&Xp(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let n=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(n!==l){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(n),h.playbackRate=n)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=Jp(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Zp(["init"])).pipe(Gp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;wl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=yt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(le(t))}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let h=Ye(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(h)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||ti(e,a[0].quality,a.at(-1)?.quality)){i();return}let u=e.max?Kp(r,e.max):!0,n=e.min?Yp(r,e.min):!0;u&&n||i(e)}};import{assertNever as $l,debounce as am,merge as Pl,observableFrom as nm,Subscription as om,map as Ll,ValueSubject as um,ErrorCategory as Wn,VideoQuality as lm}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as im}from"@vkontakte/videoplayer-shared/evergreen";var Al=["stun:videostun.mycdn.me:80"],rm=1e3,sm=3,Qn=()=>null,va=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=Qn;this.externalStopCallback=Qn;this.externalErrorCallback=Qn;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Al}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:im.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),rm)}normalizeOptions(e={}){let t={stunServerList:Al,maxRetryNumber:sm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Gr=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new um(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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return $l(e)}};this.subscription=new om,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Te(e.container,e.tuning),this.liveStreamClient=new va(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:Wn.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(Pl(this.videoState.stateChangeStarted$.pipe(Ll(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ll(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(a)}`})}));let r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(a,u)=>this.subscription.add(a.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ve(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ee(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return $l(a.to)}},i)).add(Pl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,nm(["init"])).pipe(am(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(le(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:lm.INVARIANT}),this.video.srcObject=e,k(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:Wn.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wn.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xi=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Yr,assertNonNullable as kt,ErrorCategory as ya,filter as Cl,isNonNullable as Ol,isNullable as bm,map as gm,merge as Sm,once as vm,Subject as Z,Subscription as Fl,ValueSubject as V,flattenObject as qn}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as dm,map as Rl,Subscription as cm,Subject as hm}from"@vkontakte/videoplayer-shared/evergreen";var Ml=o=>new dm(e=>{let t=new cm,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Rl(({from:l,to:h})=>`${l}-${h}`)),r=o.desiredPlaybackState$.stateChangeEnded$,s=o.providerChanged$.pipe(Rl(({type:l})=>l!==void 0)),a=new hm,u=0,n="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),n=l,u=window.setTimeout(()=>a.next(l),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),n="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>a.next(n),o.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as pm,Subscription as mm,combine as fm,filter as Bl,once as Vl}from"@vkontakte/videoplayer-shared/evergreen";function Dl(){return new(window.AudioContext||window.webkitAudioContext)}var wi=class o{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new mm;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Bl(s=>!!s.type),Vl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){D.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(fm({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Bl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Vl()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Dl();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:o.errorId,category:pm.VIDEO_PIPELINE,message:e?.message??`${o.errorId} exception`,thrown:e})}};var ym={chunkDuration:5e3,maxParallelRequests:5},Kr=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Z;this.noAvailableProvidersError$=new Z;this.volumeMultiplierError$=new Z;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableVideoCodecs$:new V([]),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),availableAudioCodecs$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Z,fetcherError$:new Z,fetcherRecoverableError$:new Z,warning$:new Z,willSeekEvent$:new Z,soundProhibitedEvent$:new Z,seekedEvent$:new Z,loopedEvent$:new Z,endedEvent$:new Z,manifestRequested$:new Z,manifestReceived$:new Z,firstBytesRequested$:new Z,firstBytesReceived$:new Z,firstBytesEvent$:new Z,loadedMetadataEvent$:new Z,firstFrameEvent$:new Z,canplay$:new Z,isLive$:new V(void 0),isLiveEnded$:new V(null),canPlayLiveTailBuffer$:new V(!1),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),severeStallOccurred$:new Z,availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new Fl;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Ba([...Du(this.params.tuning),...Mu(this.params.tuning)]).filter(l=>Ol(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",qn(s)),this.screenFormatsIterator=new xi(s);let a=[...ln(!0),...ln(!1)];this.chromecastFormatsIterator=new xi(a.filter(l=>Ol(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:n}}=this.params;n&&u!==1&&wi.isSupported()&&(this.volumeMultiplierManager=new wi(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new xi(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(bm(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:ya.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Yr(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,u={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let n=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return kt(n),this.params.tuning.useNewDashProvider?new jr({...u,source:n,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Pr({...u,source:n,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return kt(n),this.params.tuning.useNewDashProvider?new Qr({...u,source:n}):new Lr({...u,source:n})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let n=this.applyFailoverHost(t[e]);return kt(n),new qr({...u,source:n})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return kt(n),new Wr({...u,source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let n=this.applyFailoverHost(t[e]);return kt(n),new zr({...u,source:n})}case"DASH_LIVE":{let n=this.applyFailoverHost(t[e]);return kt(n),new uu({...u,source:n,config:{...ym,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let n=this.applyFailoverHost(t[e]);return kt(n),new Gr({container:i,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yr(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return kt(u),new Ri({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Yr(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Yr(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 Yr(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Fl,t=!1,i=0;return e.add(Sm(this.providerOutput.error$.pipe(Cl(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Ml({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(gm(r=>({id:`ProviderHangup:${r}`,category:ya.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Cl(({to:s})=>s==="playing"),vm()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,a={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===ya.NETWORK,n=r.category===ya.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),h=i<this.params.tuning.providerErrorLimit&&!n,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,c=l&&!n&&(u&&t||!h);a={...a,isNetworkError:u,isFatalError:n,haveFailoverHost:l,tryFailover:c,canReinitProvider:h},h?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",qn(a)):this.tracer.error("providerError",qn(a))})),e}};import{fromEvent as Ta,once as Tm,combine as Im,Subscription as _l,ValueSubject as zn,map as Em,filter as xm,isNonNullable as Ia,now as Le,safeStorage as Gn}from"@vkontakte/videoplayer-shared/evergreen";var wm=5e3,Nl="one_video_throughput",Ul="one_video_rtt",Xr=window.navigator.connection,Hl=()=>{let o=Xr?.downlink;if(Ia(o)&&o!==10)return o*1e3},jl=()=>{let o=Xr?.rtt;if(Ia(o)&&o!==3e3)return o},Ql=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},Yn=class o{constructor(e){this.subscription=new _l;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=o.load(Nl)||(e.useBrowserEstimation?Hl():void 0)||wm,i=o.load(Ul)??(e.useBrowserEstimation?jl():void 0)??0;if(this.throughput$=new zn(t),this.rtt$=new zn(i),this.rttAdjustedThroughput$=new zn(Ql(t,i,e.rttPenaltyRequestSize)),this.throughput=nt.getSmoothedValue(t,-1,e),this.rtt=nt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Hl();a&&this.throughput.next(a);let u=jl();Ia(u)&&this.rtt.next(u)};Xr&&"onchange"in Xr&&this.subscription.add(Ta(Xr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Gn.set(Nl,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Gn.set(Ul,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Im({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Em(({throughput:r,rtt:s})=>Ql(r,s,e.rttPenaltyRequestSize)),xm(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Le(),r=new _l;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Ta(e,"progress").pipe(Tm()).subscribe(s=>{t=s.loaded,i=Le()}));break;case 1:case 0:r.add(Ta(e,"loadstart").subscribe(()=>{t=0,i=Le()}));break}r.add(Ta(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,u=Le(),n=a-t,l=u-i;this.addRawSpeed(n,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Le(),a=0,u=Le(),n=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},l=async({done:h,value:d})=>{if(h)!t&&this.addRawSpeed(r,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let c=Le();if(c-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||c-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(a,m,1,t),a=d.byteLength,s=Le()}else a+=d.byteLength;u=Le()}else r+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Le()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Le()-u,this.concurrentDownloads.size),a=0,u=Le());await i?.read().then(l,n)}};this.concurrentDownloads.add(e),i?.read().then(l,n)}addRawSpeed(e,t,i=1,r=!1){if(o.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Gn.get(e);if(Ia(t))return parseInt(t,10)??void 0}},Wl=Yn;import{fillWithDefault as km,VideoQuality as Ea}from"@vkontakte/videoplayer-shared/evergreen";var ql={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ea.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ea.Q_720P,trafficSavingLimit:Ea.Q_480P},stallsManager:{enabled:!0,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ea.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},zl=o=>({...km(o,ql),configName:[...o.configName??[],...ql.configName]});import{assertNonNullable as Xn,combine as ut,ErrorCategory as xa,filter as re,filterChanged as W,fromEvent as Jn,isNonNullable as Xl,isNullable as Dm,Logger as Bm,map as j,mapTo as Jl,merge as At,now as wa,once as he,Subject as H,Subscription as Zl,tap as Zn,ValueSubject as $,isHigher as Vm,isInvariantQuality as ed,flattenObject as $t,throttle as eo,getTraceSubscriptionMethod as td,TracerFactory as Cm,InternalsExposure as Om,getPlayerId as Fm}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Am,map as $m,filter as Gl,isNonNullable as Pm}from"@vkontakte/videoplayer-shared/evergreen";var Kn=({seekState:o,position$:e})=>Am(o.stateChangeEnded$.pipe($m(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Gl(Pm)),e.pipe(Gl(()=>o.getState().state==="none")));import{assertNonNullable as Lm}from"@vkontakte/videoplayer-shared/evergreen";var Yl=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return Lm(e,`Wrong container or containerId {${o.container}}`),e};import{filter as Rm,once as Mm}from"@vkontakte/videoplayer-shared/evergreen";var Kl=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Rm(r=>r.length>0),Mm()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t?.getValue().find(i))&&e.startTransitionTo(o)};var ka=class{constructor(e={configName:[]},t=Cm.createRootTracer(!1),i){this.subscription=new Zl;this.logger=new Bm;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new $(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new $(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new $(void 0),position$:new $(0),duration$:new $(1/0),muted$:new $(!1),volume$:new $(1),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableQualities$:new $([]),availableQualitiesFps$:new $({}),currentQuality$:new $(void 0),isAutoQualityEnabled$:new $(!0),autoQualityLimitingAvailable$:new $(!1),autoQualityLimits$:new $({}),predefinedQualityLimitType$:new $("unknown"),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),isAudioAvailable$:new $(!0),currentPlaybackRate$:new $(1),currentBuffer$:new $({start:0,end:0}),isBuffering$:new $(!0),isStalled$:new $(!1),isEnded$:new $(!1),isLooped$:new $(!1),isLive$:new $(void 0),isLiveEnded$:new $(null),canPlayLiveTailBuffer$:new $(!1),canChangePlaybackSpeed$:new $(void 0),atLiveEdge$:new $(void 0),atLiveDurationEdge$:new $(void 0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),liveLatency$:new $(void 0),currentFormat$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),throughputEstimation$:new $(void 0),rttEstimation$:new $(void 0),videoBitrate$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),surface$:new $("none"),chromecastState$:new $("NOT_AVAILABLE"),chromecastDeviceName$:new $(void 0),intrinsicVideoSize$:new $(void 0),availableSources$:new $(void 0),is3DVideo$:new $(!1),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willReady$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,fetcherRecoverableError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,manifestRequested$:new H,manifestReceived$:new H,firstBytesRequested$:new H,firstBytesReceived$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H,fetcherError$:new H,severeStallOccured$:new H};this.experimental={element$:new $(void 0),tuningConfigName$:new $([]),enableDebugTelemetry$:new $(!1),dumpTelemetry:Fo,getCurrentTime$:new $(null)};if(this.initLogs(),this.tuning=zl(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(r=>r.setSuppressErrors(!0)),Object.values(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ls({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Wl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Om("core",Fm(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,s,a)=>{let u=Reflect.get(r,s,a);return typeof u!="function"?u:(...n)=>{try{return u.apply(r,n)}catch(l){let h=n.map(p=>JSON.stringify(p,(m,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${h.join(", ")})`;throw this.events.fatalError$.next({id:d,category:xa.WTF,message:c,thrown:l}),l}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",$t(a)),this.domContainer=Yl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Kr({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?D.isInited$.pipe(re(s=>!!s),he()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Jn(document,"visibilitychange").pipe(he()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(re(t=>!!t),he()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Xn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),he()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",$t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",$t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Kl(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Dm(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Xl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(No(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),he()).subscribe(()=>{this.initedAt=wa(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",$t(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:xa.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(he()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",$t(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(j(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(a=>a.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ut({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:a,currentVideoStream:u})=>a.filter(n=>u?u.id===n.streamId:!0).map(({quality:n})=>n).sort((n,l)=>ed(n)?1:ed(l)?-1:Vm(l,n)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let u={};for(let n of a)n.fps&&(u[n.quality]=n.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(W()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(re(a=>Xl(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(W((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(W((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(W()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(W()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(W()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(j(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Zn(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ut({hasLiveOffsetByPaused:At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(a=>a.to),W(),j(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add(ut({atLiveEdge:ut({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Kn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:a,position:u,isLowLatency:n})=>{let l=this.getActiveLiveDelay(n);return a&&Math.abs(u)<l/1e3}),W(),Zn(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:a,hasPausedTimeoutCase:u})=>a&&!u)).subscribe(this.info.atLiveEdge$)).add(ut({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:a,position:u,duration:n})=>a&&(Math.abs(n)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),W(),Zn(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(a=>a.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(a=>a.volume),W()).subscribe(this.info.volume$)).add(Kn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(At(e.providerOutput.endedEvent$.pipe(Jl(!0)),e.providerOutput.seekedEvent$.pipe(Jl(!1))).pipe(W()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(j(a=>({id:a?`No${a}`:"NoProviders",category:xa.VIDEO_PIPELINE,message:a?`${a} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(he()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(he()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(he()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(he()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(he(),j(a=>a??wa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(he(),j(()=>wa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(he(),j(()=>wa()-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 $(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new $(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:a})=>a==="playing"),he()).subscribe(()=>i.next(!1)));let r=0,s=At(e.providerOutput.isBuffering$,t,i).pipe(j(()=>{let a=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return a&&!u}),W());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(At(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(At(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),n=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue(),d;h==="CONNECTED"?d="second_screen":n?l?a?d="pip":u?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(j(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Zl;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),he()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Ye(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(At(this.desiredState.videoTrack.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Xn(this.providerContainer),Xn(e),Oo(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Co(t)),this.providerContainer.current$.subscribe(({type:t})=>Vi("provider",t)),e.duration$.subscribe(t=>Vi("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),he()).subscribe(t=>Vi("tracks",t)),this.events.fatalError$.subscribe(new ge("fatalError")),this.events.managedError$.subscribe(new ge("managedError")),e.position$.subscribe(new ge("position")),e.currentVideoTrack$.pipe(j(t=>t?.quality)).subscribe(new ge("quality")),this.info.currentBuffer$.subscribe(new ge("buffer")),e.isBuffering$.subscribe(new ge("isBuffering"))].forEach(t=>this.subscription.add(t)),Vi("codecs",D.video.supportedCodecs)}initTracerSubscription(){let e=td(this.tracer.log.bind(this.tracer)),t=td(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(W()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ut({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(i=>i>0),W()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ut({currentBuffer:this.info.currentBuffer$.pipe(re(i=>i.end>0),W((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(W())}).pipe(eo(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(ut({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),eo(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),re(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),re(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),re(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ut({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:i,rtt:r})=>!!i&&!!r),eo(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),re(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:xa.DOM,message:String(r)})})};this.subscription.add(At(Jn(document,"visibilitychange"),Jn(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",$t({quality:t,availableTracks:$t(e),track:$t(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Hi()}};import{Subscription as ND,Observable as UD,Subject as HD,ValueSubject as jD,VideoQuality as QD}from"@vkontakte/videoplayer-shared/evergreen";var WD=`@vkontakte/videoplayer-core@${io}`;export{ns as ChromecastState,Pa as HttpConnectionType,UD as Observable,ye as PlaybackState,ka as Player,os as PredefinedQualityLimits,WD as SDK_VERSION,HD as Subject,ND as Subscription,La as Surface,io as VERSION,jD as ValueSubject,et as VideoFormat,QD as VideoQuality,Td as areValidLiveRecordSources,D as clientChecker,Li as isMobile};
|
|
179
|
+
`),s=0;for(let a=0;a<r.length;++a){let u=r[a];switch(!0){case u.startsWith("#EXTINF:"):{let n=r[++a],l=new URL(n,t).toString(),h=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+h},url:l}),s=s+h,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),c=new Date(i.programDateTime).valueOf();i.segmentStartTime=c-d}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let n=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=n;let l=new Date(n);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(Ap(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let a of t)if(a.time.from<=e&&a.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:a.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Rp.WTF,thrown:t,message:e})}};var Wr=class{constructor(e){this.subscription=new _p;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Un([]);this.liveOffset=new Bt;this.manifestStartTime$=new Un(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(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 h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else r?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Mp(t)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Np.INVARIANT,url:this.params.source.url};let t=(i,r)=>fa(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new ba(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Be(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ga.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ga.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(le(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Un(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(n=>n.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:ga.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(Cp(),yl(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),n=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&vl(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let c=this.manifests$.getValue().find(p=>p.id===d);c&&(this.params.output.currentVideoTrack$.next(c),this.params.output.hostname$.next(le(c.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),n&&n.from==="changing_manifest"&&this.videoState.setState(n.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(Dp({startTime:this.manifestStartTime$.pipe(Vp(vl)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:n})=>this.params.output.liveTime$.next(u+n*1e3),i)),this.subscription.add(this.manifests$.pipe(yl(u=>u.map(({id:n,quality:l,size:h,bandwidth:d,fps:c})=>({id:n,quality:l,size:h,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Op(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Fp(["init"])).pipe(Bp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Sa(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:u,min:n}=t?.to??i??{};for(let[l,h]of[[u,"mq"],[n,"lq"]]){let d=String(parseFloat(l||""));h&&l&&r.searchParams.set(h,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=J(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),_n(a).then(u=>{if(!Sa(u))this.maxSeekBackTime$.next(u);else{let n=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Sa(n)||!isFinite(n))&&fetch(a).then(l=>l.text()).then(l=>{let h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(h){let d=new URL(h,a).toString();_n(d).then(c=>{Sa(c)||this.maxSeekBackTime$.next(c)})}}).catch(()=>{})}})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ga.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=J(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as Up,debounce as Hp,ErrorCategory as Hn,fromEvent as jn,isNonNullable as jp,isNullable as Qp,map as Tl,merge as Il,observableFrom as El,Subscription as Wp,ValueSubject as xl,VideoQuality as qp}from"@vkontakte/videoplayer-shared/evergreen";var qr=class{constructor(e){this.subscription=new Wp;this.videoState=new C("stopped");this.manifests$=new xl([]);this.unmuteAfterBrowserResetsHappened=new xl(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h);let{currentTime:d}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Up(t)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:qp.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(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),fa(J(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.manifestReceived$.next(),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:Hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(n=>n.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:Hn.WTF,message:"HlsProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Tl(u=>u.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),n=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&jp(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(le(m.url)))}let d=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),n&&n.from==="changing_manifest"&&this.videoState.setState(n.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(Tl(u=>u.map(({id:n,quality:l,size:h,bandwidth:d,fps:c})=>({id:n,quality:l,size:h,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!D.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(Il(jn(u,"addtrack"),jn(u,"removetrack"),jn(u,"change"),El(["init"])).subscribe(()=>{for(let n=0;n<u.length;n++)u[n].mode="hidden"},i))}let a=Il(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,El(["init"])).pipe(Hp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Qp(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[u,n]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(u||""));n&&u&&r.searchParams.set(n,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as zp,assertNonNullable as wl,debounce as Gp,ErrorCategory as kl,isHigherOrEqual as Yp,isLowerOrEqual as Kp,isNonNullable as Xp,merge as Jp,observableFrom as Zp,Subscription as em,map as tm}from"@vkontakte/videoplayer-shared/evergreen";var zr=class{constructor(e){this.subscription=new em;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Be;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:n}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:n*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return zp(e)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:kl.WTF,message:"MpegProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(tm(u=>u.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,i)),Si({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&Xp(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let n=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(n!==l){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(n),h.playbackRate=n)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=Jp(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Zp(["init"])).pipe(Gp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;wl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=yt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(le(t))}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let h=Ye(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(h)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||ti(e,a[0].quality,a.at(-1)?.quality)){i();return}let u=e.max?Kp(r,e.max):!0,n=e.min?Yp(r,e.min):!0;u&&n||i(e)}};import{assertNever as $l,debounce as am,merge as Pl,observableFrom as nm,Subscription as om,map as Ll,ValueSubject as um,ErrorCategory as Wn,VideoQuality as lm}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as im}from"@vkontakte/videoplayer-shared/evergreen";var Al=["stun:videostun.mycdn.me:80"],rm=1e3,sm=3,Qn=()=>null,va=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=Qn;this.externalStopCallback=Qn;this.externalErrorCallback=Qn;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Al}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:im.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),rm)}normalizeOptions(e={}){let t={stunServerList:Al,maxRetryNumber:sm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Gr=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new um(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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return $l(e)}};this.subscription=new om,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Te(e.container,e.tuning),this.liveStreamClient=new va(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:Wn.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(Pl(this.videoState.stateChangeStarted$.pipe(Ll(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ll(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(a)}`})}));let r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(a,u)=>this.subscription.add(a.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ve(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ee(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return $l(a.to)}},i)).add(Pl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,nm(["init"])).pipe(am(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(le(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:lm.INVARIANT}),this.video.srcObject=e,k(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:Wn.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wn.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xi=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Yr,assertNonNullable as kt,ErrorCategory as ya,filter as Cl,isNonNullable as Ol,isNullable as bm,map as gm,merge as Sm,once as vm,Subject as Z,Subscription as Fl,ValueSubject as V,flattenObject as qn}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as dm,map as Rl,Subscription as cm,Subject as hm}from"@vkontakte/videoplayer-shared/evergreen";var Ml=o=>new dm(e=>{let t=new cm,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Rl(({from:l,to:h})=>`${l}-${h}`)),r=o.desiredPlaybackState$.stateChangeEnded$,s=o.providerChanged$.pipe(Rl(({type:l})=>l!==void 0)),a=new hm,u=0,n="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),n=l,u=window.setTimeout(()=>a.next(l),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),n="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>a.next(n),o.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as pm,Subscription as mm,combine as fm,filter as Bl,once as Vl}from"@vkontakte/videoplayer-shared/evergreen";function Dl(){return new(window.AudioContext||window.webkitAudioContext)}var wi=class o{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new mm;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Bl(s=>!!s.type),Vl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){D.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(fm({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Bl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Vl()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Dl();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:o.errorId,category:pm.VIDEO_PIPELINE,message:e?.message??`${o.errorId} exception`,thrown:e})}};var ym={chunkDuration:5e3,maxParallelRequests:5},Kr=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Z;this.noAvailableProvidersError$=new Z;this.volumeMultiplierError$=new Z;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableVideoCodecs$:new V([]),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),availableAudioCodecs$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Z,fetcherError$:new Z,fetcherRecoverableError$:new Z,warning$:new Z,willSeekEvent$:new Z,soundProhibitedEvent$:new Z,seekedEvent$:new Z,loopedEvent$:new Z,endedEvent$:new Z,manifestRequested$:new Z,manifestReceived$:new Z,firstBytesRequested$:new Z,firstBytesReceived$:new Z,firstBytesEvent$:new Z,loadedMetadataEvent$:new Z,firstFrameEvent$:new Z,canplay$:new Z,isLive$:new V(void 0),isLiveEnded$:new V(null),canPlayLiveTailBuffer$:new V(!1),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),severeStallOccurred$:new Z,availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new Fl;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Ba([...Du(this.params.tuning),...Mu(this.params.tuning)]).filter(l=>Ol(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",qn(s)),this.screenFormatsIterator=new xi(s);let a=[...ln(!0),...ln(!1)];this.chromecastFormatsIterator=new xi(a.filter(l=>Ol(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:n}}=this.params;n&&u!==1&&wi.isSupported()&&(this.volumeMultiplierManager=new wi(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new xi(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(bm(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:ya.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Yr(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,u={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let n=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return kt(n),this.params.tuning.useNewDashProvider?new jr({...u,source:n,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Pr({...u,source:n,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return kt(n),this.params.tuning.useNewDashProvider?new Qr({...u,source:n}):new Lr({...u,source:n})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let n=this.applyFailoverHost(t[e]);return kt(n),new qr({...u,source:n})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return kt(n),new Wr({...u,source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let n=this.applyFailoverHost(t[e]);return kt(n),new zr({...u,source:n})}case"DASH_LIVE":{let n=this.applyFailoverHost(t[e]);return kt(n),new uu({...u,source:n,config:{...ym,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let n=this.applyFailoverHost(t[e]);return kt(n),new Gr({container:i,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yr(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return kt(u),new Ri({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Yr(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Yr(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 Yr(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Fl,t=!1,i=0;return e.add(Sm(this.providerOutput.error$.pipe(Cl(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Ml({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(gm(r=>({id:`ProviderHangup:${r}`,category:ya.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Cl(({to:s})=>s==="playing"),vm()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,a={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===ya.NETWORK,n=r.category===ya.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),h=i<this.params.tuning.providerErrorLimit&&!n,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,c=l&&!n&&(u&&t||!h);a={...a,isNetworkError:u,isFatalError:n,haveFailoverHost:l,tryFailover:c,canReinitProvider:h},h?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",qn(a)):this.tracer.error("providerError",qn(a))})),e}};import{fromEvent as Ta,once as Tm,combine as Im,Subscription as _l,ValueSubject as zn,map as Em,filter as xm,isNonNullable as Ia,now as Le,safeStorage as Gn}from"@vkontakte/videoplayer-shared/evergreen";var wm=5e3,Nl="one_video_throughput",Ul="one_video_rtt",Xr=window.navigator.connection,Hl=()=>{let o=Xr?.downlink;if(Ia(o)&&o!==10)return o*1e3},jl=()=>{let o=Xr?.rtt;if(Ia(o)&&o!==3e3)return o},Ql=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},Yn=class o{constructor(e){this.subscription=new _l;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=o.load(Nl)||(e.useBrowserEstimation?Hl():void 0)||wm,i=o.load(Ul)??(e.useBrowserEstimation?jl():void 0)??0;if(this.throughput$=new zn(t),this.rtt$=new zn(i),this.rttAdjustedThroughput$=new zn(Ql(t,i,e.rttPenaltyRequestSize)),this.throughput=nt.getSmoothedValue(t,-1,e),this.rtt=nt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Hl();a&&this.throughput.next(a);let u=jl();Ia(u)&&this.rtt.next(u)};Xr&&"onchange"in Xr&&this.subscription.add(Ta(Xr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Gn.set(Nl,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Gn.set(Ul,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Im({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Em(({throughput:r,rtt:s})=>Ql(r,s,e.rttPenaltyRequestSize)),xm(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Le(),r=new _l;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Ta(e,"progress").pipe(Tm()).subscribe(s=>{t=s.loaded,i=Le()}));break;case 1:case 0:r.add(Ta(e,"loadstart").subscribe(()=>{t=0,i=Le()}));break}r.add(Ta(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,u=Le(),n=a-t,l=u-i;this.addRawSpeed(n,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Le(),a=0,u=Le(),n=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},l=async({done:h,value:d})=>{if(h)!t&&this.addRawSpeed(r,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let c=Le();if(c-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||c-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(a,m,1,t),a=d.byteLength,s=Le()}else a+=d.byteLength;u=Le()}else r+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Le()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Le()-u,this.concurrentDownloads.size),a=0,u=Le());await i?.read().then(l,n)}};this.concurrentDownloads.add(e),i?.read().then(l,n)}addRawSpeed(e,t,i=1,r=!1){if(o.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Gn.get(e);if(Ia(t))return parseInt(t,10)??void 0}},Wl=Yn;import{fillWithDefault as km,VideoQuality as Ea}from"@vkontakte/videoplayer-shared/evergreen";var ql={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ea.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ea.Q_720P,trafficSavingLimit:Ea.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ea.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},zl=o=>({...km(o,ql),configName:[...o.configName??[],...ql.configName]});import{assertNonNullable as Xn,combine as ut,ErrorCategory as xa,filter as re,filterChanged as W,fromEvent as Jn,isNonNullable as Xl,isNullable as Dm,Logger as Bm,map as j,mapTo as Jl,merge as At,now as wa,once as he,Subject as H,Subscription as Zl,tap as Zn,ValueSubject as $,isHigher as Vm,isInvariantQuality as ed,flattenObject as $t,throttle as eo,getTraceSubscriptionMethod as td,TracerFactory as Cm,InternalsExposure as Om,getPlayerId as Fm}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Am,map as $m,filter as Gl,isNonNullable as Pm}from"@vkontakte/videoplayer-shared/evergreen";var Kn=({seekState:o,position$:e})=>Am(o.stateChangeEnded$.pipe($m(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Gl(Pm)),e.pipe(Gl(()=>o.getState().state==="none")));import{assertNonNullable as Lm}from"@vkontakte/videoplayer-shared/evergreen";var Yl=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return Lm(e,`Wrong container or containerId {${o.container}}`),e};import{filter as Rm,once as Mm}from"@vkontakte/videoplayer-shared/evergreen";var Kl=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Rm(r=>r.length>0),Mm()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t?.getValue().find(i))&&e.startTransitionTo(o)};var ka=class{constructor(e={configName:[]},t=Cm.createRootTracer(!1),i){this.subscription=new Zl;this.logger=new Bm;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new $(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new $(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new $(void 0),position$:new $(0),duration$:new $(1/0),muted$:new $(!1),volume$:new $(1),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableQualities$:new $([]),availableQualitiesFps$:new $({}),currentQuality$:new $(void 0),isAutoQualityEnabled$:new $(!0),autoQualityLimitingAvailable$:new $(!1),autoQualityLimits$:new $({}),predefinedQualityLimitType$:new $("unknown"),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),isAudioAvailable$:new $(!0),currentPlaybackRate$:new $(1),currentBuffer$:new $({start:0,end:0}),isBuffering$:new $(!0),isStalled$:new $(!1),isEnded$:new $(!1),isLooped$:new $(!1),isLive$:new $(void 0),isLiveEnded$:new $(null),canPlayLiveTailBuffer$:new $(!1),canChangePlaybackSpeed$:new $(void 0),atLiveEdge$:new $(void 0),atLiveDurationEdge$:new $(void 0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),liveLatency$:new $(void 0),currentFormat$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),throughputEstimation$:new $(void 0),rttEstimation$:new $(void 0),videoBitrate$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),surface$:new $("none"),chromecastState$:new $("NOT_AVAILABLE"),chromecastDeviceName$:new $(void 0),intrinsicVideoSize$:new $(void 0),availableSources$:new $(void 0),is3DVideo$:new $(!1),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willReady$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,fetcherRecoverableError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,manifestRequested$:new H,manifestReceived$:new H,firstBytesRequested$:new H,firstBytesReceived$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H,fetcherError$:new H,severeStallOccured$:new H};this.experimental={element$:new $(void 0),tuningConfigName$:new $([]),enableDebugTelemetry$:new $(!1),dumpTelemetry:Fo,getCurrentTime$:new $(null)};if(this.initLogs(),this.tuning=zl(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(r=>r.setSuppressErrors(!0)),Object.values(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ls({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Wl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Om("core",Fm(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,s,a)=>{let u=Reflect.get(r,s,a);return typeof u!="function"?u:(...n)=>{try{return u.apply(r,n)}catch(l){let h=n.map(p=>JSON.stringify(p,(m,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${h.join(", ")})`;throw this.events.fatalError$.next({id:d,category:xa.WTF,message:c,thrown:l}),l}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",$t(a)),this.domContainer=Yl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Kr({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?D.isInited$.pipe(re(s=>!!s),he()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Jn(document,"visibilitychange").pipe(he()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(re(t=>!!t),he()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Xn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),he()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",$t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",$t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Kl(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Dm(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Xl(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(No(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),he()).subscribe(()=>{this.initedAt=wa(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",$t(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:xa.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(he()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",$t(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(j(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(a=>a.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ut({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:a,currentVideoStream:u})=>a.filter(n=>u?u.id===n.streamId:!0).map(({quality:n})=>n).sort((n,l)=>ed(n)?1:ed(l)?-1:Vm(l,n)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let u={};for(let n of a)n.fps&&(u[n.quality]=n.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(W()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(re(a=>Xl(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(W((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(W((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(W()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(W()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(W()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(j(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Zn(a=>a&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(ut({hasLiveOffsetByPaused:At(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(a=>a.to),W(),j(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add(ut({atLiveEdge:ut({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Kn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:a,position:u,isLowLatency:n})=>{let l=this.getActiveLiveDelay(n);return a&&Math.abs(u)<l/1e3}),W(),Zn(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:a,hasPausedTimeoutCase:u})=>a&&!u)).subscribe(this.info.atLiveEdge$)).add(ut({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:a,position:u,duration:n})=>a&&(Math.abs(n)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),W(),Zn(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(a=>a.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(a=>a.volume),W()).subscribe(this.info.volume$)).add(Kn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(At(e.providerOutput.endedEvent$.pipe(Jl(!0)),e.providerOutput.seekedEvent$.pipe(Jl(!1))).pipe(W()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(j(a=>({id:a?`No${a}`:"NoProviders",category:xa.VIDEO_PIPELINE,message:a?`${a} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(he()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(he()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(he()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(he()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(he(),j(a=>a??wa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(he(),j(()=>wa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(he(),j(()=>wa()-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 $(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new $(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:a})=>a==="playing"),he()).subscribe(()=>i.next(!1)));let r=0,s=At(e.providerOutput.isBuffering$,t,i).pipe(j(()=>{let a=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return a&&!u}),W());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(At(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(At(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),n=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue(),d;h==="CONNECTED"?d="second_screen":n?l?a?d="pip":u?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(j(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Zl;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),he()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Ye(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(At(this.desiredState.videoTrack.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Xn(this.providerContainer),Xn(e),Oo(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Co(t)),this.providerContainer.current$.subscribe(({type:t})=>Vi("provider",t)),e.duration$.subscribe(t=>Vi("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),he()).subscribe(t=>Vi("tracks",t)),this.events.fatalError$.subscribe(new ge("fatalError")),this.events.managedError$.subscribe(new ge("managedError")),e.position$.subscribe(new ge("position")),e.currentVideoTrack$.pipe(j(t=>t?.quality)).subscribe(new ge("quality")),this.info.currentBuffer$.subscribe(new ge("buffer")),e.isBuffering$.subscribe(new ge("isBuffering"))].forEach(t=>this.subscription.add(t)),Vi("codecs",D.video.supportedCodecs)}initTracerSubscription(){let e=td(this.tracer.log.bind(this.tracer)),t=td(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(W()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ut({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(i=>i>0),W()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ut({currentBuffer:this.info.currentBuffer$.pipe(re(i=>i.end>0),W((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(W())}).pipe(eo(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(ut({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),eo(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),re(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),re(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),re(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ut({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:i,rtt:r})=>!!i&&!!r),eo(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),re(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:xa.DOM,message:String(r)})})};this.subscription.add(At(Jn(document,"visibilitychange"),Jn(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",$t({quality:t,availableTracks:$t(e),track:$t(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Hi()}};import{Subscription as ND,Observable as UD,Subject as HD,ValueSubject as jD,VideoQuality as QD}from"@vkontakte/videoplayer-shared/evergreen";var WD=`@vkontakte/videoplayer-core@${io}`;export{ns as ChromecastState,Pa as HttpConnectionType,UD as Observable,ye as PlaybackState,ka as Player,os as PredefinedQualityLimits,WD as SDK_VERSION,HD as Subject,ND as Subscription,La as Surface,io as VERSION,jD as ValueSubject,et as VideoFormat,QD as VideoQuality,Td as areValidLiveRecordSources,D as clientChecker,Li as isMobile};
|