@vkontakte/videoplayer-core 2.0.140-dev.4c27f703.0 → 2.0.140-dev.7b3cdcf7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/evergreen.esm.js CHANGED
@@ -1,126 +1,126 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.140-dev.4c27f703.0
3
- * Tue, 02 Sep 2025 09:42:02 GMT
2
+ * @vkontakte/videoplayer-core v2.0.140-dev.7b3cdcf7.0
3
+ * Tue, 09 Sep 2025 14:28:38 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-140/doc/
5
5
  */
6
- var io="2.0.140-dev.4c27f703.0";var Se=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Se||{}),et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_FMP4="HLS_FMP4",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(et||{});var Xr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Xr||{}),xa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(xa||{});var ka=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(ka||{}),Jr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Jr||{});import{assertNever as uo,assertNonNullable as al,isNonNullable as Zr,ValueSubject as Aa,Subject as nl,Subscription as ol,merge as ul,observableFrom as dl,fromEvent as so,map as ao,tap as no,filterChanged as ll,isNullable as wa,ErrorCategory as oo}from"@vkontakte/videoplayer-shared/evergreen";var ro=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var es=class{constructor(e){this.connection$=new Aa(void 0);this.castState$=new Aa("NOT_AVAILABLE");this.errorEvent$=new nl;this.realCastState$=new Aa("NOT_AVAILABLE");this.subscription=new ol;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=Zr(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(){Zr(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();wa(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();wa(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(ul(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)),dl([i.getCastState()])).pipe(ll(),ao(cl),no(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=Zr(this.connection$.getValue());if(s&&!a){let u=i.getCurrentSession();al(u);let o=u.getCastDevice(),d=u.getMediaSession()?.media?.contentId;(wa(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Zr(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})}}},cl=n=>{switch(n){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return uo(n)}};import{assertNever as lo}from"@vkontakte/videoplayer-shared/evergreen";var ee=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:lo(t)}return n},pt=(n,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(n);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(n);return Number(t.searchParams.get("offset_p")??0)}default:lo(e)}};var A=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as hl,Subject as ts,merge as co}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new ts;this.transitionEnded$=new ts;this.transitionUpdated$=new ts;this.forceChanged$=new ts;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||hl(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 is=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,o=/opr\//i.test(e)?"Opera":void 0,d=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||o||d||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 rs=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 ss=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var we=()=>window.ManagedMediaSource||window.MediaSource,Yt=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),ho=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),as=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var pl=document.createElement("video"),ml='video/mp4; codecs="avc1.42000a,mp4a.40.2"',fl='video/mp4; codecs="hev1.1.6.L93.B0"',po='video/webm; codecs="vp09.00.10.08"',mo='video/webm; codecs="av01.0.00M.08"',bl='audio/mp4; codecs="mp4a.40.2"',gl='audio/webm; codecs="opus"',fo,Sl=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:mo}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:po}})]);fo={DASH_WEBM_AV1:e,DASH_WEBM:t}};Sl().catch(n=>{console.log(pl),console.error(n)});var ns=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:Yt(),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=!!we()?.isTypeSupported?.(ml),t=!!we()?.isTypeSupported?.(fl),i=!!we()?.isTypeSupported?.(bl);this._codecs={h264:e,h265:t,vp9:!!we()?.isTypeSupported?.(po),av1:!!we()?.isTypeSupported?.(mo),aac:i,opus:!!we()?.isTypeSupported?.(gl),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",os=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:!!we()?.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 vl}from"@vkontakte/videoplayer-shared/evergreen";var Pa=class{constructor(){this.isInited$=new vl(!1);this._displayChecker=new ss,this._deviceChecker=new rs(this._displayChecker),this._browserChecker=new is,this._videoChecker=new ns(this._deviceChecker,this._browserChecker),this._audioChecker=new os,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 Pa;var La=n=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=D.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return n.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)}})},$a=n=>{switch(n){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_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(n)}},yl=n=>{let t=Object.keys(n).filter(i=>!$a(i));return La(t).length>0};import{assertNever as Kt,assertNonNullable as $t,debounce as So,ErrorCategory as vo,fromEvent as Mt,isNonNullable as yo,map as To,merge as Io,observableFrom as Tl,Subject as Il,Subscription as Ma,timeout as El,getHighestQuality as xl}from"@vkontakte/videoplayer-shared/evergreen";var kl=5,Al=5,wl=500,Eo=7e3,$i=class{constructor(e){this.subscription=new Ma;this.loadMediaTimeoutSubscription=new Ma;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Kt(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:Kt(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:Kt(e)}break}default:Kt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($a(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 Ma;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 Il;e.add(r.pipe(So(wl)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Mt(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)>kl)&&r.next(u),s=u})),e.add(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Mt(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(),o=a===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),a){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Al&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Kt(a)}}),t(Mt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Mt(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$,Tl(["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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];$t(d);let l=xl(Object.keys(d));$t(l);let p=d[l];$t(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let d=t[e];$t(d),i=d.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 d=t[e];$t(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];$t(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];$t(d),i=ee(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",l=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:vo.VIDEO_PIPELINE,message:d,thrown:l}),l}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Kt(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:o}=this.params.meta;return yo(u)&&(a.metadata.title=u),yo(o)&&(a.metadata.subtitle=o),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(El(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 ko}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Pl}from"@vkontakte/videoplayer-shared/evergreen";var xo=n=>{try{n.pause(),n.playbackRate=0,Pl(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as Ll,Subscription as $l}from"@vkontakte/videoplayer-shared/evergreen";var Ra=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)}},Da=window.WeakMap?new WeakMap:new Ra,Ba=window.WeakMap?new WeakMap:new Map,Ml=(n,e=20)=>{let t=0;return Ll(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},ve=(n,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=n.querySelector("video"),r=!!i;i?ko(i):(i=document.createElement("video"),n.appendChild(i)),Da.set(i,r);let s=new $l;return s.add(Ml(i,e)),Ba.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},ye=n=>{Ba.get(n)?.unsubscribe(),Ba.delete(n);let t=Da.get(n);Da.delete(n),t?ko(n):xo(n)};import{assertNonNullable as Ri,isNonNullable as We,isNullable as Bl,fromEvent as Xt,merge as Ao,observableFrom as wo,filterChanged as Po,map as Di,Subject as Lo,Subscription as Vl,ValueSubject as Cl,ErrorCategory as Ol}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Va,isNullable as Rl,Subscription as Dl}from"@vkontakte/videoplayer-shared/evergreen";var us=(n,e,t,{equal:i=(a,u)=>a===u,changed$:r,onError:s}={})=>{let a=n.getState(),u=e(),o=Rl(r),d=new Dl;return r&&d.add(r.subscribe(l=>{let p=n.getState();i(l,p)&&n.setState(l)},s)),i(u,a)||(t(a),o&&n.setState(a)),d.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),o&&n.setState(l.to)},s)),d},ze=(n,e,t)=>us(e,()=>n.loop,i=>{Va(i)&&(n.loop=i)},{onError:t}),Te=(n,e,t,i)=>us(e,()=>({muted:n.muted,volume:n.volume}),r=>{Va(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(n,e,t,i)=>us(e,()=>n.playbackRate,r=>{Va(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),Mi=us;var Fl=n=>["__",n.language,n.label].join("|"),_l=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},Ca=class n{constructor(e){this.available$=new Lo;this.current$=new Cl(void 0);this.error$=new Lo;this.subscription=new Vl;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:Ol.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=>{We(s)&&this.setInternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:u},o)=>u===a[o].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(Mi(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,a)=>We(s)&&We(a)&&s.length===a.length&&s.every(({id:u},o)=>u===a[o].id),changed$:this.available$.pipe(Di(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(){Ri(this.video);let{textTracks:e}=this.video;this.subscription.add(Xt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Ao(Xt(e,"addtrack"),Xt(e,"removetrack"),wo(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Po((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(Ao(Xt(e,"change"),wo(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Di(i=>i&&this.htmlTextTrackToITextTrack(i).id),Po()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Xt(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(Xt(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;We(t.align)&&(r.align=t.align),We(t.position)&&(r.position=t.position),We(t.size)&&(r.size=t.size),We(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ri(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:Fl(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){Ri(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Bl(e)||!_l(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){Ri(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){Ri(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=Ca;var Rt=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 $o=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Oa=n=>{let e=$o(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Mo=n=>{let e=$o(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as me,map as Ge,merge as ds,filterChanged as Do,isNonNullable as Bo,Subject as Ul,filter as Fa,mapTo as _a,combine as Hl,once as jl,shareReplay as fe,throttle as Ql,ErrorCategory as ql,ValueSubject as Vo,Subscription as zl}from"@vkontakte/videoplayer-shared/evergreen";var Nl=3,Ro=(n,e,t=Nl)=>{let i=0,r=0;for(let s=0;s<n.length;s++){let a=n.start(s),u=n.end(s);if(a<=e&&e<=u){if(i=a,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)n.end(o)+t>=i&&(i=n.start(o));for(let o=s+1;o<n.length;o++)n.start(o)-t<=r&&(r=n.end(o))}}return{from:i,to:r}};var Ie=n=>{let e=y=>me(n,y).pipe(_a(void 0),fe(1)),t=new zl,i=()=>t.unsubscribe(),r=ds(me(n,"progress"),me(n,"timeupdate")).pipe(Ge(()=>Ro(n.buffered,n.currentTime)),fe(1)),s=D.browser.isSafari?Hl({play:e("play").pipe(jl()),playing:e("playing")}).pipe(_a(void 0),fe(1)):e("playing"),a=me(n,"volumechange").pipe(Ge(()=>({muted:n.muted,volume:n.volume})),fe(1)),u=me(n,"ratechange").pipe(Ge(()=>n.playbackRate),fe(1)),o=me(n,"error").pipe(Fa(()=>!!(n.error||n.played.length)),Ge(()=>{let y=n.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:ql.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:n.error??void 0}}),fe(1)),d=me(n,"timeupdate").pipe(Ge(()=>n.currentTime),fe(1)),l=["waiting","seeking","seeked","timeupdate"],p=new Ul,c=.3,h;t.add(ds(...l.map(y=>me(n,y))).subscribe(y=>{let _=n.currentTime;n.loop&&Bo(h)&&Bo(_)&&h>=n.duration-c&&_<=c&&p.next(h),h=_}));let m=e("pause").pipe(Fa(()=>!n.error&&h!==n.duration),fe(1)),f=me(n,"enterpictureinpicture").pipe(fe(1)),b=me(n,"leavepictureinpicture").pipe(fe(1)),g=new Vo(Mo(n));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let E=new Vo(Oa(n)),I=me(n,"fullscreenchange").pipe(fe(1));t.add(I.pipe(Ge(()=>Oa(n))).subscribe(E));let v=.1,x=1e3,R=me(n,"timeupdate").pipe(Ge(y=>n.duration-n.currentTime<v),Do(),fe(1)),L=ds(R.pipe(Fa(y=>!n.loop&&y)),me(n,"ended")).pipe(Ql(x),_a(void 0),fe(1)),P=ds(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>me(n,y)),R.pipe(Ge(y=>({type:y?"ended":"unknown"})))).pipe(Ge(y=>D.browser.isFirefox&&y.type==="ended"?n.readyState<2:n.readyState<3),Do(),fe(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,looped$:p,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:me(n,"durationchange").pipe(Ge(()=>n.duration),fe(1)),isBuffering$:P,currentBuffer$:r,volumeState$:a,playbackRateState$:u,inPiP$:g,inFullscreen$:E,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as mt}from"@vkontakte/videoplayer-shared/evergreen";var ft=n=>{switch(n){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 G,isNullable as ms,now as qo,isHigher as fs,isHigherOrEqual as Zt,isInvariantQuality as bs,isLowerOrEqual as ei,videoSizeToQuality as zo,assertNotEmptyArray as gs,assertNonNullable as Wo}from"@vkontakte/videoplayer-shared/evergreen";var Na=!1,it={},Co=n=>{Na=n},Oo=()=>{it={}},Fo=n=>{n(it)},Bi=(n,e)=>{Na&&(it.meta=it.meta??{},it.meta[n]=e)},be=class{constructor(e){this.name=e}next(e){if(!Na)return;it.series=it.series??{};let t=it.series[this.name]??[];t.push([Date.now(),e]),it.series[this.name]=t}};import{isHigher as Wl,isHigherOrEqual as Fb,isLower as _o,isLowerOrEqual as _b,isNonNullable as ls,isNullable as Gl,videoHeightToQuality as cs}from"@vkontakte/videoplayer-shared/evergreen";function Ua(n,e,t){return!n.max&&n.min===e?"high_quality":!n.min&&n.max===t?"traffic_saving":"unknown"}function hs(n,e,t){return!!n&&Ua(n,e,t)==="high_quality"}function Jt(n,e,t){return Gl(n)||ls(n.min)&&ls(n.max)&&_o(n.max,n.min)||ls(n.min)&&e&&Wl(n.min,e)||ls(n.max)&&t&&_o(n.max,t)}function No({limits:n,highestAvailableHeight:e,lowestAvailableHeight:t}){return Jt({max:n?.max?cs(n.max):void 0,min:n?.min?cs(n.min):void 0},e?cs(e):void 0,t?cs(t):void 0)}var Go=new be("best_bitrate"),Ss=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t;var ti=n=>(e,t)=>n*(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={}}},vs='Assertion "ABR Tracks is empty array" failed',ps=new WeakMap,Uo=new WeakMap,Ho=new WeakMap,Vi=(n,e,t,i)=>{let r=[...e].sort(ti(1)),s=[...t].sort(ti(1)),a=s.filter(o=>G(o.bitrate)&&G(n.bitrate)?n.bitrate/o.bitrate>i:!0),u=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Ci=(n,e,t,i)=>{let r=ps.get(e);r||(r=[...e].sort(ti(1)),ps.set(e,r));let s=ps.get(t);s||(s=[...t].sort(ti(1)),ps.set(t,s));let a=Ho.get(n);a||(a=s.filter(o=>G(o.bitrate)&&G(n.bitrate)?n.bitrate/o.bitrate>i:!0),Ho.set(n,a));let u=s.at(Math.round(s.length*r.indexOf(n)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},jo=n=>"quality"in n,ys=(n,e,t,i)=>{let r=G(i?.last?.bitrate)&&G(t?.bitrate)&&i.last.bitrate<t.bitrate?n.trackCooldownIncreaseQuality:n.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=jo(a)?"video":"audio",o=jo(a)?a.quality:a.bitrate;return e({message:`
7
- [last ${u} selected] ${o}
8
- `}),a}return i?.recordSwitch(t),t},Yl=(n,e)=>Math.log(e)/Math.log(n),Yo=({tuning:n,container:e,limits:t,panelSize:i})=>{let r=n.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(n.usePixelRatio&&D.display.pixelRatio){let s=D.display.pixelRatio;if(n.pixelRatioMultiplier)r*=n.pixelRatioMultiplier*(s-1)+1;else{let a=n.pixelRatioLogBase,[u=0,o=0,d=0]=n.pixelRatioLogCoefficients,l=Yl(a,u*s+o)+d;Number.isFinite(l)&&(r*=l)}}return hs(t,n.highQualityLimit,n.trafficSavingLimit)&&(r*=2),{containerSizeLimit:n.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Qo=new WeakMap,Ye=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:o,history:d,visible:l,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{gs(n,vs);let{containerSizeFactor:b,containerSizeLimit:g}=Yo({container:e,tuning:i,limits:r,panelSize:f}),E=i.considerPlaybackRate&&G(u)?u:1,I=Qo.get(n);I||(I=n.filter(S=>!bs(S.quality)).sort((S,T)=>fs(S.quality,T.quality)?-1:1),Qo.set(n,I));let v=I.at(-1)?.quality,x=I.at(0)?.quality,R=Jt(r,x,v),L=E*Ss(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},P=null;for(let S of I){let T=!0;if(g)if(S.size)T=S.size.width<=g.width&&S.size.height<=g.height;else{let H=g&&zo(g);T=H?ei(S.quality,H):!0}if(!T){k[S.quality]="FitsContainer";continue}let z=h||t,M=G(z)&&isFinite(z)&&G(S.bitrate)?z-s>=S.bitrate*L:!0,U=hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===S.quality;if(!M&&!U){k[S.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&G(i.minBufferToSwitchUp)&&o&&!bs(o.quality)&&(a??0)<i.minBufferToSwitchUp&&fs(S.quality,o.quality)){k[S.quality]="Buffer";continue}if(!!p&&Zt(S.quality,p)&&!U){k[S.quality]="DroppedFramesLimit";continue}if(!!c&&Zt(S.quality,c)&&!U){k[S.quality]="StallsLimit";continue}let ne=R||(ms(r?.max)||ei(S.quality,r.max))&&(ms(r?.min)||Zt(S.quality,r.min)),oe=G(l)&&!l?ei(S.quality,i.backgroundVideoQualityLimit):!0;if(!ne||!oe){k[S.quality]="FitsQualityLimits";continue}P||(P=S)}P&&P.bitrate&&Go.next(P.bitrate);let y=P??I.at(-1)??n[0],_=d?.last,$=ys(i,m,y,d);return G(d)&&$.quality!==_?.quality&&m({message:`
6
+ var so="2.0.140-dev.7b3cdcf7.0";var Te=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Te||{}),et=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_FMP4="HLS_FMP4",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(et||{});var ns=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ns||{}),La=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(La||{});var Ra=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(Ra||{}),os=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(os||{});import{assertNever as co,assertNonNullable as ol,isNonNullable as us,ValueSubject as Ma,Subject as ul,Subscription as dl,merge as ll,observableFrom as cl,fromEvent as no,map as oo,tap as uo,filterChanged as hl,isNullable as Da,ErrorCategory as lo}from"@vkontakte/videoplayer-shared/evergreen";var ao=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 ds=class{constructor(e){this.connection$=new Ma(void 0);this.castState$=new Ma("NOT_AVAILABLE");this.errorEvent$=new ul;this.realCastState$=new Ma("NOT_AVAILABLE");this.subscription=new dl;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||ao("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:lo.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();Da(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Da(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(no(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 co(r.sessionState)}})).add(ll(no(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(uo(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),oo(r=>r.castState)),cl([i.getCastState()])).pipe(hl(),oo(pl),uo(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();ol(u);let n=u.getCastDevice(),d=u.getMediaSession()?.media?.contentId;(Da(d)||d===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:lo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},pl=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 co(o)}};import{assertNever as ho}from"@vkontakte/videoplayer-shared/evergreen";var ee=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:ho(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:ho(e)}};var w=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as ml,Subject as ls,merge as po}from"@vkontakte/videoplayer-shared/evergreen";var O=class{constructor(e){this.transitionStarted$=new ls;this.transitionEnded$=new ls;this.transitionUpdated$=new ls;this.forceChanged$=new ls;this.stateChangeStarted$=po(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=po(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||ml(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 vo}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,d=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||n||d||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),mo=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ms=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var fl=document.createElement("video"),bl='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gl='video/mp4; codecs="hev1.1.6.L93.B0"',fo='video/webm; codecs="vp09.00.10.08"',bo='video/webm; codecs="av01.0.00M.08"',Sl='audio/mp4; codecs="mp4a.40.2"',vl='audio/webm; codecs="opus"',go,yl=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:bo}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:fo}})]);go={DASH_WEBM_AV1:e,DASH_WEBM:t}};yl().catch(o=>{console.log(fl),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 go}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:mo(),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?.(bl),t=!!Ae()?.isTypeSupported?.(gl),i=!!Ae()?.isTypeSupported?.(Sl);this._codecs={h264:e,h265:t,vp9:!!Ae()?.isTypeSupported?.(fo),av1:!!Ae()?.isTypeSupported?.(bo),aac:i,opus:!!Ae()?.isTypeSupported?.(vl),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 So="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?.(So)},this._codecs={mp3:!!Ae()?.isTypeSupported?.(So)}}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 Tl}from"@vkontakte/videoplayer-shared/evergreen";var Ba=class{constructor(){this.isInited$=new Tl(!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 Ba;var Va=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 vo(u)}})},Ca=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 vo(o)}},Il=o=>{let t=Object.keys(o).filter(i=>!Ca(i));return Va(t).length>0};import{assertNever as Zt,assertNonNullable as Mt,debounce as yo,ErrorCategory as To,fromEvent as Dt,isNonNullable as Io,map as Eo,merge as xo,observableFrom as El,Subject as xl,Subscription as Oa,timeout as kl,getHighestQuality as wl}from"@vkontakte/videoplayer-shared/evergreen";var Al=5,$l=5,Pl=500,ko=7e3,Ri=class{constructor(e){this.subscription=new Oa;this.loadMediaTimeoutSubscription=new Oa;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default: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(Ca(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 Oa;this.subscription.add(e),this.subscription.add(xo(this.videoState.stateChangeStarted$.pipe(Eo(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Eo(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 xl;e.add(r.pipe(yo(Pl)).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)>Al)&&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<$l&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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=xo(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,El(["init"])).pipe(yo(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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(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"),w(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&w(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 d=t[e];Mt(d);let h=wl(Object.keys(d));Mt(h);let c=d[h];Mt(c),i=c,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let d=t[e];Mt(d),i=d.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 d=t[e];Mt(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];Mt(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];Mt(d),i=ee(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:To.VIDEO_PIPELINE,message:d,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 Io(u)&&(a.metadata.title=u),Io(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(kl(ko).subscribe(()=>s(`timeout(${ko})`)))});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:To.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Ao}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Ll}from"@vkontakte/videoplayer-shared/evergreen";var wo=o=>{try{o.pause(),o.playbackRate=0,Ll(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as Rl,Subscription as Ml}from"@vkontakte/videoplayer-shared/evergreen";var Fa=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)}},_a=window.WeakMap?new WeakMap:new Fa,Na=window.WeakMap?new WeakMap:new Map,Dl=(o,e=20)=>{let t=0;return Rl(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},Ie=(o,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=o.querySelector("video"),r=!!i;i?Ao(i):(i=document.createElement("video"),o.appendChild(i)),_a.set(i,r);let s=new Ml;return s.add(Dl(i,e)),Na.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},Ee=o=>{Na.get(o)?.unsubscribe(),Na.delete(o);let t=_a.get(o);_a.delete(o),t?Ao(o):wo(o)};import{assertNonNullable as Di,isNonNullable as ze,isNullable as Cl,fromEvent as ei,merge as $o,observableFrom as Po,filterChanged as Lo,map as Bi,Subject as Ro,Subscription as Ol,ValueSubject as Fl,ErrorCategory as _l}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Ua,isNullable as Bl,Subscription as Vl}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=Bl(r),d=new Vl;return r&&d.add(r.subscribe(h=>{let c=o.getState();i(h,c)&&o.setState(h)},s)),i(u,a)||(t(a),n&&o.setState(a)),d.add(o.stateChangeStarted$.subscribe(h=>{t(h.to),n&&o.setState(h.to)},s)),d},We=(o,e,t)=>gs(e,()=>o.loop,i=>{Ua(i)&&(o.loop=i)},{onError:t}),me=(o,e,t,i)=>gs(e,()=>({muted:o.muted,volume:o.volume}),r=>{Ua(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=>{Ua(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Mi=gs;var Nl=o=>["__",o.language,o.label].join("|"),Ul=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},Ha=class o{constructor(e){this.available$=new Ro;this.current$=new Fl(void 0);this.error$=new Ro;this.subscription=new Ol;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:_l.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($o(ei(e,"addtrack"),ei(e,"removetrack"),Po(["init"])).pipe(Bi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Lo((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add($o(ei(e,"change"),Po(["init"])).pipe(Bi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Bi(i=>i&&this.htmlTextTrackToITextTrack(i).id),Lo()).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:Nl(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))(Cl(e)||!Ul(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=Ha;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 Mo=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},ja=o=>{let e=Mo(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},Do=o=>{let e=Mo(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as fe,map as Ge,merge as Ss,filterChanged as Vo,isNonNullable as Co,Subject as jl,filter as Qa,mapTo as qa,combine as Ql,once as ql,shareReplay as be,throttle as Wl,ErrorCategory as zl,ValueSubject as Oo,Subscription as Gl}from"@vkontakte/videoplayer-shared/evergreen";var Hl=3,Bo=(o,e,t=Hl)=>{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 Gl,i=()=>t.unsubscribe(),r=Ss(fe(o,"progress"),fe(o,"timeupdate")).pipe(Ge(()=>Bo(o.buffered,o.currentTime)),be(1)),s=D.browser.isSafari?Ql({play:e("play").pipe(ql()),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(Qa(()=>!!(o.error||o.played.length)),Ge(()=>{let E=o.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:zl.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:o.error??void 0}}),be(1)),d=fe(o,"timeupdate").pipe(Ge(()=>o.currentTime),be(1)),h=["waiting","seeking","seeked","timeupdate"],c=new jl,l=.3,p;t.add(Ss(...h.map(E=>fe(o,E))).subscribe(E=>{let _=o.currentTime;o.loop&&Co(p)&&Co(_)&&p>=o.duration-l&&_<=l&&c.next(p),p=_}));let m=e("pause").pipe(Qa(()=>!o.error&&p!==o.duration),be(1)),f=fe(o,"enterpictureinpicture").pipe(be(1)),b=fe(o,"leavepictureinpicture").pipe(be(1)),g=new Oo(Do(o));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let y=new Oo(ja(o)),T=fe(o,"fullscreenchange").pipe(be(1));t.add(T.pipe(Ge(()=>ja(o))).subscribe(y));let v=.1,k=1e3,$=fe(o,"timeupdate").pipe(Ge(E=>o.duration-o.currentTime<v),Vo(),be(1)),P=Ss($.pipe(Qa(E=>!o.loop&&E)),fe(o,"ended")).pipe(Wl(k),qa(void 0),be(1)),M=Ss(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>fe(o,E)),$.pipe(Ge(E=>({type:E?"ended":"unknown"})))).pipe(Ge(E=>D.browser.isFirefox&&E.type==="ended"?o.readyState<2:o.readyState<3),Vo(),be(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:P,looped$:c,error$:n,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:fe(o,"durationchange").pipe(Ge(()=>o.duration),be(1)),isBuffering$:M,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 G,isNullable as Is,now as Go,isHigher as Es,isHigherOrEqual as Vt,isInvariantQuality as xs,isLowerOrEqual as ii,videoSizeToQuality as Yo,assertNotEmptyArray as ks,assertNonNullable as Ko}from"@vkontakte/videoplayer-shared/evergreen";var Wa=!1,it={},Fo=o=>{Wa=o},_o=()=>{it={}},No=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 Yl,isHigherOrEqual as Wb,isLower as Uo,isLowerOrEqual as zb,isNonNullable as vs,isNullable as Kl,videoHeightToQuality as ys}from"@vkontakte/videoplayer-shared/evergreen";function Ho(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 Kl(o)||vs(o.min)&&vs(o.max)&&Uo(o.max,o.min)||vs(o.min)&&e&&Yl(o.min,e)||vs(o.max)&&t&&Uo(o.max,t)}function jo({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 Xo=new ge("best_bitrate"),ws=(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]=Go()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},As='Assertion "ABR Tracks is empty array" failed',Ts=new WeakMap,Qo=new WeakMap,qo=new WeakMap,Ci=(o,e,t,i)=>{let r=[...e].sort(ri(1)),s=[...t].sort(ri(1)),a=s.filter(n=>G(n.bitrate)&&G(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=qo.get(o);a||(a=s.filter(n=>G(n.bitrate)&&G(o.bitrate)?o.bitrate/n.bitrate>i:!0),qo.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)},Wo=o=>"quality"in o,$s=(o,e,t,i)=>{let r=G(i?.last?.bitrate)&&G(t?.bitrate)&&i.last.bitrate<t.bitrate?o.trackCooldownIncreaseQuality:o.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Go()-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=Wo(a)?"video":"audio",n=Wo(a)?a.quality:a.bitrate;return e({message:`
7
+ [last ${u} selected] ${n}
8
+ `}),a}return i?.recordSwitch(t),t},Xl=(o,e)=>Math.log(e)/Math.log(o),Jo=({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,d=0]=o.pixelRatioLogCoefficients,h=Xl(a,u*s+n)+d;Number.isFinite(h)&&(r*=h)}}return G(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}},zo=new WeakMap,Ye=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:n,history:d,visible:h,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:l,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{ks(o,As);let{containerSizeFactor:b,containerSizeLimit:g}=Jo({container:e,tuning:i,limits:r,panelSize:f}),y=i.considerPlaybackRate&&G(u)?u:1,T=zo.get(o);T||(T=o.filter(S=>!xs(S.quality)).sort((S,I)=>Es(S.quality,I.quality)?-1:1),zo.set(o,T));let v=T.at(-1)?.quality,k=T.at(0)?.quality,$=ti(r,k,v),P=y*ws(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},M=null;for(let S of T){let I=!0;if(g)if(S.size)I=S.size.width<=g.width&&S.size.height<=g.height;else{let H=g&&Yo(g);I=H?ii(S.quality,H):!0}if(!I){x[S.quality]="FitsContainer";continue}let W=p||t,R=G(W)&&isFinite(W)&&G(S.bitrate)?W-s>=S.bitrate*P:!0,U=r?.min===S.quality;if(!R&&!U){x[S.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&G(i.minBufferToSwitchUp)&&n&&!xs(n.quality)&&(a??0)<i.minBufferToSwitchUp&&Es(S.quality,n.quality)){x[S.quality]="Buffer";continue}if(!!c&&Vt(S.quality,c)&&!U){x[S.quality]="DroppedFramesLimit";continue}if(!!l&&Vt(S.quality,l)&&!U){x[S.quality]="StallsLimit";continue}let oe=$||(Is(r?.max)||ii(S.quality,r.max))&&(Is(r?.min)||Vt(S.quality,r.min)),ue=G(h)&&!h?ii(S.quality,i.backgroundVideoQualityLimit):!0;if(!oe||!ue){x[S.quality]="FitsQualityLimits";continue}M||(M=S)}M&&M.bitrate&&Xo.next(M.bitrate);let E=M??T.at(-1)??o[0],_=d?.last,L=$s(i,m,E,d);return G(d)&&L.quality!==_?.quality&&m({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
- ${n.map(S=>`{ id: ${S.id}, quality: ${S.quality}, bitrate: ${S.bitrate}, size: ${S.size?.width}:${S.size?.height} }`).join(`
11
+ ${o.map(S=>`{ id: ${S.id}, quality: ${S.quality}, bitrate: ${S.bitrate}, size: ${S.size?.width}:${S.size?.height} }`).join(`
12
12
  `)}
13
13
 
14
14
  [tuning]
15
- ${Object.entries(i??{}).map(([S,T])=>`${S}: ${T}`).join(`
15
+ ${Object.entries(i??{}).map(([S,I])=>`${S}: ${I}`).join(`
16
16
  `)}
17
17
 
18
18
  [limit params]
19
19
  containerSizeFactor: ${b},
20
20
  containerSizeLimit: ${g?.width??0} x ${g?.height??0},
21
21
  estimatedThroughput: ${t},
22
- stallsPredictedThroughput: ${h},
22
+ stallsPredictedThroughput: ${p},
23
23
  reserve: ${s},
24
24
  playbackRate: ${u},
25
- playbackRateFactor: ${E},
25
+ playbackRateFactor: ${y},
26
26
  forwardBufferHealth: ${a},
27
- bitrateFactor: ${L},
27
+ bitrateFactor: ${P},
28
28
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
29
- droppedVideoMaxQualityLimit: ${p},
30
- stallsVideoMaxQualityLimit: ${c},
31
- limitsAreInvalid: ${R},
29
+ droppedVideoMaxQualityLimit: ${c},
30
+ stallsVideoMaxQualityLimit: ${l},
31
+ limitsAreInvalid: ${$},
32
32
  maxQualityLimit: ${r?.max},
33
33
  minQualityLimit: ${r?.min},
34
34
 
35
35
  [limited video tracks]
36
- ${Object.entries(k).map(([S,T])=>`${S}: ${T}`).join(`
36
+ ${Object.entries(x).map(([S,I])=>`${S}: ${I}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
- [best video track] ${P?.quality}
40
- [selected video track] ${$?.quality}
41
- `}),$},Ts=(n,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:o,history:d,visible:l,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:h,abrLogger:m,panelSize:f})=>{gs(n,vs);let{containerSizeFactor:b,containerSizeLimit:g}=Yo({container:e,tuning:i,limits:r,panelSize:f}),E=i.considerPlaybackRate&&G(u)?u:1,I=n.filter(T=>!bs(T.quality)).sort((T,z)=>fs(T.quality,z.quality)?-1:1),v=I.at(-1)?.quality,x=I.at(0)?.quality,R=Jt(r,x,v),L=E*Ss(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),k={},y=I.filter(T=>{let z=!0;if(g)if(T.size)z=T.size.width<=g.width&&T.size.height<=g.height;else{let N=g&&zo(g);z=N?ei(T.quality,N):!0}if(!z)return k[T.quality]="FitsContainer",!1;let M=h||t,U=G(M)&&isFinite(M)&&G(T.bitrate)?M-s>=T.bitrate*L:!0,Y=hs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===T.quality;if(!U&&!Y)return k[T.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&G(i.minBufferToSwitchUp)&&o&&!bs(o.quality)&&(a??0)<i.minBufferToSwitchUp&&fs(T.quality,o.quality))return k[T.quality]="Buffer",!1;if(!!p&&Zt(T.quality,p)&&!Y)return k[T.quality]="DroppedFramesLimit",!1;if(!!c&&Zt(T.quality,c)&&!Y)return k[T.quality]="StallsLimit",!1;let oe=R||(ms(r?.max)||ei(T.quality,r.max))&&(ms(r?.min)||Zt(T.quality,r.min)),H=G(l)&&!l?ei(T.quality,i.backgroundVideoQualityLimit):!0;return!oe||!H?(k[T.quality]="FitsQualityLimits",!1):!0})[0];y&&y.bitrate&&Go.next(y.bitrate);let _=y??I.at(-1)??n[0],$=d?.last,S=ys(i,m,_,d);return G(d)&&S.quality!==$?.quality&&m({message:`
39
+ [best video track] ${M?.quality}
40
+ [selected video track] ${L?.quality}
41
+ `}),L},Ps=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:n,history:d,visible:h,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:l,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{ks(o,As);let{containerSizeFactor:b,containerSizeLimit:g}=Jo({container:e,tuning:i,limits:r,panelSize:f}),y=i.considerPlaybackRate&&G(u)?u:1,T=o.filter(I=>!xs(I.quality)).sort((I,W)=>Es(I.quality,W.quality)?-1:1),v=T.at(-1)?.quality,k=T.at(0)?.quality,$=ti(r,k,v),P=y*ws(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},E=T.filter(I=>{let W=!0;if(g)if(I.size)W=I.size.width<=g.width&&I.size.height<=g.height;else{let N=g&&Yo(g);W=N?ii(I.quality,N):!0}if(!W)return x[I.quality]="FitsContainer",!1;let R=p||t,U=G(R)&&isFinite(R)&&G(I.bitrate)?R-s>=I.bitrate*P:!0,Y=r?.min===I.quality;if(!U&&!Y)return x[I.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&G(i.minBufferToSwitchUp)&&n&&!xs(n.quality)&&(a??0)<i.minBufferToSwitchUp&&Es(I.quality,n.quality))return x[I.quality]="Buffer",!1;if(!!c&&Vt(I.quality,c)&&!Y)return x[I.quality]="DroppedFramesLimit",!1;if(!!l&&Vt(I.quality,l)&&!Y)return x[I.quality]="StallsLimit",!1;let ue=$||(Is(r?.max)||ii(I.quality,r.max))&&(Is(r?.min)||Vt(I.quality,r.min)),H=G(h)&&!h?ii(I.quality,i.backgroundVideoQualityLimit):!0;return!ue||!H?(x[I.quality]="FitsQualityLimits",!1):!0})[0];E&&E.bitrate&&Xo.next(E.bitrate);let _=E??T.at(-1)??o[0],L=d?.last,S=$s(i,m,_,d);return G(d)&&S.quality!==L?.quality&&m({message:`
42
42
  [VIDEO TRACKS ABR]
43
43
  [available video tracks]
44
- ${n.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
44
+ ${o.map(I=>`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate}, size: ${I.size?.width}:${I.size?.height} }`).join(`
45
45
  `)}
46
46
 
47
47
  [tuning]
48
- ${Object.entries(i??{}).map(([T,z])=>`${T}: ${z}`).join(`
48
+ ${Object.entries(i??{}).map(([I,W])=>`${I}: ${W}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
52
52
  containerSizeFactor: ${b},
53
53
  containerSizeLimit: ${g?.width??0} x ${g?.height??0},
54
54
  estimatedThroughput: ${t},
55
- stallsPredictedThroughput: ${h},
55
+ stallsPredictedThroughput: ${p},
56
56
  reserve: ${s},
57
57
  playbackRate: ${u},
58
- playbackRateFactor: ${E},
58
+ playbackRateFactor: ${y},
59
59
  forwardBufferHealth: ${a},
60
- bitrateFactor: ${L},
60
+ bitrateFactor: ${P},
61
61
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
62
- droppedVideoMaxQualityLimit: ${p},
63
- stallsVideoMaxQualityLimit: ${c},
64
- limitsAreInvalid: ${R},
62
+ droppedVideoMaxQualityLimit: ${c},
63
+ stallsVideoMaxQualityLimit: ${l},
64
+ limitsAreInvalid: ${$},
65
65
  maxQualityLimit: ${r?.max},
66
66
  minQualityLimit: ${r?.min},
67
67
 
68
68
  [limited video tracks]
69
- ${Object.entries(k).map(([T,z])=>`${T}: ${z}`).join(`
69
+ ${Object.entries(x).map(([I,W])=>`${I}: ${W}`).join(`
70
70
  `)||"All tracks are available"}
71
71
 
72
- [best video track] ${y?.quality}
72
+ [best video track] ${E?.quality}
73
73
  [selected video track] ${S?.quality}
74
- `}),S},Is=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:o,stallsPredictedThroughput:d})=>{gs(t,vs);let l=r.considerPlaybackRate&&G(s)?s:1,p=[...t].sort(ti(-1)),c=n.bitrate;Wo(c);let h=l*Ss(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Vi(n,e,t,r.minVideoAudioRatio),b=d||i;G(b)&&isFinite(b)&&(m=p.find(I=>G(I.bitrate)&&G(f?.bitrate)?b-c>=I.bitrate*h&&I.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,E=m&&ys(r,o,m,u);return G(u)&&E?.bitrate!==g?.bitrate&&o({message:`
74
+ `}),S},Ls=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:n,stallsPredictedThroughput:d})=>{ks(t,As);let h=r.considerPlaybackRate&&G(s)?s:1,c=[...t].sort(ri(-1)),l=o.bitrate;Ko(l);let p=h*ws(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Ci(o,e,t,r.minVideoAudioRatio),b=d||i;G(b)&&isFinite(b)&&(m=c.find(T=>G(T.bitrate)&&G(f?.bitrate)?b-l>=T.bitrate*p&&T.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,y=m&&$s(r,n,m,u);return G(u)&&y?.bitrate!==g?.bitrate&&n({message:`
75
75
  [AUDIO TRACKS ABR]
76
76
  [available audio tracks]
77
- ${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
77
+ ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
78
78
  `)}
79
79
 
80
80
  [tuning]
81
- ${Object.entries(r??{}).map(([I,v])=>`${I}: ${v}`).join(`
81
+ ${Object.entries(r??{}).map(([T,v])=>`${T}: ${v}`).join(`
82
82
  `)}
83
83
 
84
84
  [limit params]
85
85
  estimatedThroughput: ${i},
86
86
  stallsPredictedThroughput: ${d},
87
- reserve: ${c},
87
+ reserve: ${l},
88
88
  playbackRate: ${s},
89
- playbackRateFactor: ${l},
89
+ playbackRateFactor: ${h},
90
90
  forwardBufferHealth: ${a},
91
- bitrateFactor: ${h},
91
+ bitrateFactor: ${p},
92
92
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
93
93
 
94
- [selected audio track] ${E?.id}
95
- `}),E},Es=(n,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:o,stallsPredictedThroughput:d})=>{gs(t,vs);let l=r.considerPlaybackRate&&G(s)?s:1,p=Uo.get(t);p||(p=[...t].sort(ti(-1)),Uo.set(t,p));let c=n.bitrate;Wo(c);let h=l*Ss(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Ci(n,e,t,r.minVideoAudioRatio),b=d||i;G(b)&&isFinite(b)&&(m=p.find(I=>G(I.bitrate)&&G(f?.bitrate)?b-c>=I.bitrate*h&&I.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,E=m&&ys(r,o,m,u);return G(u)&&E?.bitrate!==g?.bitrate&&o({message:`
94
+ [selected audio track] ${y?.id}
95
+ `}),y},Rs=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:n,stallsPredictedThroughput:d})=>{ks(t,As);let h=r.considerPlaybackRate&&G(s)?s:1,c=Qo.get(t);c||(c=[...t].sort(ri(-1)),Qo.set(t,c));let l=o.bitrate;Ko(l);let p=h*ws(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Oi(o,e,t,r.minVideoAudioRatio),b=d||i;G(b)&&isFinite(b)&&(m=c.find(T=>G(T.bitrate)&&G(f?.bitrate)?b-l>=T.bitrate*p&&T.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,y=m&&$s(r,n,m,u);return G(u)&&y?.bitrate!==g?.bitrate&&n({message:`
96
96
  [AUDIO TRACKS ABR]
97
97
  [available audio tracks]
98
- ${t.map(I=>`{ id: ${I.id}, bitrate: ${I.bitrate} }`).join(`
98
+ ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
99
99
  `)}
100
100
 
101
101
  [tuning]
102
- ${Object.entries(r??{}).map(([I,v])=>`${I}: ${v}`).join(`
102
+ ${Object.entries(r??{}).map(([T,v])=>`${T}: ${v}`).join(`
103
103
  `)}
104
104
 
105
105
  [limit params]
106
106
  estimatedThroughput: ${i},
107
107
  stallsPredictedThroughput: ${d},
108
- reserve: ${c},
108
+ reserve: ${l},
109
109
  playbackRate: ${s},
110
- playbackRateFactor: ${l},
110
+ playbackRateFactor: ${h},
111
111
  forwardBufferHealth: ${a},
112
- bitrateFactor: ${h},
112
+ bitrateFactor: ${p},
113
113
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
114
114
 
115
- [selected audio track] ${E?.id}
116
- `}),E};var ue=n=>new URL(n).hostname;import{assertNever as tu,assertNonNullable as iu,combine as bc,debounce as gc,ErrorCategory as ru,filter as su,filterChanged as Sc,isNonNullable as za,map as ws,merge as au,observableFrom as vc,once as yc,Subscription as Tc,ValueSubject as Wa,videoQualityToHeight as nu,videoSizeToQuality as Ic}from"@vkontakte/videoplayer-shared/evergreen";var Ko=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},Ee=async(n,e)=>{let t=n.muted;try{await n.play()}catch(i){if(!Ko(i))return!1;if(e&&e(),t)return console.warn(i),!1;n.muted=!0;try{await n.play()}catch(r){return Ko(r)&&(n.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as ks,isNullable as Jl,assertNonNullable as _i}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Xo,assertNonNullable as xs,now as Kl}from"@vkontakte/videoplayer-shared/evergreen";function se(){return Kl()}function Ha(n){return se()-n}function ja(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,u,o=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let d=a.indexOf("?")>-1?"&":"?";return o&&(a+=d+"lowLat=1",d="&"),u&&(a+=d+"_rnd="+Math.floor(999999999*Math.random())),a}}}function Jo(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function ii(n,e,t,i){let r=window.XMLHttpRequest,s,a,u,o=!1,d=0,l,p,c=!1,h="arraybuffer",m=7e3,f=2e3,b=()=>{if(o)return;xs(l);let $=Ha(l),S;if($<f){S=f-$,setTimeout(b,S);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,R()},g=$=>(s=$,_),E=$=>(p=$,_),I=()=>(h="json",_),v=()=>{if(!o){if(--d>=0){b(),i&&i();return}o=!0,p&&p(),t&&t()}},x=$=>(c=$,_),R=()=>{l=se(),a=new r,a.open("get",n);let $=0,S,T=0,z=()=>(xs(l),Math.max(l,Math.max(S||0,T||0)));if(s&&a.addEventListener("progress",M=>{let U=se();s.updateChunk&&M.loaded>$&&(s.updateChunk(z(),M.loaded-$),$=M.loaded,S=U)}),u&&(a.timeout=u,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(o)return;xs(a);let M=a.status;if(M>=200&&M<300){let{response:U,responseType:Y}=a,Z=U?.byteLength;if(typeof Z=="number"&&s){let ie=Z-$;ie&&s.updateChunk&&s.updateChunk(z(),ie)}Y==="json"&&(!U||!Object.values(U).length)?v():(p&&p(),e(U))}else v()}),a.addEventListener("error",()=>{v()}),c){let M=()=>{xs(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(T=se(),a.removeEventListener("readystatechange",M))};a.addEventListener("readystatechange",M)}return a.responseType=h,a.send(),_},_={withBitrateReporting:g,withParallel:x,withJSONResponse:I,withRetryCount:$=>(d=$,_),withRetryInterval:($,S)=>(Xo($)&&(f=$),Xo(S)&&(m=S),_),withTimeout:$=>(u=$,_),withFinally:E,send:R,abort:()=>{a&&(a.abort(),a=void 0),o=!0,p&&p()}};return _}var Oi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,u=s.end-s.start;i+=a;let o=s.bytes*a/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Fi=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=se(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=se()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ii(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=se()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=se();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as Zl}from"@vkontakte/videoplayer-shared/evergreen";var As=1e4,Qa=3;var ec=6e4,tc=10,ic=1,rc=500,Ni=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Zl,this.chunkRateEstimator=new Oi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ja(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ja(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*(D.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:d}=this.autoQualityLimits||{};!No({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(o&&s.video.height>o||d&&s.video.height<d)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ks(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{Jo(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Fi(Qa,As,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,u=null,o=null,d=null,l=!1,p=()=>{let v=s&&(!l||l===this.rep);return v||t("Not running!"),v},c=(v,x,R)=>{o&&o.abort(),o=ii(this.urlResolver.resolve(v,!1),x,R,()=>this._retryCallback()).withTimeout(As).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qa).withFinally(()=>{o=null}).send()},h=(v,x,R)=>{_i(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),x,R,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=v=>{let x=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${x}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let R=se()-1e4,L=0;for(let P=0;P<this.bufferStates.length;P++){let y=this.bufferStates[P];v=Math.min(v,y.buf),y.ts<R&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${v} drop=${L} jitter=${this.sourceJitter}`);let k=v-ic;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?m(1.15):k>1?m(1.1):k>.3?m(1.05):m(1)}},g=v=>{let x,R=()=>x&&x.start?x.start.length:0,L=M=>x.start[M]/1e3,k=M=>x.dur[M]/1e3,P=M=>x.fragIndex+M,y=(M,U)=>({chunkIdx:P(M),startTS:L(M),dur:k(M),discontinuity:U}),_=()=>{let M=0;if(x&&x.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=U;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ie=x.dur.length-1;for(;ie>=0&&(Z-=x.dur[ie],!(Z<=0));--ie);M=Math.min(ie,x.dur.length-1-Y),M=Math.max(M,0)}return y(M,!0)},$=M=>{let U=R();if(!(U<=0)){if(ks(M)){for(let Y=0;Y<U;Y++)if(L(Y)>M)return y(Y)}return _()}},S=M=>{let U=R(),Y=M?M.chunkIdx+1:0,Z=Y-x.fragIndex;if(!(U<=0)){if(!M||Z<0||Z-U>tc)return t(`Resync: offset=${Z} bChunks=${U} chunk=`+JSON.stringify(M)),_();if(!(Z>=U))return y(Y-x.fragIndex,!1)}},T=(M,U,Y)=>{d&&d.abort(),d=ii(this.urlResolver.resolve(M,!0,this.lowLatency),U,Y,()=>this._retryCallback()).withTimeout(As).withRetryCount(Qa).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(M,U)=>{T(v,Y=>{if(!p())return;x=Y;let Z=!!x.lowLatency;Z!==this.lowLatency&&f(Z);let ie=0;for(let ne=0;ne<x.dur.length;++ne)ie+=x.dur[ne];ie>0&&(_i(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/x.dur.length)),r({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,M($(U))},()=>this._handleNetworkError())},nextChunk:S}},E=()=>{s=!1,u&&u.abort(),o&&o.abort(),d&&d.abort(),_i(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:v=>{let{videoElement:x,logger:R}=this.params,L=g(e.jidxUrl),k,P,y,_,$=0,S,T,z,M=()=>{S&&(clearTimeout(S),S=void 0);let N=Math.max(rc,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=$+N,he=se(),re=Math.min(1e4,ge-he);$=he;let Me=()=>{d||p()&&L.seek(()=>{p()&&($=se(),U(),M())})};re>0?S=window.setTimeout(()=>{this.paused?M():Me()},re):Me()},U=()=>{let N;for(;N=L.nextChunk(_);)_=N,oe(N);let ge=L.nextChunk(y);if(ge){if(y&&ge.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?M():(E(),this._initPlayerWith(e));return}ne(ge)}else M()},Y=(N,ge)=>{if(!p()||!this.sourceBuffer)return;let he,re,Me,dt=He=>{window.setTimeout(()=>{p()&&Y(N,ge)},He)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),dt(100);else{let He=se(),Ae=x.currentTime;!this.paused&&x.buffered.length>1&&T===Ae&&He-z>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),T!==Ae&&(T=Ae,z=He);let lt=this._getBufferSizeSec();if(lt>30)R(`Buffered ${lt} seconds; delaying appendBuffer`),dt(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:lt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(je){if(je.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(he=this.sourceBuffer.buffered.start(0),re=Ae,re-he>4&&this.sourceBuffer.remove(he,re-3)),dt(1e3);else throw je}}},Z=()=>{P&&k&&(R([`Appending chunk, sz=${P.byteLength}:`,JSON.stringify(y)]),Y(P,function(){P=null,U()}))},ie=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),ne=N=>{p()&&h(ie(N),(ge,he)=>{if(p()){if(he/=1e3,P=ge,y=N,a=N.startTS,he){let re=Math.min(10,N.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*re:re}Z()}},()=>this._handleNetworkError())},oe=N=>{p()&&(_i(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(N),!1)))},H=N=>{p()&&(e.cachedHeader=N,Y(N,()=>{k=!0,Z()}))};s=!0,L.seek(N=>{if(p()){if($=se(),!N){M();return}_=N,!Jl(v)||N.startTS>v?ne(N):(y=N,U())}},v),e.cachedHeader?H(e.cachedHeader):c(e.headerUrl,H,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>a},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),ks(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,_i(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ks(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=p=>{if(!this.autoQuality)return;let c,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&p<this.bitrate&&(h=this._getBufferSizeSec(),m=p/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(p)}`);return}c=this._selectQuality(p),c?this._switchToQuality(c):e(`Could not find quality by bitrate ${p}`)},s={updateChunk:(c,h)=>{let m=se();if(this.chunkRateEstimator.addInterval(c,m,h)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-c,speed:b}),!0}},get:()=>{let c=this.chunkRateEstimator.getBitRate();return c?c*.85:0}},a=-1/0,u,o=!0,d=()=>{let p=s.get();if(p&&u&&this.autoQuality){if(o&&p>u&&Ha(a)<3e4)return;i(p)}o=this.autoQuality};return{updateChunk:(p,c)=>{let h=s.updateChunk(p,c);return h&&d(),h},notifySwitch:p=>{let c=se();p<u&&(a=c),u=p}}}_fetchManifest(e,t,i){this.manifestRequest=ii(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(As).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ee(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let u=[];return a?.length?(a.forEach((o,d)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=d,u.push(o))}),u.sort(function(o,d){return o.video&&d.video?d.video.height-o.video.height:d.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ec))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as sc,filter as Zo,fromEvent as ac,interval as nc,isHigher as oc,isInvariantQuality as uc,isLower as dc,merge as lc,Subject as eu,Subscription as cc}from"@vkontakte/videoplayer-shared/evergreen";var qa=class{constructor(){this.onDroopedVideoFramesLimit$=new eu;this.subscription=new cc;this.playing=!1;this.tracks=[];this.forceChecker$=new eu;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!uc(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&oc(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(ac(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=nc(this.droppedFramesChecker.checkTime).pipe(Zo(()=>this.playing),Zo(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(sc(this.droppedFramesChecker.checkTime)),i=lc(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>dc(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ri=qa;import{map as hc,Observable as pc}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as mc}from"@vkontakte/videoplayer-shared/evergreen";var Ui=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var fc=(n,e)=>new pc(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,u)=>{a.forEach(o=>t.next(o.isIntersecting||Ui()))},{...i,...e});r.observe(n);let s=mc(document,"visibilitychange").pipe(hc(a=>!document.hidden||Ui())).subscribe(a=>t.next(a));return()=>{r.unobserve(n),s.unsubscribe()}}),Ve=fc;var Ec=["paused","playing","ready"],xc=["paused","playing","ready"],Hi=class{constructor(e){this.subscription=new Tc;this.videoState=new O("stopped");this.representations$=new Wa([]);this.droppedFramesManager=new ri;this.maxSeekBackTime$=new Wa(1/0);this.zeroTime$=new Wa(void 0);this.liveOffset=new Rt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:ru.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=ft(r.name)??Ic(r.video),u=r.bitrate/1e3,o={...r.video};if(!a)continue;let d={id:s,quality:a,bitrate:u,size:o};i.push({track:d,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),za(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(xc.includes(e)&&(a||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&Ec.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(ee(this.params.source.url,o))}return;default:return tu(e)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:ru.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(au(this.videoState.stateChangeStarted$.pipe(ws(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ws(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ie(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ws(r=>r.map(({track:s})=>s)),su(r=>!!r.length),yc()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Sc(),ws(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(bc({zeroTime:this.zeroTime$.pipe(su(za)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ze(this.video,this.params.desiredState.isLooped,t)).add(Te(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&nu(r),min:s&&nu(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return tu(r.to)}},t)).add(au(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,vc(["init"])).pipe(gc(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ye(this.video)}createLiveDashPlayer(){let e=new Ni({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&za(t)?t:Ye(e.map(({track:d})=>d),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),a||o||s!==u){let d=e.find(({track:l})=>l.id===s)?.representation;iu(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;iu(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var ou=Hi;var ae=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,s=n.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as Lh,assertNonNullable as $h,debounce as Mh,ErrorCategory as Uu,filter as fn,filterChanged as Xs,fromEvent as Rh,isNonNullable as Hu,isNullable as Dh,map as bn,merge as Js,observableFrom as gn,once as ju,Subscription as Bh}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as ji}from"@vkontakte/videoplayer-shared/evergreen";var Ps=n=>{if(!n)return{id:"EmptyResponse",category:ji.PARSER,message:"Empty response"};if(n.length<=2&&n.match(/^\d+$/))return{id:`UVError#${n}`,category:ji.NETWORK,message:`UV Error ${n}`};let e=n.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ji.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(n,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ji.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ji.PARSER,message:"Response is valid XML, but parser failed"}};var de=(n,e,t=0)=>{for(let i=0;i<n.length;i++)if(n.start(i)*1e3-t<=e&&n.end(i)*1e3+t>e)return!0;return!1};import{abortable as on,assertNonNullable as pi,combine as mi,ErrorCategory as Ne,filter as Qs,filterChanged as yr,flattenObject as Tr,fromEvent as ot,getTraceSubscriptionMethod as ch,interval as un,isNonNullable as Ir,isNullable as Vu,map as fi,merge as Ct,now as dn,Subject as Tt,Subscription as Cu,tap as hh,throttle as ph,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as kc,ErrorCategory as uu,Subject as du}from"@vkontakte/videoplayer-shared/evergreen";var Ac=18,lu=!1;try{lu=D.browser.isSafari&&!!D.browser.safariVersion&&D.browser.safariVersion<=Ac}catch(n){console.error(n)}var Ga=class{constructor(e){this.bufferFull$=new du;this.error$=new du;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:uu.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)};lu&&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:uu.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:kc(t)}}},cu=Ga;var si=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as St,assertNonNullable as xe,ErrorCategory as st,fromEvent as en,getExponentialDelay as tn,isNonNullable as ui,isNullable as le,now as Ms,once as Kc,Subject as Xc,Subscription as Jc,ValueSubject as Vt}from"@vkontakte/videoplayer-shared/evergreen";var Ls=n=>n.valid,j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ai=class extends j{};import{assertNever as wc}from"@vkontakte/videoplayer-shared/evergreen";var Qi=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:wc(e)}}};var qi=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var zi=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var K=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Wi=class extends K{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Gi=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var Dt=class extends K{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:u,SAPType:o,SAPDeltaTime:d})}}}};var Ki=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xi=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ji=class extends K{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Zi=class extends K{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var er=class extends K{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var tr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ir=class extends K{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var rr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ar=class extends K{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var nr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var or=class extends K{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ur=class extends K{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var dr=class extends K{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var lr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var hr=class extends j{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var Lc={ftyp:qi,moov:zi,mvhd:Wi,moof:Gi,mdat:Yi,sidx:Dt,trak:Ki,mdia:tr,mfhd:ar,tkhd:ir,traf:nr,tfhd:or,tfdt:ur,trun:dr,minf:rr,sv3d:Xi,st3d:Ji,prhd:Zi,proj:sr,equi:er,uuid:Qi,stbl:lr,stsd:cr,avc1:hr,unknown:ai},rt=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!a||!Ls(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=Lc[e];return i?new i(t,new n):new ai(t,new n)}};var gt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{Ls(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Mc=new TextDecoder("ascii"),Rc=n=>Mc.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Dc=n=>{let e=new Dt(n,new rt),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,u})},Bc=(n,e)=>{let i=new rt().parse(n),r=new gt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let u=s[0],o=a[a.length-1],d=u.source.byteOffset,p=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(n.buffer,d,p)},Vc=n=>{let t=new rt().parse(n),i=new gt(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},Cc=n=>{let t=new rt().parse(n);return new gt(t).find("sidx")?.timescale},Oc=(n,e)=>{let i=new rt().parse(n),s=new gt(i).findAll("traf"),a=s[s.length-1].children.find(p=>p.type==="tfhd"),u=s[s.length-1].children.find(p=>p.type==="tfdt"),o=s[s.length-1].children.find(p=>p.type==="trun"),d=0;return o.sampleDuration.length?d=o.sampleDuration.reduce((p,c)=>p+c,0):d=a.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+d)/e*1e3},Fc=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new rt().parse(n),r=new gt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},hu={validateData:Rc,parseInit:Fc,getIndexRange:()=>{},parseSegments:Dc,parseFeedableSegmentChunk:Bc,getChunkEndTime:Oc,getServerLatencyTimestamps:Vc,getTimescaleFromIndex:Cc};import{assertNonNullable as Ya,isNonNullable as bu,isNullable as Nc}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as _c}from"@vkontakte/videoplayer-shared/evergreen";var pu={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},mu=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=mr(n,t),r=i in pu,s=r?pu[i].type:"binary",a=n.getUint8(t),u=0;a&128?u=1:a&64?u=2:a&32?u=3:a&16?u=4:a&8?u=5:a&4?u=6:a&2?u=7:a&1&&(u=8);let o=new DataView(n.buffer,n.byteOffset+t+1,u-1),d=a&255>>u,l=mr(o),p=d*2**((u-1)*8)+l,c=t+u,h;return c+p>n.byteLength?h=new DataView(n.buffer,n.byteOffset+c):h=new DataView(n.buffer,n.byteOffset+c,p),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:c,tagSize:c+p,value:h,valueSize:p}},mr=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return mr(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:_c(e)}},Bt=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=mu(i);if(!e(r))return;r.type==="master"&&Bt(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},fu=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=mu(n);return Bt(r.value,({tag:s,type:a,value:u})=>(s===17143?e=Fe(u,a):s===17026?t=Fe(u,a):s===17029&&(i=Fe(u,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var gu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Uc=[231,22612,22743,167,171,163,160,175],Hc=n=>{let e,t,i,r,s=!1,a=!1,u=!1,o,d,l=!1,p=0;return Bt(n,({tag:c,type:h,value:m,valueSize:f})=>{if(c===21419){let b=Fe(m,h);d=mr(b)}else c!==21420&&(d=void 0);return c===408125543?(e=m.byteOffset,t=m.byteOffset+f):c===357149030?s=!0:c===290298740?a=!0:c===2807729?i=Fe(m,h):c===17545?r=Fe(m,h):c===21420&&d===475249515?o=Fe(m,h):c===374648427?Bt(m,({tag:b,type:g,value:E})=>b===30321?(l=Fe(E,g)===1,!1):!0):s&&a&&gu.includes(c)&&(u=!0),!u}),Ya(e,"Failed to parse webm Segment start"),Ya(t,"Failed to parse webm Segment end"),Ya(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:o,is3dVideo:l,stereoMode:p,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},jc=n=>{if(Nc(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Qc=(n,e)=>{let t=!1,i=!1,r=u=>bu(u.time)&&bu(u.position),s=[],a;return Bt(n,({tag:u,type:o,value:d})=>{switch(u){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=Fe(d,o));break;case 183:break;case 241:a&&(a.position=Fe(d,o));break;default:t&&gu.includes(u)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((u,o)=>{let{time:d,position:l}=u,p=s[o+1];return{status:"none",time:{from:d,to:p?p.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:p?e.segmentStart+p.position-1:e.segmentEnd-1}}})},qc=n=>{let e=0,t=!1;try{Bt(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Uc.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},Su={validateData:fu,parseInit:Hc,getIndexRange:jc,parseSegments:Qc,parseFeedableSegmentChunk:qc};var Ke=n=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(n);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Su;case"mp4":return hu}}throw new ReferenceError(`Unsupported mime type ${n}`)};var Xe=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var Ka=n=>{let e=n.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),u=s+a;return["6E","7A","F4"].includes(u)}}return!1};import{isNonNullable as Wc,isNullable as Tu}from"@vkontakte/videoplayer-shared/evergreen";var vu=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var yu=n=>{try{let e=zc(),t=n.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(u=>{let o=a[u];(typeof o>"u"||o==="")&&delete a[u]}),a}return null}catch{return null}};function zc(){let n="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",l=`^(?:(?<langtag>${`
117
- (?<language>${`(?:[a-z]{2,3}(?:-${n})?|[a-z]{4}|[a-z]{5,8})`})
115
+ [selected audio track] ${y?.id}
116
+ `}),y};var de=o=>new URL(o).hostname;import{assertNever as su,assertNonNullable as au,combine as Sc,debounce as vc,ErrorCategory as nu,filter as ou,filterChanged as yc,isNonNullable as Xa,map as Vs,merge as uu,observableFrom as Tc,once as Ic,Subscription as Ec,ValueSubject as Ja,videoQualityToHeight as du,videoSizeToQuality as xc}from"@vkontakte/videoplayer-shared/evergreen";var Zo=o=>{if(o instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(o.message))throw o;return!(o instanceof DOMException&&(o.code===20||o.name==="AbortError"))},ke=async(o,e)=>{let t=o.muted;try{await o.play()}catch(i){if(!Zo(i))return!1;if(e&&e(),t)return console.warn(i),!1;o.muted=!0;try{await o.play()}catch(r){return Zo(r)&&(o.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ds,isNullable as ec,assertNonNullable as Ni}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as eu,assertNonNullable as Ms,now as Jl}from"@vkontakte/videoplayer-shared/evergreen";function ne(){return Jl()}function za(o){return ne()-o}function Ga(o){let e=o.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=a=>i.test(a);return{resolve:(a,u,n=!1)=>{r(a)||(a.startsWith("/")||(a="/"+a),a=t+a);let d=a.indexOf("?")>-1?"&":"?";return n&&(a+=d+"lowLat=1",d="&"),u&&(a+=d+"_rnd="+Math.floor(999999999*Math.random())),a}}}function tu(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function si(o,e,t,i){let r=window.XMLHttpRequest,s,a,u,n=!1,d=0,h,c,l=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(n)return;Ms(h);let L=za(h),S;if(L<f){S=f-L,setTimeout(b,S);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,$()},g=L=>(s=L,_),y=L=>(c=L,_),T=()=>(p="json",_),v=()=>{if(!n){if(--d>=0){b(),i&&i();return}n=!0,c&&c(),t&&t()}},k=L=>(l=L,_),$=()=>{h=ne(),a=new r,a.open("get",o);let L=0,S,I=0,W=()=>(Ms(h),Math.max(h,Math.max(S||0,I||0)));if(s&&a.addEventListener("progress",R=>{let U=ne();s.updateChunk&&R.loaded>L&&(s.updateChunk(W(),R.loaded-L),L=R.loaded,S=U)}),u&&(a.timeout=u,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(n)return;Ms(a);let R=a.status;if(R>=200&&R<300){let{response:U,responseType:Y}=a,Z=U?.byteLength;if(typeof Z=="number"&&s){let ie=Z-L;ie&&s.updateChunk&&s.updateChunk(W(),ie)}Y==="json"&&(!U||!Object.values(U).length)?v():(c&&c(),e(U))}else v()}),a.addEventListener("error",()=>{v()}),l){let R=()=>{Ms(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(I=ne(),a.removeEventListener("readystatechange",R))};a.addEventListener("readystatechange",R)}return a.responseType=p,a.send(),_},_={withBitrateReporting:g,withParallel:k,withJSONResponse:T,withRetryCount:L=>(d=L,_),withRetryInterval:(L,S)=>(eu(L)&&(f=L),eu(S)&&(m=S),_),withTimeout:L=>(u=L,_),withFinally:y,send:$,abort:()=>{a&&(a.abort(),a=void 0),n=!0,c&&c()}};return _}var Fi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,u=s.end-s.start;i+=a;let n=s.bytes*a/u;r+=n,s.start=t,s.bytes-=n}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var _i=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ne(),r=n=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=n,e._errorCB?e._errorCB(n):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=n=>{e._complete=1,e._responseData=n,e._downloadTime=ne()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(n,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=si(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(a),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ne()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ne();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=i,a._retryCB=r,a._finallyCB=s._finallyCB,a._error||a._complete?(this._removeFromActive(e),setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(a._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=a=>(s._finallyCB=a,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as tc}from"@vkontakte/videoplayer-shared/evergreen";var Bs=1e4,Ya=3;var ic=6e4,rc=10,sc=1,ac=500,Ui=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new tc,this.chunkRateEstimator=new Fi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ga(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Ga(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,a=t&&1.62*(D.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:n,min:d}=this.autoQualityLimits||{};!jo({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(n&&s.video.height>n||d&&s.video.height<d)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ds(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{tu(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new _i(Ya,Bs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,a=null,u=null,n=null,d=null,h=!1,c=()=>{let v=s&&(!h||h===this.rep);return v||t("Not running!"),v},l=(v,k,$)=>{n&&n.abort(),n=si(this.urlResolver.resolve(v,!1),k,$,()=>this._retryCallback()).withTimeout(Bs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ya).withFinally(()=>{n=null}).send()},p=(v,k,$)=>{Ni(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),k,$,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=v=>{let k=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${k}=>${v}`),i.playbackRate=v)},f=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=ne()-1e4,P=0;for(let M=0;M<this.bufferStates.length;M++){let E=this.bufferStates[M];v=Math.min(v,E.buf),E.ts<$&&P++}this.bufferStates.splice(0,P),t(`update playback rate; minBuffer=${v} drop=${P} jitter=${this.sourceJitter}`);let x=v-sc;this.sourceJitter>=0?x-=this.sourceJitter/2:this.sourceJitter-=1,x>3?m(1.15):x>1?m(1.1):x>.3?m(1.05):m(1)}},g=v=>{let k,$=()=>k&&k.start?k.start.length:0,P=R=>k.start[R]/1e3,x=R=>k.dur[R]/1e3,M=R=>k.fragIndex+R,E=(R,U)=>({chunkIdx:M(R),startTS:P(R),dur:x(R),discontinuity:U}),_=()=>{let R=0;if(k&&k.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=U;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ie=k.dur.length-1;for(;ie>=0&&(Z-=k.dur[ie],!(Z<=0));--ie);R=Math.min(ie,k.dur.length-1-Y),R=Math.max(R,0)}return E(R,!0)},L=R=>{let U=$();if(!(U<=0)){if(Ds(R)){for(let Y=0;Y<U;Y++)if(P(Y)>R)return E(Y)}return _()}},S=R=>{let U=$(),Y=R?R.chunkIdx+1:0,Z=Y-k.fragIndex;if(!(U<=0)){if(!R||Z<0||Z-U>rc)return t(`Resync: offset=${Z} bChunks=${U} chunk=`+JSON.stringify(R)),_();if(!(Z>=U))return E(Y-k.fragIndex,!1)}},I=(R,U,Y)=>{d&&d.abort(),d=si(this.urlResolver.resolve(R,!0,this.lowLatency),U,Y,()=>this._retryCallback()).withTimeout(Bs).withRetryCount(Ya).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(R,U)=>{I(v,Y=>{if(!c())return;k=Y;let Z=!!k.lowLatency;Z!==this.lowLatency&&f(Z);let ie=0;for(let oe=0;oe<k.dur.length;++oe)ie+=k.dur[oe];ie>0&&(Ni(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,R(L(U))},()=>this._handleNetworkError())},nextChunk:S}},y=()=>{s=!1,u&&u.abort(),n&&n.abort(),d&&d.abort(),Ni(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:v=>{let{videoElement:k,logger:$}=this.params,P=g(e.jidxUrl),x,M,E,_,L=0,S,I,W,R=()=>{S&&(clearTimeout(S),S=void 0);let N=Math.max(ac,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=L+N,he=ne(),ae=Math.min(1e4,ye-he);L=he;let Re=()=>{d||c()&&P.seek(()=>{c()&&(L=ne(),U(),R())})};ae>0?S=window.setTimeout(()=>{this.paused?R():Re()},ae):Re()},U=()=>{let N;for(;N=P.nextChunk(_);)_=N,ue(N);let ye=P.nextChunk(E);if(ye){if(E&&ye.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?R():(y(),this._initPlayerWith(e));return}oe(ye)}else R()},Y=(N,ye)=>{if(!c()||!this.sourceBuffer)return;let he,ae,Re,dt=He=>{window.setTimeout(()=>{c()&&Y(N,ye)},He)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),dt(100);else{let He=ne(),we=k.currentTime;!this.paused&&k.buffered.length>1&&I===we&&He-W>500&&($("Stall suspected; trying to fix"),this._fixupStall()),I!==we&&(I=we,W=He);let lt=this._getBufferSizeSec();if(lt>30)$(`Buffered ${lt} seconds; delaying appendBuffer`),dt(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:lt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(je){if(je.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),Re=this.sourceBuffer.buffered.length,Re!==0&&(he=this.sourceBuffer.buffered.start(0),ae=we,ae-he>4&&this.sourceBuffer.remove(he,ae-3)),dt(1e3);else throw je}}},Z=()=>{M&&x&&($([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(E)]),Y(M,function(){M=null,U()}))},ie=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),oe=N=>{c()&&p(ie(N),(ye,he)=>{if(c()){if(he/=1e3,M=ye,E=N,a=N.startTS,he){let ae=Math.min(10,N.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ae:ae}Z()}},()=>this._handleNetworkError())},ue=N=>{c()&&(Ni(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(N),!1)))},H=N=>{c()&&(e.cachedHeader=N,Y(N,()=>{x=!0,Z()}))};s=!0,P.seek(N=>{if(c()){if(L=ne(),!N){R();return}_=N,!ec(v)||N.startTS>v?oe(N):(E=N,U())}},v),e.cachedHeader?H(e.cachedHeader):l(e.headerUrl,H,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>a},h}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Ds(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ni(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ds(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let l,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),m=c/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}l=this._selectQuality(c),l?this._switchToQuality(l):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(l,p)=>{let m=ne();if(this.chunkRateEstimator.addInterval(l,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-l,speed:b}),!0}},get:()=>{let l=this.chunkRateEstimator.getBitRate();return l?l*.85:0}},a=-1/0,u,n=!0,d=()=>{let c=s.get();if(c&&u&&this.autoQuality){if(n&&c>u&&za(a)<3e4)return;i(c)}n=this.autoQuality};return{updateChunk:(c,l)=>{let p=s.updateChunk(c,l);return p&&d(),p},notifySwitch:c=>{let l=ne();c<u&&(a=l),u=c}}}_fetchManifest(e,t,i){this.manifestRequest=si(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Bs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ke(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=a=>{let u=[];return a?.length?(a.forEach((n,d)=>{n.video&&r.canPlayType(n.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(n.codecs)&&(n.index=d,u.push(n))}),u.sort(function(n,d){return n.video&&d.video?d.video.height-n.video.height:d.bitrate-n.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ic))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as nc,filter as iu,fromEvent as oc,interval as uc,isHigher as dc,isInvariantQuality as lc,isLower as cc,merge as hc,Subject as ru,Subscription as pc}from"@vkontakte/videoplayer-shared/evergreen";var Ka=class{constructor(){this.onDroopedVideoFramesLimit$=new ru;this.subscription=new pc;this.playing=!1;this.tracks=[];this.forceChecker$=new ru;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!lc(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&dc(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(oc(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=uc(this.droppedFramesChecker.checkTime).pipe(iu(()=>this.playing),iu(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(nc(this.droppedFramesChecker.checkTime)),i=hc(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>cc(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ai=Ka;import{map as mc,Observable as fc}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as bc}from"@vkontakte/videoplayer-shared/evergreen";var Hi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var gc=(o,e)=>new fc(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,u)=>{a.forEach(n=>t.next(n.isIntersecting||Hi()))},{...i,...e});r.observe(o);let s=bc(document,"visibilitychange").pipe(mc(a=>!document.hidden||Hi())).subscribe(a=>t.next(a));return()=>{r.unobserve(o),s.unsubscribe()}}),Ve=gc;var kc=["paused","playing","ready"],wc=["paused","playing","ready"],ji=class{constructor(e){this.subscription=new Ec;this.videoState=new O("stopped");this.representations$=new Ja([]);this.droppedFramesManager=new ai;this.maxSeekBackTime$=new Ja(1/0);this.zeroTime$=new Ja(void 0);this.liveOffset=new Bt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:nu.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),a=ft(r.name)??xc(r.video),u=r.bitrate/1e3,n={...r.video};if(!a)continue;let d={id:s,quality:a,bitrate:u,size:n};i.push({track:d,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Xa(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(wc.includes(e)&&(a||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&kc.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let n=r?.from;n&&n==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let n=this.liveOffset.getTotalOffset();n>=this.maxSeekBackTime$.getValue()&&(n=0,this.liveOffset.resetTo(n)),this.liveOffset.resume(),this.params.output.position$.next(-n/1e3),this.dash.reinit(ee(this.params.source.url,n))}return;default:return su(e)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:nu.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(uu(this.videoState.stateChangeStarted$.pipe(Vs(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Vs(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=xe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Vs(r=>r.map(({track:s})=>s)),ou(r=>!!r.length),Ic()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(yc(),Vs(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Sc({zeroTime:this.zeroTime$.pipe(ou(Xa)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(We(this.video,this.params.desiredState.isLooped,t)).add(me(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&du(r),min:s&&du(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return su(r.to)}},t)).add(uu(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Tc(["init"])).pipe(vc(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}createLiveDashPlayer(){let e=new Ui({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Xa(t)?t:Ye(e.map(({track:d})=>d),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,n=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||s!==u)&&this.setVideoTrack(r),n&&this.setAutoQuality(i),a||n||s!==u){let d=e.find(({track:h})=>h.id===s)?.representation;au(d,"Representations missing"),this.dash.startPlay(d,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;au(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,a=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var lu=ji;var le=(o,e)=>{let t=0;for(let i=0;i<o.length;i++){let r=o.start(i)*1e3,s=o.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as Mh,assertNonNullable as Dh,combine as Bh,debounce as Vh,ErrorCategory as ju,filter as wr,filterChanged as Ar,fromEvent as Ch,isNonNullable as Qu,isNullable as Oh,map as Si,merge as $r,observableFrom as aa,once as na,Subscription as Fh,throttle as _h,ValueSubject as Nh}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Qi}from"@vkontakte/videoplayer-shared/evergreen";var Cs=o=>{if(!o)return{id:"EmptyResponse",category:Qi.PARSER,message:"Empty response"};if(o.length<=2&&o.match(/^\d+$/))return{id:`UVError#${o}`,category:Qi.NETWORK,message:`UV Error ${o}`};let e=o.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Qi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(o,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Qi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Qi.PARSER,message:"Response is valid XML, but parser failed"}};var ce=(o,e,t=0)=>{for(let i=0;i<o.length;i++)if(o.start(i)*1e3-t<=e&&o.end(i)*1e3+t>e)return!0;return!1};import{abortable as hn,assertNonNullable as mi,combine as fi,ErrorCategory as Ne,filter as Js,filterChanged as Ir,flattenObject as Er,fromEvent as ot,getTraceSubscriptionMethod as mh,interval as pn,isNonNullable as xr,isNullable as Ou,map as bi,merge as _t,now as mn,Subject as It,Subscription as Fu,tap as fh,throttle as bh,ValueSubject as X}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Ac,ErrorCategory as cu,Subject as hu}from"@vkontakte/videoplayer-shared/evergreen";var $c=18,pu=!1;try{pu=D.browser.isSafari&&!!D.browser.safariVersion&&D.browser.safariVersion<=$c}catch(o){console.error(o)}var Za=class{constructor(e){this.bufferFull$=new hu;this.error$=new hu;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:cu.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)};pu&&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:cu.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:Ac(t)}}},mu=Za;var ni=o=>{let e=0;for(let t=0;t<o.length;t++)e+=o.end(t)-o.start(t);return e*1e3};import{abortable as St,assertNonNullable as Se,ErrorCategory as st,fromEvent as nn,getExponentialDelay as on,isHigher as Jc,isNonNullable as vt,isNullable as re,now as _s,once as Zc,Subject as eh,Subscription as th,ValueSubject as Ft}from"@vkontakte/videoplayer-shared/evergreen";var Os=o=>o.valid,j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var oi=class extends j{};import{assertNever as Pc}from"@vkontakte/videoplayer-shared/evergreen";var qi=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:Pc(e)}}};var Wi=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var zi=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var K=class extends j{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Gi=class extends K{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Yi=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ki=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var Ct=class extends K{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,a=r<<1>>>1,u=this.readUint32();r=this.readUint32();let n=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:u,SAPType:n,SAPDeltaTime:d})}}}};var Xi=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ji=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zi=class extends K{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var er=class extends K{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var tr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rr=class extends K{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var sr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ar=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var nr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var or=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ur=class extends K{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var dr=class extends K{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var lr=class extends K{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var cr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hr=class extends K{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var pr=class extends j{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var Rc={ftyp:Wi,moov:zi,mvhd:Gi,moof:Yi,mdat:Ki,sidx:Ct,trak:Xi,mdia:ir,mfhd:nr,tkhd:rr,traf:or,tfhd:ur,tfdt:dr,trun:lr,minf:sr,sv3d:Ji,st3d:Zi,prhd:er,proj:ar,equi:tr,uuid:qi,stbl:cr,stsd:hr,avc1:pr,unknown:oi},rt=class o{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),a;try{a=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!a||!Os(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=Rc[e];return i?new i(t,new o):new oi(t,new o)}};var gt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{Os(t)&&(this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Dc=new TextDecoder("ascii"),Bc=o=>Dc.decode(new DataView(o.buffer,o.byteOffset+4,4))==="ftyp",Vc=o=>{let e=new Ct(o,new rt),t=e.earliestPresentationTime/e.timescale*1e3,i=o.byteOffset+o.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let a=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+a},byte:{from:i,to:i+s.referencedSize-1}};return t+=a,i+=s.referencedSize,u})},Cc=(o,e)=>{let i=new rt().parse(o),r=new gt(i),s=r.findAll("moof"),a=e?r.findAll("uuid"):r.findAll("mdat");if(!(a.length&&s.length))return null;let u=s[0],n=a[a.length-1],d=u.source.byteOffset,c=n.source.byteOffset-u.source.byteOffset+n.size;return new DataView(o.buffer,d,c)},Oc=o=>{let t=new rt().parse(o),i=new gt(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},Fc=o=>{let t=new rt().parse(o);return new gt(t).find("sidx")?.timescale},_c=(o,e)=>{let i=new rt().parse(o),s=new gt(i).findAll("traf"),a=s[s.length-1].children.find(c=>c.type==="tfhd"),u=s[s.length-1].children.find(c=>c.type==="tfdt"),n=s[s.length-1].children.find(c=>c.type==="trun"),d=0;return n.sampleDuration.length?d=n.sampleDuration.reduce((c,l)=>c+l,0):d=a.defaultSampleDuration*n.sampleCount,(Number(u.baseMediaDecodeTime)+d)/e*1e3},Nc=o=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new rt().parse(o),r=new gt(i);if(r.find("sv3d")){e.is3dVideo=!0;let a=r.find("st3d");a&&(e.stereoMode=a.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let n=r.find("equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},fu={validateData:Bc,parseInit:Nc,getIndexRange:()=>{},parseSegments:Vc,parseFeedableSegmentChunk:Cc,getChunkEndTime:_c,getServerLatencyTimestamps:Oc,getTimescaleFromIndex:Fc};import{assertNonNullable as en,isNonNullable as vu,isNullable as Hc}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Uc}from"@vkontakte/videoplayer-shared/evergreen";var bu={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},gu=o=>{let e=o.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=fr(o,t),r=i in bu,s=r?bu[i].type:"binary",a=o.getUint8(t),u=0;a&128?u=1:a&64?u=2:a&32?u=3:a&16?u=4:a&8?u=5:a&4?u=6:a&2?u=7:a&1&&(u=8);let n=new DataView(o.buffer,o.byteOffset+t+1,u-1),d=a&255>>u,h=fr(n),c=d*2**((u-1)*8)+h,l=t+u,p;return l+c>o.byteLength?p=new DataView(o.buffer,o.byteOffset+l):p=new DataView(o.buffer,o.byteOffset+l,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:l,tagSize:l+c,value:p,valueSize:c}},fr=(o,e=o.byteLength)=>{switch(e){case 1:return o.getUint8(0);case 2:return o.getUint16(0);case 3:return o.getUint8(0)*2**16+o.getUint16(1);case 4:return o.getUint32(0);case 5:return o.getUint8(0)*2**32+o.getUint32(1);case 6:return o.getUint16(0)*2**32+o.getUint32(2);case 7:{let t=o.getUint8(0)*281474976710656+o.getUint16(1)*4294967296+o.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(o,e)=>{switch(e){case"int":return o.getInt8(0);case"uint":return fr(o);case"float":return o.byteLength===4?o.getFloat32(0):o.getFloat64(0);case"string":return new TextDecoder("ascii").decode(o);case"utf8":return new TextDecoder("utf-8").decode(o);case"date":return new Date(Date.UTC(2001,0)+o.getInt8(0)).getTime();case"master":return o;case"binary":return o;default:Uc(e)}},Ot=(o,e)=>{let t=0;for(;t<o.byteLength;){let i=new DataView(o.buffer,o.byteOffset+t),r=gu(i);if(!e(r))return;r.type==="master"&&Ot(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},Su=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=gu(o);return Ot(r.value,({tag:s,type:a,value:u})=>(s===17143?e=Fe(u,a):s===17026?t=Fe(u,a):s===17029&&(i=Fe(u,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var yu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],jc=[231,22612,22743,167,171,163,160,175],Qc=o=>{let e,t,i,r,s=!1,a=!1,u=!1,n,d,h=!1,c=0;return Ot(o,({tag:l,type:p,value:m,valueSize:f})=>{if(l===21419){let b=Fe(m,p);d=fr(b)}else l!==21420&&(d=void 0);return l===408125543?(e=m.byteOffset,t=m.byteOffset+f):l===357149030?s=!0:l===290298740?a=!0:l===2807729?i=Fe(m,p):l===17545?r=Fe(m,p):l===21420&&d===475249515?n=Fe(m,p):l===374648427?Ot(m,({tag:b,type:g,value:y})=>b===30321?(h=Fe(y,g)===1,!1):!0):s&&a&&yu.includes(l)&&(u=!0),!u}),en(e,"Failed to parse webm Segment start"),en(t,"Failed to parse webm Segment end"),en(r,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:n,is3dVideo:h,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},qc=o=>{if(Hc(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wc=(o,e)=>{let t=!1,i=!1,r=u=>vu(u.time)&&vu(u.position),s=[],a;return Ot(o,({tag:u,type:n,value:d})=>{switch(u){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=Fe(d,n));break;case 183:break;case 241:a&&(a.position=Fe(d,n));break;default:t&&yu.includes(u)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((u,n)=>{let{time:d,position:h}=u,c=s[n+1];return{status:"none",time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},zc=o=>{let e=0,t=!1;try{Ot(o,i=>i.tag===524531317?i.tagSize<=o.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):jc.includes(i.tag)?(e+i.tagSize<=o.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=o.byteLength&&t?new DataView(o.buffer,o.byteOffset,e):null},Tu={validateData:Su,parseInit:Qc,getIndexRange:qc,parseSegments:Wc,parseFeedableSegmentChunk:zc};var Ke=o=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(o);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Tu;case"mp4":return fu}}throw new ReferenceError(`Unsupported mime type ${o}`)};var Xe=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var tn=o=>{let e=o.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,a]=i;return!!(a&&parseInt(a,10)>8)}case"vp09":{let[r,s,a]=i;return!!(r&&parseInt(r,10)>=2&&a&&parseInt(a,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,a]=r.toUpperCase(),u=s+a;return["6E","7A","F4"].includes(u)}}return!1};import{isNonNullable as Yc,isNullable as xu}from"@vkontakte/videoplayer-shared/evergreen";var Iu=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var Eu=o=>{try{let e=Gc(),t=o.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(n=>{r[n[0]]=n.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),a={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(a).forEach(u=>{let n=a[u];(typeof n>"u"||n==="")&&delete a[u]}),a}return null}catch{return null}};function Gc(){let o="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",h=`^(?:(?<langtag>${`
117
+ (?<language>${`(?:[a-z]{2,3}(?:-${o})?|[a-z]{4}|[a-z]{5,8})`})
118
118
  (-(?<script>[a-z]{4}))?
119
119
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
120
120
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
121
121
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
122
122
  (?:-(?<privateuse>(?:${e})))?
123
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(l,"i")}var Iu=n=>{if(!n?.startsWith("P"))return;let e=(a,u)=>{let o=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},_e=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(u,o)=>Tu(s)?u:Tu(o)?s:s.padStart(parseInt(o,10),"0"))}return t},$s=(n,e)=>{let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(P=>P.textContent?.trim()??""),u=a.at(0)??"",o=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),l=s.getAttribute("publishTime"),p=s.getElementsByTagName("vk:Attrs")[0],c=p?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=p?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=p?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=p?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;o&&(b={availabilityStartTime:d?new Date(d).getTime():0,publishTime:l?new Date(l).getTime():0,latestSegmentPublishTime:c?new Date(c).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let g,E=s.getAttribute("mediaPresentationDuration"),I=[...s.getElementsByTagName("Period")],v=I.reduce((P,y)=>({...P,[y.id]:y.children}),{}),x=I.reduce((P,y)=>({...P,[y.id]:y.getAttribute("duration")}),{});E?g=Iu(E):Object.values(x).filter(P=>P).length&&!o?g=Object.values(x).reduce((P,y)=>P+(Iu(y)??0),0):f&&(g=parseInt(f,10));let R=0,L=s.getAttribute("profiles")?.split(",")??[];for(let P of I.map(y=>y.id))for(let y of v[P]){let _=y.getAttribute("id")??"id"+(R++).toString(10),$=y.getAttribute("mimeType")??"",S=y.getAttribute("codecs")??"",T=y.getAttribute("contentType")??$?.split("/")[0],z=y.getAttribute("profiles")?.split(",")??[],M=yu(y.getAttribute("lang")??"")??{},U=y.querySelector("Label")?.textContent?.trim()??void 0,Y=y.querySelectorAll("Representation"),Z=y.querySelector("SegmentTemplate"),ie=y.querySelector("Role")?.getAttribute("value")??void 0,ne=T,oe={id:_,language:M.language,isDefault:ie==="main",label:U,codecs:S,hdr:ne==="video"&&Ka(S),mime:$,representations:[]};for(let H of Y){let N=H.getAttribute("lang")??void 0,ge=U??y.getAttribute("label")??H.getAttribute("label")??void 0,he=H.querySelector("BaseURL")?.textContent?.trim()??"",re=new URL(he||u,e).toString(),Me=H.getAttribute("mimeType")??$,dt=H.getAttribute("codecs")??S??"",He;if(T==="text"){let Ae=H.getAttribute("id")||"",lt=M.privateuse?.includes("x-auto")||Ae.includes("_auto"),je=H.querySelector("SegmentTemplate");if(je){let ki={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},jr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Qr=parseInt(je.getAttribute("startNumber")??"",10)??1,jt=parseInt(je.getAttribute("timescale")??"",10),Ia=je.querySelectorAll("SegmentTimeline S")??[],Qt=je.getAttribute("media");if(!Qt)continue;let qr=[],zr=0,Wr="",qt=0,Ai=Qr,pe=0;for(let Ce of Ia){let wt=parseInt(Ce.getAttribute("d")??"",10),Re=parseInt(Ce.getAttribute("r")??"",10)||0,ct=parseInt(Ce.getAttribute("t")??"",10);pe=Number.isFinite(ct)?ct:pe;let Pt=wt/jt*1e3,zt=pe/jt*1e3;for(let Qe=0;Qe<Re+1;Qe++){let ht=_e(Qt,{...ki,segmentNumber:Ai.toString(10),segmentTime:(pe+Qe*wt).toString(10)}),Wt=(zt??0)+Qe*Pt,Pi=Wt+Pt;Ai++,qr.push({time:{from:Wt,to:Pi},url:ht})}pe+=(Re+1)*wt,zr+=(Re+1)*Pt}qt=pe/jt*1e3,Wr=_e(Qt,{...ki,segmentNumber:Ai.toString(10),segmentTime:pe.toString(10)});let wi={time:{from:qt,to:1/0},url:Wr},Ze={type:"template",baseUrl:re,segmentTemplateUrl:Qt,initUrl:"",totalSegmentsDurationMs:zr,segments:qr,nextSegmentBeyondManifest:wi,timescale:jt};He={id:Ae,kind:"text",segmentReference:Ze,profiles:[],duration:g,bitrate:jr,mime:"",codecs:"",width:0,height:0,isAuto:lt}}else He={id:Ae,isAuto:lt,kind:"text",url:re}}else{let Ae=H.getAttribute("contentType")??Me?.split("/")[0]??T,lt=y.getAttribute("profiles")?.split(",")??[],je=parseInt(H.getAttribute("width")??"",10),ki=parseInt(H.getAttribute("height")??"",10),jr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Qr=H.getAttribute("frameRate")??"",jt=H.getAttribute("quality")??void 0,Ia=Qr?vu(Qr):void 0,Qt=H.getAttribute("id")??"id"+(R++).toString(10),qr=Ae==="video"?`${ki}p`:Ae==="audio"?`${jr}Kbps`:dt,zr=`${Qt}@${qr}`,Wr=[...L,...z,...lt],qt,Ai=H.querySelector("SegmentBase"),pe=H.querySelector("SegmentTemplate")??Z;if(Ai){let Ze=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ce,wt]=Ze.split("-").map(ht=>parseInt(ht,10)),Re={from:Ce,to:wt},ct=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[Pt,zt]=ct?ct.split("-").map(ht=>parseInt(ht,10)):[],Qe=ct?{from:Pt,to:zt}:void 0;qt={type:"byteRange",url:re,initRange:Re,indexRange:Qe}}else if(pe){let Ze={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ce=parseInt(pe.getAttribute("timescale")??"",10),wt=pe.getAttribute("initialization")??"",Re=pe.getAttribute("media"),ct=parseInt(pe.getAttribute("startNumber")??"",10)??1,Pt=_e(wt,Ze);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let zt=pe.querySelectorAll("SegmentTimeline S")??[],Qe=[],ht=0,Wt="",Pi=0;if(zt.length){let Gr=ct,Oe=0;for(let Gt of zt){let qe=parseInt(Gt.getAttribute("d")??"",10),Lt=parseInt(Gt.getAttribute("r")??"",10)||0,Yr=parseInt(Gt.getAttribute("t")??"",10);Oe=Number.isFinite(Yr)?Yr:Oe;let Ea=qe/Ce*1e3,il=Oe/Ce*1e3;for(let Kr=0;Kr<Lt+1;Kr++){let rl=_e(Re,{...Ze,segmentNumber:Gr.toString(10),segmentTime:(Oe+Kr*qe).toString(10)}),to=(il??0)+Kr*Ea,sl=to+Ea;Gr++,Qe.push({time:{from:to,to:sl},url:rl})}Oe+=(Lt+1)*qe,ht+=(Lt+1)*Ea}Pi=Oe/Ce*1e3,Wt=_e(Re,{...Ze,segmentNumber:Gr.toString(10),segmentTime:Oe.toString(10)})}else if(Wc(g)){let Oe=parseInt(pe.getAttribute("duration")??"",10)/Ce*1e3,Gt=Math.ceil(g/Oe),qe=0;for(let Lt=1;Lt<Gt;Lt++){let Yr=_e(Re,{...Ze,segmentNumber:Lt.toString(10),segmentTime:qe.toString(10)});Qe.push({time:{from:qe,to:qe+Oe},url:Yr}),qe+=Oe}Pi=qe,Wt=_e(Re,{...Ze,segmentNumber:Gt.toString(10),segmentTime:qe.toString(10)})}let tl={time:{from:Pi,to:1/0},url:Wt};qt={type:"template",baseUrl:re,segmentTemplateUrl:Re,initUrl:Pt,totalSegmentsDurationMs:ht,segments:Qe,nextSegmentBeyondManifest:tl,timescale:Ce}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ae||!Me)continue;let wi={video:"video",audio:"audio",text:"text"}[Ae];if(!wi)continue;ne||=wi,He={id:zr,kind:wi,segmentReference:qt,profiles:Wr,duration:g,bitrate:jr,mime:Me,codecs:dt,width:je,height:ki,fps:Ia,quality:jt}}oe.language||=N,oe.label||=ge,oe.mime||=Me,oe.codecs||=dt,oe.hdr||=ne==="video"&&Ka(dt),oe.representations.push(He)}if(ne){let H=r[ne].find(N=>N.id===oe.id);if(H&&oe.representations.every(N=>N.segmentReference.type==="template"))for(let N of H.representations){let he=oe.representations.find(Me=>Me.id===N.id)?.segmentReference,re=N.segmentReference;re.segments.push(...he.segments),re.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[ne].push(oe)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{videoSizeToQuality as Gc}from"@vkontakte/videoplayer-shared/evergreen";var Eu=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??Gc({width:e,height:t});return u&&{id:n,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},xu=({id:n,bitrate:e})=>({id:n,bitrate:e}),ku=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Au=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),Xa=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Ja=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Za=n=>"url"in n,Pe=n=>n.type==="template";import{isNonNullable as wu}from"@vkontakte/videoplayer-shared/evergreen";var B=(n,e)=>wu(n)&&wu(e)&&n.readyState==="open"&&Yc(n,e);function Yc(n,e){for(let t=0;t<n.activeSourceBuffers.length;++t)if(n.activeSourceBuffers[t]===e)return!0;return!1}var fr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:d}){this.currentLiveSegmentServerLatency$=new Vt(0);this.currentLowLatencySegmentLength$=new Vt(0);this.currentSegmentLength$=new Vt(0);this.onLastSegment$=new Vt(!1);this.fullyBuffered$=new Vt(!1);this.playingRepresentation$=new Vt(void 0);this.playingRepresentationInit$=new Vt(void 0);this.error$=new Xc;this.gaps=[];this.subscription=new Jc;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=St(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cu(this.sourceBuffer),this.subscription.add(en(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),u??={id:"SegmentEjection",category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(u)})),this.subscription.add(en(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:st.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 o=Math.min(this.bufferLimit,si(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let d=this.getForwardBufferDuration(u),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,d<l).catch(p=>{this.handleAsyncError(p,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);xe(i,"No init buffer for starting representation"),xe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=St(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);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!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();ui(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=St(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);xe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(le(s)||le(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),xe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!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();ui(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=St(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let d=t.find(c=>c.id===o);d&&this.representations.set(o,d);let l=this.representations.get(o);if(!l||!Pe(l.segmentReference))return;let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);xe(r);let s=this.segments.get(i);xe(s,"No segments for starting representation");let a=this.initData.get(i);if(xe(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let 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=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!d?.live,this.baseUrls=d?.baseUrls??[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),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,St(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);xe(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(le(u)||le(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),xe(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 o=this.getCurrentPosition();ui(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!le(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(le(e)||le(this.downloadingRepresentationId)||le(this.playingRepresentationId)||le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ui(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);ui(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=this.getForwardBufferDuration(e),p=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+a&&(s=p)}if(isFinite(this.bufferLimit)&&si(this.sourceBuffer.buffered)>=this.bufferLimit){let l=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{let p=o.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=i.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<a),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}),i=s.time.to;ui(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Pe(i.segmentReference))return;let r=i.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,o=r?.findIndex(d=>u>=d.time.from+s&&u<=d.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,d)}else{let d=r.slice(o+1);this.segments.set(i.id,[...a,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;xe(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}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)??[],a=s.find(o=>Math.floor(o.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(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),d=_e(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:c,time:{from:h,to:m}},f)=>{let b=h<=i&&m>=i,g=h>i||b||f===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+E||r<E&&m-h>=E||m<=i+E;return(c==="none"||c==="partially_ejected"&&g&&I&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(de(this.sourceBuffer.buffered,h)&&de(this.sourceBuffer.buffered,m)))&&g&&I});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,o=0,d=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<a.length&&(u<=l||o<=p);c++){let h=a[c];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")d.push(h);else break}return d}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:o,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await St(u,async function*(){let l=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,l))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Ms(),!l)return;let p=new DataView(l),c=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(p,f)}o&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(p);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xe(l)||(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 o of e)o.status="downloading",this.activeSegments.add({segment:o,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 St(a,async function*(){let o=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,o),en(window,"online").pipe(Kc()).subscribe(()=>{d(),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=Ms(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Xe(o)||(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,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ms(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}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=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ms();let p=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,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:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),l=Ke(a.mime).parseFeedableSegmentChunk(d,this.isLive);l?.byteLength&&(o.status="partially_fed",u.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),u.fedBytes+=l.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 o of this.activeSegments){let{segment:d}=o;if(o.representationId!==t)continue;if(s.aborted){await a();continue}let l=d.byte.from-i,p=d.byte.to-i,c=p-l+1,h=l<r,m=p<=r;if(!h)continue;let f=Ke(u.mime);if(d.status==="downloading"&&m){d.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,c);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(o.loadedBytes=Math.min(c,r-l),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+o.feedingBytes,o.loadedBytes-o.feedingBytes),g=o.loadedBytes===c?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(d.status="partially_fed",o.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(o.fedBytes+=g.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&D.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(de(this.sourceBuffer.buffered,e.segment.time.from,100)&&de(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:st.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",Za(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?St(this.destroyAbortController.signal,async function*(){let u=tn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(async u=>{if(!u)return;let{init:o,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let c=l;this.isLive&&Pe(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:st.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||le(e))return!1;let r=[],s=0,a=o=>{o.sort((l,p)=>l.from-p.from);let d=[o[0]];for(let l=1;l<o.length;l++){let{from:p,to:c}=o[l],h=d[d.length-1];h.to>=p?h.to=Math.max(h.to,c):d.push(o[l])}return d},u=o=>{if(s>=t)return r;r.push({...o.time}),r=a(r);let d=Za(o)?o.size??0:o.byte.to-o.byte.from;s+=d};for(let o of this.segments.values())for(let d of o){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&d.status==="fed"&&u(d)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let d=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let c of this.segments.values())for(let h of c)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(d)&&Math.round(h.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let c={time:{from:d,to:l},url:"",status:"none"};u(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+o&&l.status==="fed"&&u(l)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||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)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||le(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let a=this.sourceBuffer.buffered.start(s)*1e3,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||a>=i.time.to)){if(a<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),a<i.time.to&&a>i.time.from&&(r.to=a)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:st.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(le(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||le(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(l=>l.from-t<=a&&l.to+t>=u),d=e.filter(l=>a>=l.from&&a<l.to-t||u>l.from+t&&u<=l.to);o||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:st.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var vt=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var Rs=n=>{let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as br,assertNever as Pu,fromEvent as Lu,merge as Zc,now as gr,Subject as di,ValueSubject as rn,flattenObject as li,ErrorCategory as Sr,SubscriptionRemovable as eh}from"@vkontakte/videoplayer-shared/evergreen";var Ds=n=>{let e=new URL(n);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Vs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new di;this.manifestReceived=new di;this.firstBytesRequested=new di;this.firstBytesReceived=new di;this.lastConnectionType$=new rn(void 0);this.lastConnectionReused$=new rn(void 0);this.lastRequestFirstBytes$=new rn(void 0);this.recoverableError$=new di;this.error$=new di;this.abortAllController=new AbortController;this.subscription=new eh;this.fetchManifest=br(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ds(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Bs);return r?(t.log("success",li({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",li({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=br(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:o=!1,bufferOptimisation:d=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let S=new URL(l,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),l=S.toString();break}default:Pu(t)}this.requestQuic&&(l=vt(l));let h=this.abortAllController.signal,m;if(a){let S=new AbortController;if(m=Zc(Lu(this.abortAllController.signal,"abort"),Lu(a,"abort")).subscribe(()=>{try{S.abort()}catch(T){Bs(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{S.abort()}catch(T){Bs(T)}h=S.signal}let f=0,b=gr();c.log("startRequest",li({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(l,{priority:s,headers:p,signal:h}),E=gr();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(E-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let S=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:S}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let S=gr(),T={requestStartedAt:b,requestEndedAt:S,duration:S-b};return c.log("endRequest",li(T)),c.end(),g.arrayBuffer()}let I=g.body;if(u){let S;[I,S]=g.body.tee(),this.throughputEstimator?.trackStream(S,o)}let v=I.getReader(),x,R=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(R)&&(x=R),!x&&i&&(x=i.to-i.from+1);let L=x?new Uint8Array(x):new Uint8Array(0),k=!1,P=S=>{this.unsubscribeAbortSubscription(m),k=!0,Bs(S)},y=br(h,async function*({done:S,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(gr()-b),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!S&&T){if(d&&x)L.set(T,f),f+=T.byteLength;else{let z=new Uint8Array(L.length+T.length);z.set(L),z.set(T,L.length),L=z,f+=T.byteLength}r?.(new DataView(L.buffer),f),yield v?.read().then(y,P)}}.bind(this));yield v?.read().then(y,P),this.unsubscribeAbortSubscription(m);let _=gr(),$={failed:k,requestStartedAt:b,requestEndedAt:_,duration:_-b};return k?(c.error("endRequest",li($)),c.end(),null):(c.log("endRequest",li($)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=br(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,o=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,o=s+1===d,o&&(a=Math.min(d,r),u=Math.max(l,s))),a=Math.min(a,0);let p=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!p)return null;let c=new DataView(p,r-a,s-a+1);if(!t.validateData(c))throw new Error("Invalid media file");let h=t.parseInit(c),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(p,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,h,m);return{init:h,dataView:new DataView(p),segments:b}}.bind(this));this.fetchTemplateRepresentation=br(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}=Rs(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:Pu(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Sr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Sr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Sr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Sr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Sr.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Bs=n=>{if(!Xe(n))throw n};var at=(n,e,t)=>t*e+(1-t)*n,sn=(n,e)=>n.reduce((t,i)=>t+i,0)/e,$u=(n,e,t,i)=>{let r=0,s=t,a=sn(n,e),u=e<i?e:i;for(let o=0;o<u;o++)n[s]>a?r++:r--,s=(n.length+s-1)%n.length;return Math.abs(r)===u};import{isNullable as th,ValueSubject as Mu}from"@vkontakte/videoplayer-shared/evergreen";var yt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mu(e.initial),this.debounced$=new Mu(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,a=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<a)&&(th(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Cs=class extends yt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=at(this.slow,e,this.params.emaAlphaSlow),this.fast=at(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Os=class extends yt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=sn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=at(this.emaSmoothed,e,this.params.emaAlpha);let i=$u(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Fs=class extends yt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?at(this.smoothed,t,this.params.emaAlpha):t}};var nt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Cs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Os({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Fs({initial:e,label:"liveEdgeDelay",...t})}};var ci=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};import{isNullable as ih,ValueSubject as rh}from"@vkontakte/videoplayer-shared/evergreen";var vr=class n{constructor(e,t){this.currentRepresentation$=new rh(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(!ih(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 o=r.segments.find(d=>d.time.from<=e&&d.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Pe(t.segmentReference))}};import{assertNever as Ns}from"@vkontakte/videoplayer-shared/evergreen";var _s=n=>{let{webmDecodingInfo:e}=D.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(n){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Ns(n)}return[t,i]},Ru=({webmCodec:n,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],..._s(n),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(D.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",..._s(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[..._s(n),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",..._s(n),...s,"HLS","HLS_ONDEMAND"];default:Ns(e)}if(D.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Ns(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Du=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],u,o=D.device.isMac&&D.browser.isSafari;if(D.device.isAndroid)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=a;break}default:Ns(n)}else D.video.nativeHlsSupported&&!o?u=a:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},an=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Us=n=>{if(n.size===0)return;if(n.size===1)return n.values().next().value.split(".").at(0);for(let t of n){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return n.values().next().value.split(".").at(0)},Hs=n=>{let e=n.map(i=>hi(i)),{codecs:t}=D.video;return oh().filter(i=>{if(e.includes(i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},js=n=>{let e=n.map(i=>hi(i)),{codecs:t}=D.video;return uh().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},hi=n=>n.split(".")[0].replace("0",""),oh=()=>["av1","vp9","hev1","avc1"],uh=()=>["opus","mp4a"];var mh=["timeupdate","progress","play","seeked","stalled","waiting"],fh=["timeupdate","progress","loadeddata","playing","seeked"];var qs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Cu;this.representationSubscription=new Cu;this.state$=new O("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new Tt;this.manifestRequested=new Tt;this.manifestReceived=new Tt;this.firstBytesRequested=new Tt;this.firstBytesReceived=new Tt;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new Tt;this.fetcherError$=new Tt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Tt;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=on(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ne.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=on(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ne.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=$s(e??"",this.manifestUrlString)}catch(o){let d=Ps(e)??{id:"ManifestParsing",category:Ne.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(d)}if(!t)return null;let i=(o,d,l)=>!!(this.element?.canPlayType?.(d)&&we()?.isTypeSupported?.(`${d}; codecs="${l}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:d,streamIsUnpublished:l,streamIsAlive:p}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((d-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=l?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:c,codecs:h})=>i(o,c,h));r[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:h})=>h);o==="audio"&&(a=js(c),p=a[0]),o==="video"&&(s=Hs(c),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=l.filter(({codecs:h})=>hi(h)===p))}else{let c=new Set(l.map(({codecs:h})=>h));p=Us(c),p&&(r[o]=l.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,h=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);D.display.isHDR&&c&&h?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",Tr(u)),u}.bind(this));this.initRepresentations=on(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Tr({initialVideo:e,initialAudio:t,sourceHls:i})),pi(this.manifest),pi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(ot(c,"error").pipe(Qs(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ne.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=as();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Yt())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,h)=>[...c,...h.representations],[]);if(this.videoBufferManager=new fr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],Ir(t)){let c=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new fr("audio",this.source,c,a),this.bufferManagers.push(this.audioBufferManager)}vr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new vr(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 o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ct(...fh.map(c=>ot(this.element,c))).pipe(fi(c=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),yr(),hh(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ct(ot(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(yr()).subscribe(h=>this.liveStreamEndTimestamp=dn())),this.subscription.add(ot(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=un(1e3).subscribe(h=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ot(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(mi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fi(({isActiveLive:h,isLowLatency:m})=>h&&m),yr()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ci(this.element,1)})),this.representationSubscription.add(mi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Qs(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(mi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Qs(({isLive:h})=>h),yr((h,m)=>m.bufferLength<h.bufferLength),fi(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=pt(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(mi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(I)>g&&(v=1+Math.sign(I)*E),ci(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(mi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ph(1e3)).subscribe(async({liveLoadBufferLength:h,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,E=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,x=isFinite(h)?h:m,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let k="none";if(R?k="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&x<E?k="live_forward_buffering":x<E+v&&(k="live_with_target_offset"),isFinite(h)&&(c=h>c?h:c),k==="live_forward_buffering"||k==="live_with_target_offset"){let P=c-(E+I),y=this.normolizeLiveOffset(Math.trunc(b+P/f)),_=Math.abs(y-b),$=0;!h||_<=this.tuning.dashCmafLive.offsetCalculationError?$=b:y>0&&_>this.tuning.dashCmafLive.offsetCalculationError&&($=y),this.manifestUrlString=ee(this.manifestUrlString,$,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(c=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Ne.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let d=Ct(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(fi(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=Ct(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(fi(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=mi({allBuffersFull:d,someBufferEnded:l}).pipe(yr(),fi(({allBuffersFull:c,someBufferEnded:h})=>c&&h),Qs(c=>c));if(this.representationSubscription.add(Ct(this.forceEnded$,p).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:Ne.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(Ct(...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(h=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),Pe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&Ir(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=un(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ne.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Vs({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()}async seekLive(e){pi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?dn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){pi(this.element),this.state$.setState("running"),this.subscription.add(Ct(...mh.map(e=>ot(this.element,e)),ot(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ne.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ot(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ot(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&de(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=dn(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,l=o<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((l||p)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let c=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(c).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:Ne.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=c}else{let c=this.element.currentTime*1e3;this.videoBufferManager?.maintain(c),this.audioBufferManager?.maintain(c),i.position=c}this.tracer.log("stallIntervalCallback",Tr(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=un(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ne.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){pi(this.element),pi(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),de(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Vu(this.element)||Vu(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Tr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Ir(this.element)&&Ir(this.source)&&Ir(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.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=ch(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-a<=r&&o.to+a>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Tr(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var zs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ws=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,a=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:a},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Fu=`attribute vec2 a_vertex;
123
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(h,"i")}var ku=o=>{if(!o?.startsWith("P"))return;let e=(a,u)=>{let n=a?parseFloat(a.replace(",",".")):NaN;return(isNaN(n)?0:n)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(o),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},_e=(o,e)=>{let t=o;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let a=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(a,(u,n)=>xu(s)?u:xu(n)?s:s.padStart(parseInt(n,10),"0"))}return t},Fs=(o,e)=>{let i=new DOMParser().parseFromString(o,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],a=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(M=>M.textContent?.trim()??""),u=a.at(0)??"",n=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],l=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;n&&(b={availabilityStartTime:d?new Date(d).getTime():0,publishTime:h?new Date(h).getTime():0,latestSegmentPublishTime:l?new Date(l).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let g,y=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],v=T.reduce((M,E)=>({...M,[E.id]:E.children}),{}),k=T.reduce((M,E)=>({...M,[E.id]:E.getAttribute("duration")}),{});y?g=ku(y):Object.values(k).filter(M=>M).length&&!n?g=Object.values(k).reduce((M,E)=>M+(ku(E)??0),0):f&&(g=parseInt(f,10));let $=0,P=s.getAttribute("profiles")?.split(",")??[];for(let M of T.map(E=>E.id))for(let E of v[M]){let _=E.getAttribute("id")??"id"+($++).toString(10),L=E.getAttribute("mimeType")??"",S=E.getAttribute("codecs")??"",I=E.getAttribute("contentType")??L?.split("/")[0],W=E.getAttribute("profiles")?.split(",")??[],R=Eu(E.getAttribute("lang")??"")??{},U=E.querySelector("Label")?.textContent?.trim()??void 0,Y=E.querySelectorAll("Representation"),Z=E.querySelector("SegmentTemplate"),ie=E.querySelector("Role")?.getAttribute("value")??void 0,oe=I,ue={id:_,language:R.language,isDefault:ie==="main",label:U,codecs:S,hdr:oe==="video"&&tn(S),mime:L,representations:[]};for(let H of Y){let N=H.getAttribute("lang")??void 0,ye=U??E.getAttribute("label")??H.getAttribute("label")??void 0,he=H.querySelector("BaseURL")?.textContent?.trim()??"",ae=new URL(he||u,e).toString(),Re=H.getAttribute("mimeType")??L,dt=H.getAttribute("codecs")??S??"",He;if(I==="text"){let we=H.getAttribute("id")||"",lt=R.privateuse?.includes("x-auto")||we.includes("_auto"),je=H.querySelector("SegmentTemplate");if(je){let wi={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Jr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Zr=parseInt(je.getAttribute("startNumber")??"",10)??1,Wt=parseInt(je.getAttribute("timescale")??"",10),$a=je.querySelectorAll("SegmentTimeline S")??[],zt=je.getAttribute("media");if(!zt)continue;let es=[],ts=0,is="",Gt=0,Ai=Zr,pe=0;for(let Ce of $a){let Pt=parseInt(Ce.getAttribute("d")??"",10),Me=parseInt(Ce.getAttribute("r")??"",10)||0,ct=parseInt(Ce.getAttribute("t")??"",10);pe=Number.isFinite(ct)?ct:pe;let Lt=Pt/Wt*1e3,Yt=pe/Wt*1e3;for(let Qe=0;Qe<Me+1;Qe++){let ht=_e(zt,{...wi,segmentNumber:Ai.toString(10),segmentTime:(pe+Qe*Pt).toString(10)}),Kt=(Yt??0)+Qe*Lt,Pi=Kt+Lt;Ai++,es.push({time:{from:Kt,to:Pi},url:ht})}pe+=(Me+1)*Pt,ts+=(Me+1)*Lt}Gt=pe/Wt*1e3,is=_e(zt,{...wi,segmentNumber:Ai.toString(10),segmentTime:pe.toString(10)});let $i={time:{from:Gt,to:1/0},url:is},Ze={type:"template",baseUrl:ae,segmentTemplateUrl:zt,initUrl:"",totalSegmentsDurationMs:ts,segments:es,nextSegmentBeyondManifest:$i,timescale:Wt};He={id:we,kind:"text",segmentReference:Ze,profiles:[],duration:g,bitrate:Jr,mime:"",codecs:"",width:0,height:0,isAuto:lt}}else He={id:we,isAuto:lt,kind:"text",url:ae}}else{let we=H.getAttribute("contentType")??Re?.split("/")[0]??I,lt=E.getAttribute("profiles")?.split(",")??[],je=parseInt(H.getAttribute("width")??"",10),wi=parseInt(H.getAttribute("height")??"",10),Jr=parseInt(H.getAttribute("bandwidth")??"",10)/1e3,Zr=H.getAttribute("frameRate")??"",Wt=H.getAttribute("quality")??void 0,$a=Zr?Iu(Zr):void 0,zt=H.getAttribute("id")??"id"+($++).toString(10),es=we==="video"?`${wi}p`:we==="audio"?`${Jr}Kbps`:dt,ts=`${zt}@${es}`,is=[...P,...W,...lt],Gt,Ai=H.querySelector("SegmentBase"),pe=H.querySelector("SegmentTemplate")??Z;if(Ai){let Ze=H.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ce,Pt]=Ze.split("-").map(ht=>parseInt(ht,10)),Me={from:Ce,to:Pt},ct=H.querySelector("SegmentBase")?.getAttribute("indexRange"),[Lt,Yt]=ct?ct.split("-").map(ht=>parseInt(ht,10)):[],Qe=ct?{from:Lt,to:Yt}:void 0;Gt={type:"byteRange",url:ae,initRange:Me,indexRange:Qe}}else if(pe){let Ze={representationId:H.getAttribute("id")??void 0,bandwidth:H.getAttribute("bandwidth")??void 0},Ce=parseInt(pe.getAttribute("timescale")??"",10),Pt=pe.getAttribute("initialization")??"",Me=pe.getAttribute("media"),ct=parseInt(pe.getAttribute("startNumber")??"",10)??1,Lt=_e(Pt,Ze);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let Yt=pe.querySelectorAll("SegmentTimeline S")??[],Qe=[],ht=0,Kt="",Pi=0;if(Yt.length){let rs=ct,Oe=0;for(let Xt of Yt){let qe=parseInt(Xt.getAttribute("d")??"",10),Rt=parseInt(Xt.getAttribute("r")??"",10)||0,ss=parseInt(Xt.getAttribute("t")??"",10);Oe=Number.isFinite(ss)?ss:Oe;let Pa=qe/Ce*1e3,sl=Oe/Ce*1e3;for(let as=0;as<Rt+1;as++){let al=_e(Me,{...Ze,segmentNumber:rs.toString(10),segmentTime:(Oe+as*qe).toString(10)}),ro=(sl??0)+as*Pa,nl=ro+Pa;rs++,Qe.push({time:{from:ro,to:nl},url:al})}Oe+=(Rt+1)*qe,ht+=(Rt+1)*Pa}Pi=Oe/Ce*1e3,Kt=_e(Me,{...Ze,segmentNumber:rs.toString(10),segmentTime:Oe.toString(10)})}else if(Yc(g)){let Oe=parseInt(pe.getAttribute("duration")??"",10)/Ce*1e3,Xt=Math.ceil(g/Oe),qe=0;for(let Rt=1;Rt<Xt;Rt++){let ss=_e(Me,{...Ze,segmentNumber:Rt.toString(10),segmentTime:qe.toString(10)});Qe.push({time:{from:qe,to:qe+Oe},url:ss}),qe+=Oe}Pi=qe,Kt=_e(Me,{...Ze,segmentNumber:Xt.toString(10),segmentTime:qe.toString(10)})}let rl={time:{from:Pi,to:1/0},url:Kt};Gt={type:"template",baseUrl:ae,segmentTemplateUrl:Me,initUrl:Lt,totalSegmentsDurationMs:ht,segments:Qe,nextSegmentBeyondManifest:rl,timescale:Ce}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!we||!Re)continue;let $i={video:"video",audio:"audio",text:"text"}[we];if(!$i)continue;oe||=$i,He={id:ts,kind:$i,segmentReference:Gt,profiles:is,duration:g,bitrate:Jr,mime:Re,codecs:dt,width:je,height:wi,fps:$a,quality:Wt}}ue.language||=N,ue.label||=ye,ue.mime||=Re,ue.codecs||=dt,ue.hdr||=oe==="video"&&tn(dt),ue.representations.push(He)}if(oe){let H=r[oe].find(N=>N.id===ue.id);if(H&&ue.representations.every(N=>N.segmentReference.type==="template"))for(let N of H.representations){let he=ue.representations.find(Re=>Re.id===N.id)?.segmentReference,ae=N.segmentReference;ae.segments.push(...he.segments),ae.nextSegmentBeyondManifest=he.nextSegmentBeyondManifest}else r[oe].push(ue)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{videoSizeToQuality as Kc}from"@vkontakte/videoplayer-shared/evergreen";var br=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??Kc({width:e,height:t});return u&&{id:o,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},wu=({id:o,bitrate:e})=>({id:o,bitrate:e}),Au=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),$u=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),rn=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),sn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),an=o=>"url"in o,$e=o=>o.type==="template";import{isNonNullable as Pu}from"@vkontakte/videoplayer-shared/evergreen";var B=(o,e)=>Pu(o)&&Pu(e)&&o.readyState==="open"&&Xc(o,e);function Xc(o,e){for(let t=0;t<o.activeSourceBuffers.length;++t)if(o.activeSourceBuffers[t]===e)return!0;return!1}var gr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:n=!1,manifest:d}){this.currentLiveSegmentServerLatency$=new Ft(0);this.currentLowLatencySegmentLength$=new Ft(0);this.currentSegmentLength$=new Ft(0);this.onLastSegment$=new Ft(!1);this.fullyBuffered$=new Ft(!1);this.playingRepresentation$=new Ft(void 0);this.playingRepresentationInit$=new Ft(void 0);this.error$=new eh;this.gaps=[];this.subscription=new th;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.startWith=St(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Se(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new mu(this.sourceBuffer),this.subscription.add(nn(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let u,n=this.mediaSource.readyState;n!=="open"&&(u={id:`SegmentEjection_source_${n}`,category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),u??={id:"SegmentEjection",category:st.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(u)})),this.subscription.add(nn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:st.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 d=this.getForwardBufferDuration(u),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,d<h).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Se(i,"No init buffer for starting representation"),Se(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=St(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);Se(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(re(s)||re(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Se(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();vt(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=St(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);Se(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(re(s)||re(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Se(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();vt(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=St(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(n=>n.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let n of this.representations.keys()){let d=t.find(l=>l.id===n);d&&this.representations.set(n,d);let h=this.representations.get(n);if(!h||!$e(h.segmentReference))return;let c=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Se(r);let s=this.segments.get(i);Se(s,"No segments for starting representation");let a=this.initData.get(i);if(Se(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))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=!!d?.live,this.baseUrls=d?.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,St(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Se(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(re(u)||re(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),Se(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();vt(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(){!re(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(re(e)||re(this.downloadingRepresentationId)||re(this.playingRepresentationId)||re(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||vt(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(Se(t,`No such representation ${this.downloadingRepresentationId}`),Se(i,`No such representation ${this.playingRepresentationId}`),re(r)||re(s))return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);vt(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 l=this.getForwardBufferDuration(e),p=br(i),m=br(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&vt(p)&&vt(m)&&Jc(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?u+=Math.min(l,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=a.time.to-e+n&&(u=a?a.time.to+n:-1/0),this.tuning.dash.useNewRepresentationSwitch){let y=[...this.segments.entries()].map(([T,v])=>{let k=v.find($=>e>=$.time.from&&e<$.time.to);return{representationId:T,status:k?.status}}).find(T=>T.status==="fed")?.representationId;if(!y)return;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 l=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=[];if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,u),h.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))l="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(h,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=r.at(-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-c.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;vt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!$e(i.segmentReference))return;let r=i.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,n=r?.findIndex(d=>u>=d.time.from+s&&u<=d.time.to+s);if(n===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,d)}else{let d=r.slice(n+1);this.segments.set(i.id,[...a,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Se(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!$e(r))return;let s=this.segments.get(i.id)??[],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),d=_e(r.segmentTemplateUrl,{segmentTime:n});s.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:l,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(l==="none"||l==="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[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,n=0,d=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<a.length&&(u<=h||n<=c);l++){let p=a[l];if(u+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")d.push(p);else break}return d}async loadSegments(e,t,i="auto"){$e(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:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await St(u,async function*(){let h=on(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,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=_s(),!h)return;let c=new DataView(h),l=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=l.getChunkEndTime(c,f)}n&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=l.getServerLatencyTimestamps(c);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())$e(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 St(a,async function*(){let n=on(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,n),nn(window,"online").pipe(Zc()).subscribe(()=>{d(),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=_s(),this.failedDownloads=0}catch(n){this.abortActiveSegments(e),Xe(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if($e(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=_s(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:n,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!$e(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?(d,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=_s();let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}: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 d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=Ke(a.mime).parseFeedableSegmentChunk(d,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){let{segment:d}=n;if(n.representationId!==t)continue;if(s.aborted){await a();continue}let h=d.byte.from-i,c=d.byte.to-i,l=c-h+1,p=h<r,m=c<=r;if(!p)continue;let f=Ke(u.mime);if(d.status==="downloading"&&m){d.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+h,l);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(n,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(n.loadedBytes=Math.min(l,r-h),n.loadedBytes>n.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+h+n.feedingBytes,n.loadedBytes-n.feedingBytes),g=n.loadedBytes===l?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(d.status="partially_fed",n.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(n.fedBytes+=g.byteLength,n.fedBytes===l&&this.onSegmentFullyAppended(n,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(re(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:st.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",an(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let a=s instanceof Promise;t||=a,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=(!i&&this.failedDownloads>0?St(this.destroyAbortController.signal,async function*(){let u=on(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(async u=>{if(!u)return;let{init:n,dataView:d,segments:h}=u,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let l=h;this.isLive&&$e(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),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:st.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||re(e))return!1;let r=[],s=0,a=n=>{n.sort((h,c)=>h.from-c.from);let d=[n[0]];for(let h=1;h<n.length;h++){let{from:c,to:l}=n[h],p=d[d.length-1];p.to>=c?p.to=Math.max(p.to,l):d.push(n[h])}return d},u=n=>{if(s>=t)return r;r.push({...n.time}),r=a(r);let d=an(n)?n.size??0:n.byte.to-n.byte.from;s+=d};for(let n of this.segments.values())for(let d of n){let h=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(h||c)&&d.status==="fed"&&u(d)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let d=this.sourceBuffer.buffered.start(n)*1e3,h=this.sourceBuffer.buffered.end(n)*1e3,c=0;for(let l of this.segments.values())for(let p of l)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(d)&&Math.round(p.time.to)>=Math.round(h)&&c++;if(c===this.segments.size){let l={time:{from:d,to:h},url:"",status:"none"};u(l)}}if(r.length&&i){let n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let h of d)h.time.from>=e+n&&h.status==="fed"&&u(h)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,h)=>d||h,!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)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||re(e)?0:le(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let a=0;a<s.length;a++){let u=s.start(a)*1e3,n=s.end(a)*1e3;if(!(n<=i.time.from||u>=i.time.to)){if(u<=i.time.from&&n>=i.time.to){r=void 0;break}n>i.time.from&&n<i.time.to&&(r.from=n),u<i.time.to&&u>i.time.from&&(r.to=u)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let a=Math.round(s.from),u=Math.round(s.to);for(let n=0;n<i.length;n++)if(a>=Math.round(i.start(n)*1e3)&&u<=Math.round(i.end(n)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:st.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(re(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||re(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),n=e.some(h=>h.from-t<=a&&h.to+t>=u),d=e.filter(h=>a>=h.from&&a<h.to-t||u>h.from+t&&u<=h.to);n||(d.length===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:st.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var yt=o=>{let e=new URL(o);return e.searchParams.set("quic","1"),e.toString()};var Ns=o=>{let e=o.get("X-Delivery-Type"),t=o.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as Sr,assertNever as Lu,fromEvent as Ru,merge as ih,now as vr,Subject as li,ValueSubject as un,flattenObject as ci,ErrorCategory as yr,SubscriptionRemovable as rh}from"@vkontakte/videoplayer-shared/evergreen";var Us=o=>{let e=new URL(o);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var js=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new li;this.manifestReceived=new li;this.firstBytesRequested=new li;this.firstBytesReceived=new li;this.lastConnectionType$=new un(void 0);this.lastConnectionReused$=new un(void 0);this.lastRequestFirstBytes$=new un(void 0);this.recoverableError$=new li;this.error$=new li;this.abortAllController=new AbortController;this.subscription=new rh;this.fetchManifest=Sr(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(Hs);return r?(t.log("success",ci({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ci({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Sr(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:d=!1}={}){let h=e,c=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let S=new URL(h,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),h=S.toString();break}default:Lu(t)}this.requestQuic&&(h=yt(h));let p=this.abortAllController.signal,m;if(a){let S=new AbortController;if(m=ih(Ru(this.abortAllController.signal,"abort"),Ru(a,"abort")).subscribe(()=>{try{S.abort()}catch(I){Hs(I)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{S.abort()}catch(I){Hs(I)}p=S.signal}let f=0,b=vr();l.log("startRequest",ci({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:n,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(h,{priority:s,headers:c,signal:p}),y=vr();if(!g)return l.error("error",{message:"No response in request"}),l.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(y-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let S=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:S}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let S=vr(),I={requestStartedAt:b,requestEndedAt:S,duration:S-b};return l.log("endRequest",ci(I)),l.end(),g.arrayBuffer()}let T=g.body;if(u){let S;[T,S]=g.body.tee(),this.throughputEstimator?.trackStream(S,n)}let v=T.getReader(),k,$=parseInt(g.headers.get("content-length")??"",10);Number.isFinite($)&&(k=$),!k&&i&&(k=i.to-i.from+1);let P=k?new Uint8Array(k):new Uint8Array(0),x=!1,M=S=>{this.unsubscribeAbortSubscription(m),x=!0,Hs(S)},E=Sr(p,async function*({done:S,value:I}){if(f===0&&(this.lastRequestFirstBytes$.next(vr()-b),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!S&&I){if(d&&k)P.set(I,f),f+=I.byteLength;else{let W=new Uint8Array(P.length+I.length);W.set(P),W.set(I,P.length),P=W,f+=I.byteLength}r?.(new DataView(P.buffer),f),yield v?.read().then(E,M)}}.bind(this));yield v?.read().then(E,M),this.unsubscribeAbortSubscription(m);let _=vr(),L={failed:x,requestStartedAt:b,requestEndedAt:_,duration:_-b};return x?(l.error("endRequest",ci(L)),l.end(),null):(l.log("endRequest",ci(L)),l.end(),P.buffer)}.bind(this));this.fetchByteRangeRepresentation=Sr(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,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,n=s+1===d,n&&(a=Math.min(d,r),u=Math.max(h,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!c)return null;let l=new DataView(c,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(n)f=new DataView(c,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=Sr(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:Lu(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await fetch(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:yr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:yr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:yr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:yr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:yr.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Hs=o=>{if(!Xe(o))throw o};var at=(o,e,t)=>t*e+(1-t)*o,dn=(o,e)=>o.reduce((t,i)=>t+i,0)/e,Mu=(o,e,t,i)=>{let r=0,s=t,a=dn(o,e),u=e<i?e:i;for(let n=0;n<u;n++)o[s]>a?r++:r--,s=(o.length+s-1)%o.length;return Math.abs(r)===u};import{isNullable as sh,ValueSubject as Du}from"@vkontakte/videoplayer-shared/evergreen";var Tt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Du(e.initial),this.debounced$=new Du(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ge(`raw_${t}`),this.smoothedSeries$=new ge(`smoothed_${t}`),this.reportedSeries$=new ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,a=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<a)&&(sh(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Qs=class extends Tt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=at(this.slow,e,this.params.emaAlphaSlow),this.fast=at(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var qs=class extends Tt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=dn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=at(this.emaSmoothed,e,this.params.emaAlpha);let i=Mu(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ws=class extends Tt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?at(this.smoothed,t,this.params.emaAlpha):t}};var nt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Qs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new qs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Ws({initial:e,label:"liveEdgeDelay",...t})}};var hi=(o,e)=>{o&&o.playbackRate!==e&&(o.playbackRate=e)};import{isNullable as ah,ValueSubject as nh}from"@vkontakte/videoplayer-shared/evergreen";var Tr=class o{constructor(e,t){this.currentRepresentation$=new nh(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(!ah(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(d=>d.time.from<=e&&d.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&&$e(t.segmentReference))}};import{assertNever as Gs}from"@vkontakte/videoplayer-shared/evergreen";var zs=o=>{let{webmDecodingInfo:e}=D.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(o){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Gs(o)}return[t,i]},Bu=({webmCodec:o,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...zs(o),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(D.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...zs(o),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...zs(o),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...zs(o),...s,"HLS","HLS_ONDEMAND"];default:Gs(e)}if(D.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Gs(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Vu=({androidPreferredFormat:o,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],a=[...r,...i],u,n=D.device.isMac&&D.browser.isSafari;if(D.device.isAndroid)switch(o){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=a;break}default:Gs(o)}else D.video.nativeHlsSupported&&!n?u=a:n?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},ln=o=>o?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ys=o=>{if(o.size===0)return;if(o.size===1)return o.values().next().value.split(".").at(0);for(let t of o){let i=t.split(".").at(0);if(i==="opus"||i==="vp09"||i==="av01")return i}return o.values().next().value.split(".").at(0)},Ks=o=>{let e=o.map(i=>pi(i)),{codecs:t}=D.video;return lh().filter(i=>{if(e.includes(i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Xs=o=>{let e=o.map(i=>pi(i)),{codecs:t}=D.video;return ch().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},pi=o=>o.split(".")[0].replace("0",""),lh=()=>["av1","vp9","hev1","avc1"],ch=()=>["opus","mp4a"];var gh=["timeupdate","progress","play","seeked","stalled","waiting"],Sh=["timeupdate","progress","loadeddata","playing","seeked"];var Zs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Fu;this.representationSubscription=new Fu;this.state$=new O("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new It;this.manifestRequested=new It;this.manifestReceived=new It;this.firstBytesRequested=new It;this.firstBytesReceived=new It;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.isActiveLive$=new X(!1);this.isLowLatency$=new X(!1);this.liveDuration$=new X(0);this.liveSeekableDuration$=new X(0);this.liveAvailabilityStartTime$=new X(0);this.liveStreamStatus$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.fetcherRecoverableError$=new It;this.fetcherError$=new It;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new It;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=hn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ne.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=hn(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:Ne.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Fs(e??"",this.manifestUrlString)}catch(n){let d=Cs(e)??{id:"ManifestParsing",category:Ne.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(d)}if(!t)return null;let i=(n,d,h)=>!!(this.element?.canPlayType?.(d)&&Ae()?.isTypeSupported?.(`${d}; codecs="${h}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:d,streamIsUnpublished:h,streamIsAlive:c}=t.live,l=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*l),this.liveDuration$.next((d-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(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:l,codecs:p})=>i(n,l,p));r[n]=h;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let l=h.map(({codecs:p})=>p);n==="audio"&&(a=Xs(l),c=a[0]),n==="video"&&(s=Ks(l),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?c=this.forceVideoCodec:c=s[0]),c&&(r[n]=h.filter(({codecs:p})=>pi(p)===c))}else{let l=new Set(h.map(({codecs:p})=>p));c=Ys(l),c&&(r[n]=h.filter(({codecs:p})=>p.startsWith(c)))}if(n==="video"){let l=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);D.display.isHDR&&l&&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",Er(u)),u}.bind(this));this.initRepresentations=hn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Er({initialVideo:e,initialAudio:t,sourceHls:i})),mi(this.manifest),mi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(ot(l,"error").pipe(Js(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ne.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=ms();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Jt())if(i){let l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.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((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new gr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],xr(t)){let l=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new gr("audio",this.source,l,a),this.bufferManagers.push(this.audioBufferManager)}Tr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Tr(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(_t(...Sh.map(l=>ot(this.element,l))).pipe(bi(l=>this.element?le(this.element.buffered,this.element.currentTime*1e3):0),Ir(),fh(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&n()})).subscribe(this.bufferLength$)),this.representationSubscription.add(_t(ot(this.element,"ended"),this.forceEnded$).subscribe(()=>{n()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ir()).subscribe(p=>this.liveStreamEndTimestamp=mn())),this.subscription.add(ot(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=pn(1e3).subscribe(p=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ot(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(fi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(bi(({isActiveLive:p,isLowLatency:m})=>p&&m),Ir()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||hi(this.element,1)})),this.representationSubscription.add(fi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Js(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(fi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Js(({isLive:p})=>p),Ir((p,m)=>m.bufferLength<p.bufferLength),bi(({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(fi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=p-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(T)>g&&(v=1+Math.sign(T)*y),hi(this.element,v)})),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 l=0;this.representationSubscription.add(fi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(bh(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,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,k=isFinite(p)?p:m,$=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),P=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(P);let x="none";if($?x="active_low_latency":this.isLowLatency$.getValue()&&P?(this.bufferManagers.forEach(M=>M.proceedLowLatencyLive()),x="active_low_latency"):b!==0&&k<y?x="live_forward_buffering":k<y+v&&(x="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),x==="live_forward_buffering"||x==="live_with_target_offset"){let M=l-(y+T),E=this.normolizeLiveOffset(Math.trunc(b+M/f)),_=Math.abs(E-b),L=0;!p||_<=this.tuning.dashCmafLive.offsetCalculationError?L=b:E>0&&_>this.tuning.dashCmafLive.offsetCalculationError&&(L=E),this.manifestUrlString=ee(this.manifestUrlString,L,2)}(x==="live_with_target_offset"||x==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ne.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let d=_t(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(bi(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),h=_t(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(bi(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),c=fi({allBuffersFull:d,someBufferEnded:h}).pipe(Ir(),bi(({allBuffersFull:l,someBufferEnded:p})=>l&&p),Js(l=>l));if(this.representationSubscription.add(_t(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(_t(...this.bufferManagers.map(l=>l.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 l=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{l&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Ne.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let l=[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),$e(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&xr(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=pn(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ne.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new js({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){mi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?mn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){mi(this.element),this.state$.setState("running"),this.subscription.add(_t(...gh.map(e=>ot(this.element,e)),ot(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ne.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ot(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ot(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&ce(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=mn(),s=100,a=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(a);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,n=this.videoBufferManager?.getForwardBufferDuration()??0,d=this.audioBufferManager?.getForwardBufferDuration()??0,h=n<s&&r-a>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&d<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let l=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(l).catch(p=>{this.error$.next({id:"stallIntervalCallback",category:Ne.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:p})}),i.liveLastOffset=l}else{let l=this.element.currentTime*1e3;this.videoBufferManager?.maintain(l),this.audioBufferManager?.maintain(l),i.position=l}this.tracer.log("stallIntervalCallback",Er(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=pn(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ne.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){mi(this.element),mi(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),ce(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Ou(this.element)||Ou(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Er({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){xr(this.element)&&xr(this.source)&&xr(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.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=mh(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,a=[],u=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let d of n.gaps)(r&&d.persistent||n.playingRepresentation$.getValue()===d.representation)&&d.from-u<=s&&d.to+u>s&&(this.element.duration*1e3-d.to<this.tuning.endGapTolerance?a.push(1/0):a.push(d.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,i={...i,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Er(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var ea=class{constructor(e,t){this.fov=e,this.orientation=t}};var ta=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,a=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:a},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Nu=`attribute vec2 a_vertex;
124
124
  attribute vec2 a_texel;
125
125
 
126
126
  varying vec2 v_texel;
@@ -131,7 +131,7 @@ void main(void) {
131
131
  // save texel vector to pass to fragment shader
132
132
  v_texel = a_texel;
133
133
  }
134
- `;var _u=`#ifdef GL_ES
134
+ `;var Uu=`#ifdef GL_ES
135
135
  precision highp float;
136
136
  precision highp int;
137
137
  #else
@@ -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 bi=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 zs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ws(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(Fu,this.gl.VERTEX_SHADER),i=this.createShader(_u,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,o=t-r,d=e+i,l=t+r,p=e-i,c=t+r;return[s,a,u,o,d,l,p,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 Sh,now as Er,once as vh,Subscription as yh,ValueSubject as ln,isNonNullable as Th,safeStorage as cn,filterChanged as Ih}from"@vkontakte/videoplayer-shared/evergreen";var Gs="stalls_manager_metrics",hn="stalls_manager_abr_params",Nu="stalls_manager_default_tuning_abr_params",pn=class{constructor(){this.isSeeked$=new ln(!1);this.isBuffering$=new ln(!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 yh;this.severeStallOccurred$=new ln(!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(hn):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Er(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Er()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Nu)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(hn),this.setStoredData(Nu,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Gs,"[]");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,o)=>u+o.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(Gs,[]),this.setStoredData(hn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:u,stallsMetricsHistoryLength:o}=this.tuning,d=a*Math.min(t/(u*o),1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-d,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-d,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+d,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+d,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+d,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-d,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(cn.get(e)??t)}setStoredData(e,t){cn.set(e,JSON.stringify(t))}removeStoredData(e){cn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Gs,"[]"),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(Gs,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(vh()).subscribe(t=>this.providerStartWatchingTimestamp=Er())),this.subscription.add(this.currentStallDuration$.pipe(Ih()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(Sh(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),l=Er(),p=r&&this.currentStallsCount>=r,c=i&&l-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&l-d>=i+u&&t>=i;(p||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,Th(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Er()-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}))}},Ys=pn;import{combine as Eh,map as xh,observeElementSize as kh,Subscription as Ah,ValueSubject as mn,noop as wh}from"@vkontakte/videoplayer-shared/evergreen";var Ks=class{constructor(){this.subscription=new Ah;this.pipSize$=new mn(void 0);this.videoSize$=new mn(void 0);this.elementSize$=new mn(void 0);this.pictureInPictureWindowRemoveEventListener=wh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(kh(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(Eh({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(xh(({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 Ot=class{constructor(e){this.subscription=new Bh;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ri;this.stallsManager=new Ys;this.elementSizeManager=new Ks;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"),A(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return Lh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new bi(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=ve(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new qs({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;Dh(this.observableVideo)&&(this.observableVideo=Ie(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Uu.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(fn(d=>!!d.length),ju()).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(bn(d=>d.to.state!=="none"),Xs());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(fn(Hu),ju()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(bn(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(ze(this.video,t.isLooped,r)),this.subscription.add(Te(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"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),A(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 l=this.player.getStreams(),p=this.player.getCodecs();if($h(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of l.audio){h.push(Xa(m));let f=[];for(let b of m.representations){let g=xu(b);f.push(g),this.audioTracksMap.set(g,{stream:m,representation:b})}this.audioStreamsMap.set(m,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of l.video){c.push(Ja(h));let m=[];for(let f of h.representations){let b=Eu({...f,streamId:h.id});b&&(m.push(b),this.videoTracksMap.set(b,{stream:h,representation:f}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(c);for(let h of l.text)for(let m of h.representations){let f=ku(h,m);this.textTracksMap.set(f,{stream:h,representation:m})}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)),this.subscription.add(Js(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Rh(this.video,"progress")).pipe(fn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(d)||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[c,h]=p,m=[...this.videoTracksMap.keys()].find(b=>this.videoTracksMap.get(b)?.representation.id===c.id);Hu(m)&&(this.stallsManager.lastVideoTrackSelected=m);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),d==="manifest_ready")await this.player.initRepresentations(c.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",c.id),h){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,b)}},r)),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(Xs()).subscribe(d=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===d);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:c}]=l,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===c.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ja(c));let m=this.player.calculateDurationFromSegments();m&&this.params.output.duration$.next(m/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Xs()).subscribe(d=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===d);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:c}]=l,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===c.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Xa(c))},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(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}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 u=t.playbackState.stateChangeStarted$.pipe(bn(({to:d})=>d==="ready"),Xs());this.subscription.add(Js(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,gn(["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(Js(u,this.player.state$.stateChangeEnded$,gn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=Js(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gn(["init"])).pipe(Mh(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ci:Vi,t=this.params.tuning.useNewAutoSelectVideoTrack?Es:Is,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:Ts,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,d=[...this.videoTracksMap.keys()].find(({id:y})=>y===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(d&&this.videoTracksMap.get(d)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:y})=>y===p.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let m=ae(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(m/Math.min(f,b||1/0),1),E=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=[...this.audioStreamsMap.keys()].find(({id:y})=>y===E?.id)??this.audioStreamsMap.keys().next().value,v=0;if(I){if(d&&!a){let y=e(d,h,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,y?.bitrate??-1/0)}if(l){let y=e(l,h,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,y?.bitrate??-1/0)}}let x=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:g,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}),R=a?x??d:d??x,L=I&&t(R,h,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=this.videoTracksMap.get(R)?.representation,P=L&&this.audioTracksMap.get(L)?.representation;if(k&&P)return[k,P];if(k&&!P&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uu.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),ye(this.video),this.tracer.end()}};var xr=class extends Ot{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 Sn,merge as Qu,filter as qu,filterChanged as zu,isNullable as vn,map as Wu,ValueSubject as yn,isNonNullable as Vh}from"@vkontakte/videoplayer-shared/evergreen";var kr=class extends Ot{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 yn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zu()).subscribe(o=>{let d=i.position$.getValue(),l=i.volume$.getValue(),p=!l.volume||l.muted;!o&&!d&&p?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Wu(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Sn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Wu(({liveBufferTime:o,liveAvailabilityStartTime:d})=>o&&d?o+d:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(qu(o=>Vh(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(Sn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Qu(r.playbackRateState$,new yn(1))}).pipe(qu(({liveStreamStatus:o,liveDuration:d})=>o==="active"&&!!d)).subscribe(({liveDuration:o,playbackRate:d})=>{let l=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||d<1-c||this.video.paused||vn(l)||(t=o-l)})).add(Sn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Qu(r.playbackRateState$,new yn(1))}).pipe(zu((o,d)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===d.liveDuration:o.time===d.time)).subscribe(({time:o,liveDuration:d,playbackRate:l})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||vn(o)||vn(d))return;let h=-1*(d-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let d=Au(o);this.params.output.availableTextTracks$.next([d])}}))}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 op,assertNonNullable as up,debounce as dp,ErrorCategory as dd,filter as Bn,filterChanged as oa,fromEvent as lp,isNonNullable as ld,isNullable as cp,map as Vn,merge as ua,observableFrom as Cn,once as cd,Subscription as hp}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as Ln,assertNonNullable as yi,combine as Ti,ErrorCategory as Ue,filter as sa,filterChanged as Mr,flattenObject as Rr,fromEvent as Je,getTraceSubscriptionMethod as Xh,interval as $n,isNonNullable as Dr,isNullable as od,map as Ii,merge as Ut,now as Mn,Subject as Et,Subscription as Rn,tap as Jh,throttle as ud,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Ch,ErrorCategory as Gu,Subject as Yu}from"@vkontakte/videoplayer-shared/evergreen";var Oh=18,Ku=!1;try{Ku=D.browser.isSafari&&!!D.browser.safariVersion&&D.browser.safariVersion<=Oh}catch(n){console.error(n)}var Tn=class{constructor(e){this.bufferFull$=new Yu;this.error$=new Yu;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:Gu.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)};Ku&&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:Gu.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:Ch(t)}}},Xu=Tn;import{abortable as It,assertNonNullable as ke,ErrorCategory as _t,fromEvent as kn,getExponentialDelay as An,isNonNullable as gi,isNullable as ce,now as ta,once as Hh,Subject as jh,Subscription as Qh,ValueSubject as Nt}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Fh,throttleFn as _h}from"@vkontakte/videoplayer-shared/evergreen";var Ju=({id:n,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?ft(s):void 0)??Fh({width:e,height:t});return u&&{id:n,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},Zu=({id:n,bitrate:e})=>({id:n,bitrate:e}),ed=({language:n,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),td=({language:n,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:n,label:e}),In=({id:n,language:e,label:t,codecs:i,isDefault:r})=>({id:n,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),En=({id:n,language:e,label:t,hdr:i,codecs:r})=>({id:n,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),xn=n=>"url"in n,Le=n=>n.type==="template";var id=n=>{n.sort((t,i)=>t.from-i.from);let e=[n[0]];for(let t=1;t<n.length;t++){let{from:i,to:r}=n[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(n[t])}return e},Ft=(n,e)=>{for(let t of n)if(e(t))return t;return null},rd=n=>{let e=!1,t=_h(()=>{e=!0},n);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Nh,Subscription as Uh}from"@vkontakte/videoplayer-shared/evergreen";var Zs=n=>{let e=[];for(let t=0;t<n.length;t++){let i=Math.floor(n.start(t)*1e3),r=Math.ceil(n.end(t)*1e3);e.push(i,r)}return e};var ea=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Uh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Nh(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!B(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Zs(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],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 Ar=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:d}){this.currentLiveSegmentServerLatency$=new Nt(0);this.currentLowLatencySegmentLength$=new Nt(0);this.currentSegmentLength$=new Nt(0);this.onLastSegment$=new Nt(!1);this.fullyBuffered$=new Nt(!1);this.playingRepresentation$=new Nt(void 0);this.playingRepresentationInit$=new Nt(void 0);this.error$=new jh;this.gaps=[];this.subscription=new Qh;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.switchAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=It(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Xu(this.sourceBuffer),this.sourceBufferBufferedDiff=new ea(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:_t.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 o=Math.min(this.bufferLimit,si(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let d=ae(this.sourceBuffer.buffered,u),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,d<l).catch(p=>{this.handleAsyncError(p,"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);ke(i,"No init buffer for starting representation"),ke(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=It(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);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(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();gi(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=It(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);ke(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ce(s)||ce(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ke(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();gi(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=It(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let d=t.find(c=>c.id===o);d&&this.representations.set(o,d);let l=this.representations.get(o);if(!l||!Le(l.segmentReference))return;let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ke(r);let s=this.segments.get(i);ke(s,"No segments for starting representation");let a=this.initData.get(i);if(ke(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))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=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!d?.live,this.baseUrls=d?.baseUrls??[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),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,It(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ke(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(ce(u)||ce(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),ke(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 o=this.getCurrentPosition();gi(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ce(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ce(e)||ce(this.downloadingRepresentationId)||ce(this.playingRepresentationId)||ce(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||gi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ke(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(l=>e>=l.time.from&&e<l.time.to);gi(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,a=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let l=ae(this.sourceBuffer.buffered,e),p=r?r.time.to+a:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+a&&(s=p)}if(isFinite(this.bufferLimit)&&si(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ae(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")});return}let o=null;if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o?.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))l="high";else{let p=o.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o?.length&&ae(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=i.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-ae(this.sourceBuffer.buffered,e)<a),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;gi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Le(i.segmentReference))return;let r=i.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,o=r?.findIndex(d=>u>=d.time.from+s&&u<=d.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,d)}else{let d=r.slice(o+1);this.segments.set(i.id,[...a,...d])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ke(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Le(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(o=>Math.floor(o.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(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),d=_e(r.segmentTemplateUrl,{segmentTime:o});s.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}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:h,to:m}},f)=>{let b=h<=i&&m>=i,g=h>i||b||f===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+E||r<E&&m-h>=E||m<=i+E;return(c==="none"||c==="partially_ejected"&&g&&I&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(de(this.sourceBuffer.buffered,h)&&de(this.sourceBuffer.buffered,m)))&&g&&I});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,o=0,d=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<a.length&&(u<=l||o<=p);c++){let h=a[c];if(u+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")d.push(h);else break}return d}async loadSegments(e,t,i="auto"){Le(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:u,onProgress:o,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await It(u,async function*(){let l=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,l))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=ta(),!l)return;let p=new DataView(l),c=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(p,f)}o&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(p);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xe(l)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Le(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,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 It(a,async function*(){let o=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,o),kn(window,"online").pipe(Hh()).subscribe(()=>{d(),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=ta(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Xe(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Le(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ta(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:_t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Le(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ta();let p=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:_t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,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:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),l=Ke(a.mime).parseFeedableSegmentChunk(d,this.isLive);l?.byteLength&&(o.status="partially_fed",u.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),u.fedBytes+=l.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 o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:d}=o,l=d.byte.from-i,p=d.byte.to-i,c=p-l+1,h=l<r,m=p<=r;if(h){if(d.status==="downloading"&&m){d.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+l,c);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(o.loadedBytes=Math.min(c,r-l),o.loadedBytes>o.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+l+o.feedingBytes,o.loadedBytes-o.feedingBytes),b=o.loadedBytes===c?f:Ke(u.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(d.status="partially_fed",o.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(o.fedBytes+=b.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(ce(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&D.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(de(this.sourceBuffer.buffered,e.segment.time.from,100)&&de(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:_t.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",xn(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?It(this.destroyAbortController.signal,async function*(){let u=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let c=l;this.isLive&&Le(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:_t.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||ce(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=u=>{if(s>=t)return;r.push({...u.time});let o=xn(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let d=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&o.status==="fed"&&a(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let c of p)["none","partially_ejected"].includes(c.status)&&Math.round(c.time.from)<=Math.round(o)&&Math.round(c.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:o,to:d},url:"",status:"none"};a(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let d of o)d.time.from>=e+u&&d.status==="fed"&&a(d)}return r.length?(r=id(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,d)=>o||d,!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||ce(e)?0:ae(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let a=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let a=i.start(s)*1e3,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))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:_t.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ce(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ce(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Zs(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=!1,d=0;for(let l=0;l<e.length;l+=2){let p=e[l],c=e[l+1];o||(o=p-t<=a&&c+t>=u),(a>=p&&a<c-t||u>p+t&&u<=c)&&(d+=1)}o||(d===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:_t.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 wr,assertNever as sd,fromEvent as ad,merge as qh,now as Pr,Subject as Si,ValueSubject as wn,flattenObject as vi,ErrorCategory as Lr,SubscriptionRemovable as zh}from"@vkontakte/videoplayer-shared/evergreen";var ra=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Si;this.manifestReceived=new Si;this.firstBytesRequested=new Si;this.firstBytesReceived=new Si;this.lastConnectionType$=new wn(void 0);this.lastConnectionReused$=new wn(void 0);this.lastRequestFirstBytes$=new wn(void 0);this.recoverableError$=new Si;this.error$=new Si;this.abortAllController=new AbortController;this.subscription=new zh;this.fetchManifest=wr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=vt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ds(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ia);return r?(t.log("success",vi({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",vi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=wr(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:o=!1,bufferOptimisation:d=!1}={}){let l=e,p=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let S=new URL(l,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),l=S.toString();break}default:sd(t)}this.requestQuic&&(l=vt(l));let h=this.abortAllController.signal,m;if(a){let S=new AbortController;if(m=qh(ad(this.abortAllController.signal,"abort"),ad(a,"abort")).subscribe(()=>{try{S.abort()}catch(T){ia(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{S.abort()}catch(T){ia(T)}h=S.signal}let f=0,b=Pr();c.log("startRequest",vi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:b})),this.firstBytesRequested.next();let g=yield this.doFetch(l,{priority:s,headers:p,signal:h}),E=Pr();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(E-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let S=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:S}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let S=Pr(),T={requestStartedAt:b,requestEndedAt:S,duration:S-b};return c.log("endRequest",vi(T)),c.end(),g.arrayBuffer()}let I=g.body;if(u){let S;[I,S]=g.body.tee(),this.throughputEstimator?.trackStream(S,o)}let v=I.getReader(),x,R=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(R)&&(x=R),!x&&i&&(x=i.to-i.from+1);let L=x?new Uint8Array(x):new Uint8Array(0),k=!1,P=S=>{this.unsubscribeAbortSubscription(m),k=!0,ia(S)},y=wr(h,async function*({done:S,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(Pr()-b),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!S&&T){if(d&&x)L.set(T,f),f+=T.byteLength;else{let z=new Uint8Array(L.length+T.length);z.set(L),z.set(T,L.length),L=z,f+=T.byteLength}r?.(new DataView(L.buffer),f),yield v?.read().then(y,P)}}.bind(this));yield v?.read().then(y,P),this.unsubscribeAbortSubscription(m);let _=Pr(),$={failed:k,requestStartedAt:b,requestEndedAt:_,duration:_-b};return k?(c.error("endRequest",vi($)),c.end(),null):(c.log("endRequest",vi($)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=wr(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,o=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,o=s+1===d,o&&(a=Math.min(d,r),u=Math.max(l,s))),a=Math.min(a,0);let p=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!p)return null;let c=new DataView(p,r-a,s-a+1);if(!t.validateData(c))throw new Error("Invalid media file");let h=t.parseInit(c),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(o)f=new DataView(p,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,h,m);return{init:h,dataView:new DataView(p),segments:b}}.bind(this));this.fetchTemplateRepresentation=wr(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}=Rs(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:sd(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:Lr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Lr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Lr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Lr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Lr.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ia=n=>{if(!Xe(n))throw n};import{isNullable as Wh,ValueSubject as Gh}from"@vkontakte/videoplayer-shared/evergreen";var $r=class n{constructor(e,t){this.currentRepresentation$=new Gh(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(!Wh(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 o=r.segments.find(d=>d.time.from<=e&&d.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=n.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>n.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Le(t.segmentReference))}};var Zh=["progress","play","seeked","stalled","waiting"],ep=["timeupdate","progress","loadeddata","playing","seeked"];var aa=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Rn;this.representationSubscription=new Rn;this.state$=new O("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new Et;this.manifestRequested=new Et;this.manifestReceived=new Et;this.firstBytesRequested=new Et;this.firstBytesReceived=new Et;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new Et;this.fetcherError$=new Et;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Et;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=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category: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(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ue.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=$s(e??"",this.manifestUrlString)}catch(o){let d=Ps(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(d)}if(!t)return null;let i=(o,d,l)=>!!(this.element?.canPlayType?.(d)&&we()?.isTypeSupported?.(`${d}; codecs="${l}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:d,streamIsUnpublished:l,streamIsAlive:p}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((d-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=l?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let o of["video","audio"]){let l=t.streams[o].filter(({mime:c,codecs:h})=>i(o,c,h));r[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:h})=>h);o==="audio"&&(a=js(c),p=a[0]),o==="video"&&(s=Hs(c),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=l.filter(({codecs:h})=>hi(h)===p))}else{let c=new Set(l.map(({codecs:h})=>h));p=Us(c),p&&(r[o]=l.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,h=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);D.display.isHDR&&c&&h?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",Rr(u)),u}.bind(this));this.initRepresentations=Ln(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Rr({initialVideo:e,initialAudio:t,sourceHls:i})),yi(this.manifest),yi(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Rn,this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Je(c,"error").pipe(sa(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ue.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=as();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),Yt())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,h)=>[...c,...h.representations],[]);if(this.videoBufferManager=new Ar("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],Dr(t)){let c=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ar("audio",this.source,c,a),this.bufferManagers.push(this.audioBufferManager)}$r.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new $r(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 o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ut(...ep.map(c=>Je(this.element,c))).pipe(Ii(c=>this.element?ae(this.element.buffered,this.element.currentTime*1e3):0),Mr(),Jh(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ut(Je(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Mr()).subscribe(h=>this.liveStreamEndTimestamp=Mn())),this.subscription.add(Je(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=$n(1e3).subscribe(h=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Je(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ti({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ii(({isActiveLive:h,isLowLatency:m})=>h&&m),Mr()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ci(this.element,1)})),this.representationSubscription.add(Ti({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(sa(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Ti({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(sa(({isLive:h})=>h),Mr((h,m)=>m.bufferLength<h.bufferLength),Ii(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let b=pt(this.manifestUrlString,2);return(h/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ti({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(I)>g&&(v=1+Math.sign(I)*E),ci(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(Ti({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ud(1e3)).subscribe(async({liveLoadBufferLength:h,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,E=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,x=isFinite(h)?h:m,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let k="none";if(R?k="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),k="active_low_latency"):b!==0&&x<E?k="live_forward_buffering":x<E+v&&(k="live_with_target_offset"),isFinite(h)&&(c=h>c?h:c),k==="live_forward_buffering"||k==="live_with_target_offset"){let P=c-(E+I),y=this.normolizeLiveOffset(Math.trunc(b+P/f)),_=Math.abs(y-b),$=0;!h||_<=this.tuning.dashCmafLive.offsetCalculationError?$=b:y>0&&_>this.tuning.dashCmafLive.offsetCalculationError&&($=y),this.manifestUrlString=ee(this.manifestUrlString,$,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(c=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Ue.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let d=Ut(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Ii(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=Ut(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Ii(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=Ti({allBuffersFull:d,someBufferEnded:l}).pipe(Mr(),Ii(({allBuffersFull:c,someBufferEnded:h})=>c&&h),sa(c=>c));if(this.representationSubscription.add(Ut(this.forceEnded$,p).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(Ut(...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(h=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();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),h()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(h=>h.representations).flatMap(h=>{let m=[];return h.duration&&m.push(h.duration),Le(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&Dr(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=$n(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category: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 ra({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()}async seekLive(e){yi(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Mn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){yi(this.element),this.state$.setState("running");let e=Je(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(ud(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Ut(...Zh.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.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&de(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 o=this.audioBufferManager?.lastDataObtainedTimestamp??0,d=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,p=d<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<a&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:Ue.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",Rr(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=$n(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){yi(this.element),yi(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),de(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(od(this.element)||od(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Rr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Dr(this.element)&&Dr(this.source)&&Dr(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.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=Xh(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 o of this.bufferManagers)for(let d of o.gaps)(d.persistent||o.playingRepresentation$.getValue()===d.representation)&&d.from-u<=s&&d.to+u>s&&(this.element.duration*1e3-d.to<this.tuning.endGapTolerance?a=1/0:(a===null||d.to>a)&&(a=d.to));if(a!==null){let o=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",Rr({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as tp,map as ip,observeElementSize as rp,Subscription as sp,ValueSubject as Dn,noop as ap}from"@vkontakte/videoplayer-shared/evergreen";var na=class{constructor(){this.subscription=new sp;this.pipSize$=new Dn(void 0);this.videoSize$=new Dn(void 0);this.elementSize$=new Dn(void 0);this.pictureInPictureWindowRemoveEventListener=ap}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(rp(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(tp({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ip(({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 Ht=class{constructor(e){this.subscription=new hp;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ri;this.stallsManager=new Ys;this.elementSizeManager=new na;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"),A(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return op(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new bi(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=ve(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new aa({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;cp(this.observableVideo)&&(this.observableVideo=Ie(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:dd.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(Bn(p=>!!p.length),cd()).subscribe(p=>{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:p})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Vn(p=>p.to.state!=="none"),oa());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(Bn(ld),cd()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Vn(p=>p.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(Te(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"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),A(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:p})=>{if(p==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),h=this.player.getCodecs();if(up(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of c.audio){f.push(In(b));let g=[];for(let E of b.representations){let I=Zu(E);g.push(I),this.audioTracksMap.set(I,{stream:b,representation:E})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of c.video){m.push(En(f));let b=[];for(let g of f.representations){let E=Ju({...g,streamId:f.id});E&&(b.push(E),this.videoTracksMap.set(E,{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=ed(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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else p==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&rd(u)||null;this.subscription.add(ua(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$,lp(this.video,"progress")).pipe(Bn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let p=this.player.state$.getState(),c=this.player.state$.getTransition();if(p!=="manifest_ready"&&p!=="running"||c||p==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let f=Ft(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===h.id);ld(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),p==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:p})=>{this.scene3D&&p&&this.scene3D.pointCameraTo(p.x,p.y)})),this.subscription.add(this.elementSizeManager.subscribe(p=>{this.scene3D&&p&&this.scene3D.setViewportSize(p.width,p.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(oa()).subscribe(p=>{let c=Ft(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===p);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{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(h),e.currentVideoStream$.next(En(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(oa()).subscribe(p=>{let c=Ft(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===p);if(!c){e.currentAudioStream$.next(void 0);return}let[h,{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(In(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(p=>{if(p?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(p),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 d=t.playbackState.stateChangeStarted$.pipe(Vn(({to:p})=>p==="ready"),oa());this.subscription.add(ua(d,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Cn(["init"])).subscribe(()=>{let p=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(ua(d,this.player.state$.stateChangeEnded$,Cn(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=ua(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Cn(["init"])).pipe(dp(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Ci:Vi,t=this.params.tuning.useNewAutoSelectVideoTrack?Es:Is,i=this.params.tuning.useNewAutoSelectVideoTrack?Ye:Ts,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Ft(this.videoTracksMap.keys(),k=>k.id===u),d=s.currentVideoTrack$.getValue(),l=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let p=Ft(this.videoStreamsMap.keys(),k=>k.id===l.id),c=p&&this.videoStreamsMap.get(p);if(!c)return;let h=ae(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(h/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),E=g?.id&&Ft(this.audioStreamsMap.keys(),k=>k.id===g.id)||this.audioStreamsMap.keys().next().value,I=0;if(E){if(o&&!a){let k=e(o,c,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,k?.bitrate??-1/0)}if(d){let k=e(d,c,this.audioStreamsMap.get(E)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,k?.bitrate??-1/0)}}let v=o;(a||!v)&&(v=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:I,forwardBufferHealth:b,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let x=E&&t(v,c,this.audioStreamsMap.get(E)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=this.videoTracksMap.get(v)?.representation,L=x&&this.audioTracksMap.get(x)?.representation;R&&L?(this.selectedRepresentations.video=R,this.selectedRepresentations.audio=L):R&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=R,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dd.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),ye(this.video),this.tracer.end()}};var Br=class extends Ht{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 On,merge as hd,filter as pd,filterChanged as md,isNullable as Fn,map as fd,ValueSubject as _n,isNonNullable as pp}from"@vkontakte/videoplayer-shared/evergreen";var Vr=class extends Ht{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 _n(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(md()).subscribe(o=>{let d=i.position$.getValue(),l=i.volume$.getValue(),p=!l.volume||l.muted;!o&&!d&&p?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(fd(o=>o.to)).subscribe(this.player.isLowLatency$)).add(On({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fd(({liveBufferTime:o,liveAvailabilityStartTime:d})=>o&&d?o+d:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(pd(o=>pp(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add(On({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:hd(r.playbackRateState$,new _n(1))}).pipe(pd(({liveStreamStatus:o,liveDuration:d})=>o==="active"&&!!d)).subscribe(({liveDuration:o,playbackRate:d})=>{let l=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;p||d<1-c||this.video.paused||Fn(l)||(t=o-l)})).add(On({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:hd(r.playbackRateState$,new _n(1))}).pipe(md((o,d)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===d.liveDuration:o.time===d.time)).subscribe(({time:o,liveDuration:d,playbackRate:l})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&l>=1-c||Fn(o)||Fn(d))return;let h=-1*(d-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let d=td(o);this.params.output.availableTextTracks$.next([d])}}))}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 bd="X-Playback-Duration",Nn=async n=>{let e=await fetch(n),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(bd)?parseInt(e.headers.get(bd),10):void 0};import{assertNever as xp,combine as kp,debounce as Ap,ErrorCategory as ca,filter as wp,filterChanged as Pp,isNonNullable as vd,isNullable as ha,map as yd,merge as Lp,observableFrom as $p,Subscription as Mp,ValueSubject as Hn,VideoQuality as Rp}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as mp,getExponentialDelay as fp}from"@vkontakte/videoplayer-shared/evergreen";var bp=n=>{let e=null;if(n.QUALITY&&(e=ft(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=mp({width:t,height:i})}return e??null},gp=(n,e)=>{let t=n.split(`
178
- `),i=[],r=[];for(let s=0;s<t.length;s++){let a=t[s],u=a.match(/^#EXT-X-STREAM-INF:(.+)/),o=a.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!o)){if(u){let d=Object.fromEntries(u[1].split(",").map(b=>b.split("="))),l=d.QUALITY??`stream-${d.BANDWIDTH}`,p=bp(d),c;d.BANDWIDTH&&(c=parseInt(d.BANDWIDTH,10)/1e3||void 0),!c&&d["AVERAGE-BANDWIDTH"]&&(c=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,m;if(d.RESOLUTION){let[b,g]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();p&&i.push({id:l,quality:p,url:f,bandwidth:c,size:m,fps:h})}if(o){let d=Object.fromEntries(o[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),l=d.URI?.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,c=d.NAME;l&&p&&r.push({type:"internal",id:p,label:c,language:p,url:l,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Sp=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),Un=0,gd=async(n,e=n,t,i)=>{let s=await(await fetch(n,i)).text();Un+=1;try{let{qualityManifests:a,textTracks:u}=gp(s,e);return{qualityManifests:a,textTracks:u}}catch{if(Un<=t.manifestRetryMaxCount)return await Sp(fp(Un-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),gd(n,e,t)}return{qualityManifests:[],textTracks:[]}},da=gd;import{isNonNullable as vp,Subscription as yp,throttle as Tp,ValueSubject as Sd,Subject as Ip,ErrorCategory as Ep}from"@vkontakte/videoplayer-shared/evergreen";var la=class{constructor(e,t,i,r,s){this.subscription=new yp;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Sd(null);this.getCurrentTime$=new Sd(null);this.error$=new Ip;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(Tp(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 o=r[++a],d=new URL(o,t).toString(),l=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+l},url:d}),s=s+l,!i.segmentStartTime){let p=new Date(i.vkStartTime).valueOf(),c=new Date(i.programDateTime).valueOf();i.segmentStartTime=c-p}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 o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let d=new Date(o);d.setMilliseconds(0),s=d.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(vp(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:Ep.WTF,thrown:t,message:e})}};var Cr=class{constructor(e){this.subscription=new Mp;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Hn([]);this.liveOffset=new Rt;this.manifestStartTime$=new Hn(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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position&&d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else r?.to==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return xp(t)}};this.params=e,this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Rp.INVARIANT,url:this.params.source.url};let t=(i,r)=>da(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 la(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:ca.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:ca.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Hn(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(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:ca.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Ie(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,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(Te(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"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(Pp(),yd(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&vd(d.to)){let p=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let c=this.manifests$.getValue().find(h=>h.id===p);c&&(this.params.output.currentVideoTrack$.next(c),this.params.output.hostname$.next(ue(c.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.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(kp({startTime:this.manifestStartTime$.pipe(wp(vd)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe(yd(u=>u.map(({id:o,quality:d,size:l,bandwidth:p,fps:c})=>({id:o,quality:d,size:l,fps:c,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Lp(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,$p(["init"])).pipe(Ap(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),ye(this.video)}prepare(){let e=this.selectManifest();if(ha(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:o}=t?.to??i??{};for(let[d,l]of[[u,"mq"],[o,"lq"]]){let p=String(parseFloat(d||""));l&&d&&r.searchParams.set(l,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=ee(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),Nn(a).then(u=>{if(!ha(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(ha(o)||!isFinite(o))&&fetch(a).then(d=>d.text()).then(d=>{let l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(l){let p=new URL(l,a).toString();Nn(p).then(c=>{ha(c)||this.maxSeekBackTime$.next(c)})}}).catch(()=>{})}})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ca.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ee(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as Dp,debounce as Bp,ErrorCategory as jn,fromEvent as Qn,isNonNullable as Vp,isNullable as Cp,map as Td,merge as Id,observableFrom as Ed,Subscription as Op,ValueSubject as Fp,VideoQuality as _p}from"@vkontakte/videoplayer-shared/evergreen";var Or=class{constructor(e){this.subscription=new Op;this.videoState=new O("stopped");this.manifests$=new Fp([]);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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:p}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Dp(t)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=ve(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_p.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),da(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.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:jn.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(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:jn.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Ie(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));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(Td(u=>u.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(Te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Vp(d.to)){let h=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let m=this.manifests$.getValue().find(f=>f.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(ue(m.url)))}let p=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(p!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(p),h.playbackRate=p)}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(Td(u=>u.map(({id:o,quality:d,size:l,bandwidth:p,fps:c})=>({id:o,quality:d,size:l,fps:c,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i)),!D.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(Id(Qn(u,"addtrack"),Qn(u,"removetrack"),Qn(u,"change"),Ed(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let a=Id(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ed(["init"])).pipe(Bp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){let e=this.selectManifest();if(Cp(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,o]of[[s,"mq"],[a,"lq"]]){let d=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Np,assertNonNullable as xd,debounce as Up,ErrorCategory as kd,isHigherOrEqual as Hp,isLowerOrEqual as jp,isNonNullable as Qp,merge as qp,observableFrom as zp,Subscription as Wp,map as Gp}from"@vkontakte/videoplayer-shared/evergreen";var Fr=class{constructor(e){this.subscription=new Wp;this.videoState=new O("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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),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:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return Np(e)}};this.params=e,this.video=ve(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:kd.WTF,message:"MpegProvider internal logic error",thrown:u})},r=Ie(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,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(Gp(u=>u.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),this.subscription.add(Te(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"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&Qp(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(o!==d){let l=this.params.output.element$.getValue();l&&(this.params.desiredState.playbackRate.setState(o),l.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=qp(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,zp(["init"])).pipe(Up(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),ye(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;xd(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];xd(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=vt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kd.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=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let l=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:d,abrLogger:this.params.dependencies.abrLogger});t(l)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(d=>d.track);if(!r||!s||Jt(e,a[0].quality,a.at(-1)?.quality)){i();return}let u=e.max?jp(r,e.max):!0,o=e.min?Hp(r,e.min):!0;u&&o||i(e)}};import{assertNever as wd,debounce as Jp,merge as Pd,observableFrom as Zp,Subscription as em,map as Ld,ValueSubject as tm,ErrorCategory as zn,VideoQuality as im}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Yp}from"@vkontakte/videoplayer-shared/evergreen";var Ad=["stun:videostun.mycdn.me:80"],Kp=1e3,Xp=3,qn=()=>null,pa=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:Ad}]};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:Yp.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),Kp)}normalizeOptions(e={}){let t={stunServerList:Ad,maxRetryNumber:Xp,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var _r=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new tm(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return wd(e)}};this.subscription=new em,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ve(e.container,e.tuning),this.liveStreamClient=new pa(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),ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:zn.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(Pd(this.videoState.stateChangeStarted$.pipe(Ld(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ld(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(a)}`})}));let r=Ie(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(Te(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 wd(a.to)}},i)).add(Pd(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Zp(["init"])).pipe(Jp(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:im.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:zn.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zn.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ei=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 Nr,assertNonNullable as xt,ErrorCategory as ma,filter as Vd,isNonNullable as Cd,isNullable as dm,map as lm,merge as cm,once as hm,Subject as te,Subscription as Od,ValueSubject as V,flattenObject as Wn}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as rm,map as $d,Subscription as sm,Subject as am}from"@vkontakte/videoplayer-shared/evergreen";var Md=n=>new rm(e=>{let t=new sm,i=n.desiredPlaybackState$.stateChangeStarted$.pipe($d(({from:d,to:l})=>`${d}-${l}`)),r=n.desiredPlaybackState$.stateChangeEnded$,s=n.providerChanged$.pipe($d(({type:d})=>d!==void 0)),a=new am,u=0,o="unknown";return t.add(i.subscribe(d=>{u&&window.clearTimeout(u),o=d,u=window.setTimeout(()=>a.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(d=>{u&&(window.clearTimeout(u),u=0,d&&(u=window.setTimeout(()=>a.next(o),n.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as nm,Subscription as om,combine as um,filter as Dd,once as Bd}from"@vkontakte/videoplayer-shared/evergreen";function Rd(){return new(window.AudioContext||window.webkitAudioContext)}var xi=class n{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new om;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Dd(s=>!!s.type),Bd()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){D.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(um({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Dd(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Bd()).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=Rd();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:n.errorId,category:nm.VIDEO_PIPELINE,message:e?.message??`${n.errorId} exception`,thrown:e})}};var pm={chunkDuration:5e3,maxParallelRequests:5},Ur=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new te;this.noAvailableProvidersError$=new te;this.volumeMultiplierError$=new te;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 te,fetcherError$:new te,fetcherRecoverableError$:new te,warning$:new te,willSeekEvent$:new te,soundProhibitedEvent$:new te,seekedEvent$:new te,loopedEvent$:new te,endedEvent$:new te,manifestRequested$:new te,manifestReceived$:new te,firstBytesRequested$:new te,firstBytesReceived$:new te,firstBytesEvent$:new te,loadedMetadataEvent$:new te,firstFrameEvent$:new te,canplay$:new te,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 te,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 Od;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=La([...Du(this.params.tuning),...Ru(this.params.tuning)]).filter(d=>Cd(e.sources[d])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(d=>!r.includes(d)),...t.filter(d=>r.includes(d))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Wn(s)),this.screenFormatsIterator=new Ei(s);let a=[...an(!0),...an(!1)];this.chromecastFormatsIterator=new Ei(a.filter(d=>Cd(e.sources[d]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&xi.isSupported()&&(this.volumeMultiplierManager=new xi(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 Ei(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(dm(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:ma.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 Nr(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 o=this.applyFailoverHost(t[e]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return xt(o),this.params.tuning.useNewDashProvider?new Br({...u,source:o,sourceHls:d,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new xr({...u,source:o,sourceHls:d,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return xt(o),this.params.tuning.useNewDashProvider?new Vr({...u,source:o}):new kr({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return xt(o),new Or({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return xt(o),new Cr({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return xt(o),new Fr({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return xt(o),new ou({...u,source:o,config:{...pm,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return xt(o),new _r({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Nr(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 xt(u),new $i({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 Nr(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Nr(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 Nr(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 Od,t=!1,i=0;return e.add(cm(this.providerOutput.error$.pipe(Vd(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Md({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(lm(r=>({id:`ProviderHangup:${r}`,category:ma.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(Vd(({to:s})=>s==="playing"),hm()).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===ma.NETWORK,o=r.category===ma.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!o,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,c=d&&!o&&(u&&t||!l);a={...a,isNetworkError:u,isFatalError:o,haveFailoverHost:d,tryFailover:c,canReinitProvider:l},l?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Wn(a)):this.tracer.error("providerError",Wn(a))})),e}};import{fromEvent as fa,once as mm,combine as fm,Subscription as Fd,ValueSubject as Gn,map as bm,filter as gm,isNonNullable as ba,now as $e,safeStorage as Yn}from"@vkontakte/videoplayer-shared/evergreen";var Sm=5e3,_d="one_video_throughput",Nd="one_video_rtt",Hr=window.navigator.connection,Ud=()=>{let n=Hr?.downlink;if(ba(n)&&n!==10)return n*1e3},Hd=()=>{let n=Hr?.rtt;if(ba(n)&&n!==3e3)return n},jd=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Kn=class n{constructor(e){this.subscription=new Fd;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=n.load(_d)||(e.useBrowserEstimation?Ud():void 0)||Sm,i=n.load(Nd)??(e.useBrowserEstimation?Hd():void 0)??0;if(this.throughput$=new Gn(t),this.rtt$=new Gn(i),this.rttAdjustedThroughput$=new Gn(jd(t,i,e.rttPenaltyRequestSize)),this.throughput=nt.getSmoothedValue(t,-1,e),this.rtt=nt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=Ud();a&&this.throughput.next(a);let u=Hd();ba(u)&&this.rtt.next(u)};Hr&&"onchange"in Hr&&this.subscription.add(fa(Hr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Yn.set(_d,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Yn.set(Nd,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(fm({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(bm(({throughput:r,rtt:s})=>jd(r,s,e.rttPenaltyRequestSize)),gm(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=$e(),r=new Fd;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(fa(e,"progress").pipe(mm()).subscribe(s=>{t=s.loaded,i=$e()}));break;case 1:case 0:r.add(fa(e,"loadstart").subscribe(()=>{t=0,i=$e()}));break}r.add(fa(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,u=$e(),o=a-t,d=u-i;this.addRawSpeed(o,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=$e(),a=0,u=$e(),o=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:p})=>{if(l)!t&&this.addRawSpeed(r,$e()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let c=$e();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=p.byteLength,s=$e()}else a+=p.byteLength;u=$e()}else r+=p.byteLength,a+=p.byteLength,a>=this.tuningConfig.streamMinSampleSize&&$e()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,$e()-u,this.concurrentDownloads.size),a=0,u=$e());await i?.read().then(d,o)}};this.concurrentDownloads.add(e),i?.read().then(d,o)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Yn.get(e);if(ba(t))return parseInt(t,10)??void 0}},Qd=Kn;import{fillWithDefault as vm,VideoQuality as ga}from"@vkontakte/videoplayer-shared/evergreen";var qd={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:ga.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:ga.Q_720P,trafficSavingLimit:ga.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:ga.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1},dashCmafLive:{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,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},zd=n=>({...vm(n,qd),configName:[...n.configName??[],...qd.configName]});import{assertNonNullable as Sa,combine as ut,ErrorCategory as va,filter as C,filterChanged as W,fromEvent as Jn,isNonNullable as Kd,isNullable as Am,Logger as wm,map as q,mapTo as Xd,merge as kt,now as ya,once as F,Subject as Q,Subscription as Jd,tap as Zn,ValueSubject as w,isHigher as Pm,isInvariantQuality as Zd,flattenObject as At,throttle as eo,getTraceSubscriptionMethod as el,TracerFactory as Lm,InternalsExposure as $m}from"@vkontakte/videoplayer-shared/evergreen";import{merge as ym,map as Tm,filter as Wd,isNonNullable as Im}from"@vkontakte/videoplayer-shared/evergreen";var Xn=({seekState:n,position$:e})=>ym(n.stateChangeEnded$.pipe(Tm(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Wd(Im)),e.pipe(Wd(()=>n.getState().state==="none")));import{assertNonNullable as Em}from"@vkontakte/videoplayer-shared/evergreen";var Gd=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return Em(e,`Wrong container or containerId {${n.container}}`),e};import{filter as xm,once as km}from"@vkontakte/videoplayer-shared/evergreen";var Yd=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(xm(r=>r.length>0),km()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t?.getValue().find(i))&&e.startTransitionTo(n)};var Ta=class{constructor(e={configName:[]},t=Lm.createRootTracer(!1)){this.subscription=new Jd;this.logger=new wm;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new w(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new w(void 0),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),predefinedQualityLimitType$:new w("unknown"),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),isLiveEnded$:new w(null),canPlayLiveTailBuffer$:new w(!1),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willReady$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,fetcherRecoverableError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,manifestRequested$:new Q,manifestReceived$:new Q,firstBytesRequested$:new Q,firstBytesReceived$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q,fetcherError$:new Q,severeStallOccured$:new Q};this.experimental={element$:new w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:Fo,getCurrentTime$:new w(null)};if(this.initLogs(),this.tuning=zd(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(i=>i.setSuppressErrors(!0)),Object.values(this.events).forEach(i=>i.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new es({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Qd(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new $m("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let a=Reflect.get(i,r,s);return typeof a!="function"?a:(...u)=>{try{return a.apply(i,u)}catch(o){let d=u.map(c=>JSON.stringify(c,(h,m)=>{let f=typeof m;return["number","string","boolean"].includes(f)?m:m===null?null:`<${f}>`})),l=`Player.${String(r)}`,p=`Exception calling ${l} (${d.join(", ")})`;throw this.events.fatalError$.next({id:l,category:va.WTF,message:p,thrown:o}),o}}}})}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",At(a)),this.domContainer=Gd(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ur({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(C(s=>!!s),F()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Jn(document,"visibilitychange").pipe(F()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{Sa(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(C(i=>i.length>0),F()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",At(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{Sa(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",At(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{Yd(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(C(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Am(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Kd(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(kt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ua(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(C(({from:e})=>e==="stopped"),F()).subscribe(()=>{this.initedAt=ya(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",At(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:va.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(F()).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",At(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(q(a=>a.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ut({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(q(({availableVideoTracks:a,currentVideoStream:u})=>a.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,d)=>Zd(o)?1:Zd(d)?-1:Pm(d,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let u={};for(let o of a)o.fps&&(u[o.quality]=o.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(C(a=>Kd(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(q(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(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:kt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(a=>a.to),W(),q(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:Xn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(q(({isLive:a,position:u,isLowLatency:o})=>{let d=this.getActiveLiveDelay(o);return a&&Math.abs(u)<d/1e3}),W(),Zn(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(q(({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(q(({isLive:a,position:u,duration:o})=>a&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),W(),Zn(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(q(a=>a.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(q(a=>a.volume),W()).subscribe(this.info.volume$)).add(Xn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(kt(e.providerOutput.endedEvent$.pipe(Xd(!0)),e.providerOutput.seekedEvent$.pipe(Xd(!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(q(a=>({id:a?`No${a}`:"NoProviders",category:va.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(F()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(F()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(F()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(F()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(F(),q(a=>a??ya()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),q(()=>ya()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),q(()=>ya()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new w(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(C(({to:a})=>a==="playing"),F()).subscribe(()=>i.next(!1)));let r=0,s=kt(e.providerOutput.isBuffering$,t,i).pipe(q(()=>{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(kt(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(kt(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(),o=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),p;l==="CONNECTED"?p="second_screen":o?d?a?p="pip":u?p="fullscreen":p="inline":p="invisible":p="none",this.info.surface$.getValue()!==p&&this.info.surface$.next(p)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Jd;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(C(i=>i.length>0),F()).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(kt(this.desiredState.videoTrack.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(q(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Sa(this.providerContainer),Sa(e),Oo(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Co(t)),this.providerContainer.current$.subscribe(({type:t})=>Bi("provider",t)),e.duration$.subscribe(t=>Bi("duration",t)),e.availableVideoTracks$.pipe(C(t=>!!t.length),F()).subscribe(t=>Bi("tracks",t)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe(q(t=>t?.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(t=>this.subscription.add(t)),Bi("codecs",D.video.supportedCodecs)}initTracerSubscription(){let e=el(this.tracer.log.bind(this.tracer)),t=el(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(C(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(C(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(C(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(C(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(C(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),eo(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),C(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),C(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(),C(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ut({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(C(({throughputEstimation:i,rtt:r})=>!!i&&!!r),eo(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),C(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:va.DOM,message:String(r)})})};this.subscription.add(kt(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",At({quality:t,availableTracks:At(e),track:At(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&&!Ui()}};import{Subscription as xD,Observable as kD,Subject as AD,ValueSubject as wD,VideoQuality as PD}from"@vkontakte/videoplayer-shared/evergreen";var LD=`@vkontakte/videoplayer-core@${io}`;export{Xr as ChromecastState,xa as HttpConnectionType,kD as Observable,Se as PlaybackState,Ta as Player,Jr as PredefinedQualityLimits,LD as SDK_VERSION,AD as Subject,xD as Subscription,ka as Surface,io as VERSION,wD as ValueSubject,et as VideoFormat,PD as VideoQuality,yl as areValidLiveRecordSources,D as clientChecker,Li as isMobile};
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(Nu,this.gl.VERTEX_SHADER),i=this.createShader(Uu,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,d=e+i,h=t+r,c=e-i,l=t+r;return[s,a,u,n,d,h,c,l]}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 Th,now as kr,once as Ih,Subscription as Eh,ValueSubject as fn,isNonNullable as xh,safeStorage as bn,filterChanged as kh}from"@vkontakte/videoplayer-shared/evergreen";var ia="stalls_manager_metrics",gn="stalls_manager_abr_params",Hu="stalls_manager_default_tuning_abr_params",Sn=class{constructor(){this.isSeeked$=new fn(!1);this.isBuffering$=new fn(!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 Eh;this.severeStallOccurred$=new fn(!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(gn):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=kr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(kr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Hu)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(gn),this.setStoredData(Hu,{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(gn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:u,stallsMetricsHistoryLength:n}=this.tuning,d=a*Math.min(t/(u*n),1),h=this.abrTuningParams;return e<i-r?h={bitrateFactorAtEmptyBuffer:Math.max(h.bitrateFactorAtEmptyBuffer-d,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(h.bitrateFactorAtFullBuffer-d,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(h.containerSizeFactor+d,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(h={bitrateFactorAtEmptyBuffer:Math.min(h.bitrateFactorAtEmptyBuffer+d,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(h.bitrateFactorAtFullBuffer+d,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(h.containerSizeFactor-d,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(bn.get(e)??t)}setStoredData(e,t){bn.set(e,JSON.stringify(t))}removeStoredData(e){bn.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(Ih()).subscribe(t=>this.providerStartWatchingTimestamp=kr())),this.subscription.add(this.currentStallDuration$.pipe(kh()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(Th(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),n=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),h=kr(),c=r&&this.currentStallsCount>=r,l=i&&h-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&h-d>=i+u&&t>=i;(c||l)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,xh(this.lastUniqueVideoTrackSelected.bitrate)&&n>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&kr()-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=Sn;import{combine as wh,map as Ah,observeElementSize as $h,Subscription as Ph,ValueSubject as vn,noop as Lh}from"@vkontakte/videoplayer-shared/evergreen";var sa=class{constructor(){this.subscription=new Ph;this.pipSize$=new vn(void 0);this.videoSize$=new vn(void 0);this.elementSize$=new vn(void 0);this.pictureInPictureWindowRemoveEventListener=Lh}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add($h(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(Ah(({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 Nt=class{constructor(e){this.subscription=new Fh;this.videoState=new O("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.unmuteAfterBrowserResetsHappened=new Nh(!1);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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(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=Ie(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(de(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:ju.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(wr(c=>!!c.length),na()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Si(c=>c.to.state!=="none"),Ar());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(wr(Qu),na()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Si(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(me(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(t.volume.stateChangeStarted$.pipe(Si(()=>{let c=t.volume.getTransition(),l=this.params.output.element$.getValue();return!l||!c?!1:!c.to.muted&&l.muted}),wr(c=>!!c),na()).subscribe(()=>{this.unmuteAfterBrowserResetsHappened.next(!0)})),this.subscription.add(me(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.playbackRateState$.pipe(wr(()=>this.unmuteAfterBrowserResetsHappened.getValue()),na()).subscribe(()=>{let c=this.params.output.element$.getValue(),l=t.playbackRate.getState();c&&l!==c.playbackRate&&(c.playbackRate=l)})),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"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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"),w(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(Dh(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(rn(b));let g=[];for(let y of b.representations){let T=wu(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 l.video){m.push(sn(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 l.text)for(let b of f.representations){let g=Au(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 c==="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(wr(()=>this.videoTracksMap.size>0)),{abrThrottle:n}=this.params.tuning.dash;n&&(u=u.pipe(_h(n))),this.subscription.add(u.subscribe(async()=>{let c=this.player.state$.getState(),l=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||l)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);Qu(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="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(Si(c=>c.to)))}).pipe(Si(({videoState:c,autoVideoTrackState:l})=>c.to!=="stopped"&&l),Ar()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ar()).subscribe(c=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=l,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(sn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ar()).subscribe(c=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(rn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}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 d=t.playbackState.stateChangeStarted$.pipe(Si(({to:c})=>c==="ready"),Ar());this.subscription.add($r(d,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,aa(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add($r(d,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:x})=>x===u),d=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 c=[...this.videoStreamsMap.keys()].find(({id:x})=>x===h.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let p=le(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:x})=>x===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(y){if(n&&!a){let x=e(n,l,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,x?.bitrate??-1/0)}if(d){let x=e(d,l,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,x?.bitrate??-1/0)}}let v=n;(a||!v)&&(v=i(l,{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:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let k=y&&t(v,l,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}),$=this.videoTracksMap.get(v)?.representation,P=k&&this.audioTracksMap.get(k)?.representation;if($&&P)return[$,P];if($&&!P&&this.audioTracksMap.size===0)return[$,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ju.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),Ee(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 yn,merge as qu,filter as Wu,filterChanged as zu,isNullable as Tn,map as Gu,ValueSubject as In,isNonNullable as Uh}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 In(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zu()).subscribe(n=>{let d=i.position$.getValue(),h=i.volume$.getValue(),c=!h.volume||h.muted;!n&&!d&&c?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(yn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Gu(({liveBufferTime:n,liveAvailabilityStartTime:d})=>n&&d?n+d:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(Wu(n=>Uh(n))).subscribe(n=>i.isLiveEnded$.next(n!=="active"&&i.position$.getValue()===0))).add(yn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:qu(r.playbackRateState$,new In(1))}).pipe(Wu(({liveStreamStatus:n,liveDuration:d})=>n==="active"&&!!d)).subscribe(({liveDuration:n,playbackRate:d})=>{let h=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;c||d<1-l||this.video.paused||Tn(h)||(t=n-h)})).add(yn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:qu(r.playbackRateState$,new In(1))}).pipe(zu((n,d)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===d.liveDuration:n.time===d.time)).subscribe(({time:n,liveDuration:d,playbackRate:h})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&h>=1-l||Tn(n)||Tn(d))return;let p=-1*(d-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let d=$u(n);this.params.output.availableTextTracks$.next([d])}}))}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 dd,filter as Cn,filterChanged as Nr,fromEvent as Sp,isNonNullable as ld,isNullable as vp,map as Ur,merge as Hr,observableFrom as fa,once as cd,Subscription as yp}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as Rn,assertNonNullable as Ti,combine as Ii,ErrorCategory as Ue,filter as ha,filterChanged as Or,flattenObject as Fr,fromEvent as Je,getTraceSubscriptionMethod as sp,interval as Mn,isNonNullable as _r,isNullable as od,map as Ei,merge as Qt,now as Dn,Subject as kt,Subscription as Bn,tap as ap,throttle as ud,ValueSubject as J}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Hh,ErrorCategory as Yu,Subject as Ku}from"@vkontakte/videoplayer-shared/evergreen";var jh=18,Xu=!1;try{Xu=D.browser.isSafari&&!!D.browser.safariVersion&&D.browser.safariVersion<=jh}catch(o){console.error(o)}var En=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:Hh(t)}}},Ju=En;import{abortable as Et,assertNonNullable as ve,ErrorCategory as Ht,fromEvent as An,getExponentialDelay as $n,isHigher as Gh,isNonNullable as xt,isNullable as se,now as da,once as Yh,Subject as Kh,Subscription as Xh,ValueSubject as jt}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Qh,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)??Qh({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}),ed=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),td=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),xn=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),kn=({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 id=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},rd=o=>{let e=!1,t=qh(()=>{e=!0},o);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Wh,Subscription as zh}from"@vkontakte/videoplayer-shared/evergreen";var oa=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 ua=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new zh;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=oa(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:d}){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 Kh;this.gaps=[];this.subscription=new Xh;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 ua(this.mediaSource,this.sourceBuffer),this.subscription.add(An(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(An(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 d=le(this.sourceBuffer.buffered,u),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,d<h).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);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(se(s)||se(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(se(s)||se(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.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let n of this.representations.keys()){let d=t.find(l=>l.id===n);d&&this.representations.set(n,d);let h=this.representations.get(n);if(!h||!Pe(h.segmentReference))return;let c=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ve(r);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))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=!!d?.live,this.baseUrls=d?.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(se(u)||se(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(){!se(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(se(e)||se(this.downloadingRepresentationId)||se(this.playingRepresentationId)||se(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}`),se(r)||se(s))return;let a=r.find(l=>e>=l.time.from&&e<l.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 l=this.getForwardBufferDuration(e),p=Rr(i),m=Rr(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&xt(p)&&xt(m)&&Gh(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?u+=Math.min(l,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=a.time.to-e+n&&(u=a?a.time.to+n:-1/0),this.tuning.dash.useNewRepresentationSwitch){let y=[...this.segments.entries()].map(([T,v])=>{let k=v.find($=>e>=$.time.from&&e<$.time.to);return{representationId:T,status:k?.status}}).find(T=>T.status==="fed")?.representationId;if(!y)return;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 l=le(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<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 l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))l="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(h,t,l).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h?.length&&le(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=r.at(-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-le(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-c.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].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=e?.streams[this.kind].flatMap(i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!Pe(i.segmentReference))return;let r=i.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,n=r?.findIndex(d=>u>=d.time.from+s&&u<=d.time.to+s);if(n===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,d)}else{let d=r.slice(n+1);this.segments.set(i.id,[...a,...d])}}}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),d=_e(r.segmentTemplateUrl,{segmentTime:n});s.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}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:l,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(l==="none"||l==="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,d=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let l=s;l<a.length&&(u<=h||n<=c);l++){let p=a[l];if(u+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")d.push(p);else break}return d}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:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await Et(u,async function*(){let h=$n(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,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=da(),!h)return;let c=new DataView(h),l=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=l.getChunkEndTime(c,f)}n&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=l.getServerLatencyTimestamps(c);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=$n(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,n),An(window,"online").pipe(Yh()).subscribe(()=>{d(),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=da(),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=da(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:n,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}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?(d,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=da();let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}: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 d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=Ke(a.mime).parseFeedableSegmentChunk(d,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:d}=n,h=d.byte.from-i,c=d.byte.to-i,l=c-h+1,p=h<r,m=c<=r;if(p){if(d.status==="downloading"&&m){d.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+h,l);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(n,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(n.loadedBytes=Math.min(l,r-h),n.loadedBytes>n.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+h+n.feedingBytes,n.loadedBytes-n.feedingBytes),b=n.loadedBytes===l?f:Ke(u.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(d.status="partially_fed",n.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(n.fedBytes+=b.byteLength,n.fedBytes===l&&this.onSegmentFullyAppended(n,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(se(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=$n(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:d,segments:h}=u,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let l=h;this.isLive&&Pe(e.segmentReference)&&(l=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,l),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||se(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 d=n.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=n.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||h)&&n.status==="fed"&&a(n)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let n=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,h=0;for(let c of this.segments.values())for(let l of c)["none","partially_ejected"].includes(l.status)&&Math.round(l.time.from)<=Math.round(n)&&Math.round(l.time.to)>=Math.round(d)&&h++;if(h===this.segments.size){let c={time:{from:n,to:d},url:"",status:"none"};a(c)}}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 d of n)d.time.from>=e+u&&d.status==="fed"&&a(d)}return r.length?(r=id(r),(await Promise.all(r.map(n=>this.sourceBufferTaskQueue.remove(n.from,n.to)))).reduce((n,d)=>n||d,!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||se(e)?0:le(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(se(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||se(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=oa(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,d=0;for(let h=0;h<e.length;h+=2){let c=e[h],l=e[h+1];n||(n=c-t<=a&&l+t>=u),(a>=c&&a<l-t||u>c+t&&u<=l)&&(d+=1)}n||(d===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 sd,fromEvent as ad,merge as Jh,now as Br,Subject as vi,ValueSubject as Pn,flattenObject as yi,ErrorCategory as Vr,SubscriptionRemovable as Zh}from"@vkontakte/videoplayer-shared/evergreen";var ca=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 Pn(void 0);this.lastConnectionReused$=new Pn(void 0);this.lastRequestFirstBytes$=new Pn(void 0);this.recoverableError$=new vi;this.error$=new vi;this.abortAllController=new AbortController;this.subscription=new Zh;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:d=!1}={}){let h=e,c=new Headers,l=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let S=new URL(h,location.href);S.searchParams.append("bytes",`${i.from}-${i.to}`),h=S.toString();break}default:sd(t)}this.requestQuic&&(h=yt(h));let p=this.abortAllController.signal,m;if(a){let S=new AbortController;if(m=Jh(ad(this.abortAllController.signal,"abort"),ad(a,"abort")).subscribe(()=>{try{S.abort()}catch(I){la(I)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{S.abort()}catch(I){la(I)}p=S.signal}let f=0,b=Br();l.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:c,signal:p}),y=Br();if(!g)return l.error("error",{message:"No response in request"}),l.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(y-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let S=`Fetch error ${g.status}: ${g.statusText}`;return l.error("error",{message:S}),l.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let S=Br(),I={requestStartedAt:b,requestEndedAt:S,duration:S-b};return l.log("endRequest",yi(I)),l.end(),g.arrayBuffer()}let T=g.body;if(u){let S;[T,S]=g.body.tee(),this.throughputEstimator?.trackStream(S,n)}let v=T.getReader(),k,$=parseInt(g.headers.get("content-length")??"",10);Number.isFinite($)&&(k=$),!k&&i&&(k=i.to-i.from+1);let P=k?new Uint8Array(k):new Uint8Array(0),x=!1,M=S=>{this.unsubscribeAbortSubscription(m),x=!0,la(S)},E=Dr(p,async function*({done:S,value:I}){if(f===0&&(this.lastRequestFirstBytes$.next(Br()-b),this.firstBytesReceived.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!S&&I){if(d&&k)P.set(I,f),f+=I.byteLength;else{let W=new Uint8Array(P.length+I.length);W.set(P),W.set(I,P.length),P=W,f+=I.byteLength}r?.(new DataView(P.buffer),f),yield v?.read().then(E,M)}}.bind(this));yield v?.read().then(E,M),this.unsubscribeAbortSubscription(m);let _=Br(),L={failed:x,requestStartedAt:b,requestEndedAt:_,duration:_-b};return x?(l.error("endRequest",yi(L)),l.end(),null):(l.log("endRequest",yi(L)),l.end(),P.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,d,h;e.indexRange&&(d=e.indexRange.from,h=e.indexRange.to,n=s+1===d,n&&(a=Math.min(d,r),u=Math.max(h,s))),a=Math.min(a,0);let c=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!c)return null;let l=new DataView(c,r-a,s-a+1);if(!t.validateData(l))throw new Error("Invalid media file");let p=t.parseInit(l),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(n)f=new DataView(c,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(c),segments:b}}.bind(this));this.fetchTemplateRepresentation=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:sd(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 ep,ValueSubject as tp}from"@vkontakte/videoplayer-shared/evergreen";var Cr=class o{constructor(e,t){this.currentRepresentation$=new tp(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(!ep(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(d=>d.time.from<=e&&d.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 pa=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Bn;this.representationSubscription=new Bn;this.state$=new O("none");this.currentVideoRepresentation$=new J(void 0);this.currentVideoRepresentationInit$=new J(void 0);this.currentAudioRepresentation$=new J(void 0);this.currentVideoSegmentLength$=new J(0);this.currentAudioSegmentLength$=new J(0);this.error$=new kt;this.manifestRequested=new kt;this.manifestReceived=new kt;this.firstBytesRequested=new kt;this.firstBytesReceived=new kt;this.lastConnectionType$=new J(void 0);this.lastConnectionReused$=new J(void 0);this.lastRequestFirstBytes$=new J(void 0);this.currentLiveTextRepresentation$=new J(null);this.isLive$=new J(!1);this.isActiveLive$=new J(!1);this.isLowLatency$=new J(!1);this.liveDuration$=new J(0);this.liveSeekableDuration$=new J(0);this.liveAvailabilityStartTime$=new J(0);this.liveStreamStatus$=new J(void 0);this.bufferLength$=new J(0);this.liveLatency$=new J(void 0);this.liveLoadBufferLength$=new J(0);this.livePositionFromPlayer$=new J(0);this.currentStallDuration$=new J(0);this.videoLastDataObtainedTimestamp$=new J(0);this.fetcherRecoverableError$=new kt;this.fetcherError$=new kt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new kt;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Rn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ue.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Rn(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 d=Cs(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(d)}if(!t)return null;let i=(n,d,h)=>!!(this.element?.canPlayType?.(d)&&Ae()?.isTypeSupported?.(`${d}; codecs="${h}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:d,streamIsUnpublished:h,streamIsAlive:c}=t.live,l=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*l),this.liveDuration$.next((d-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(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:l,codecs:p})=>i(n,l,p));r[n]=h;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let l=h.map(({codecs:p})=>p);n==="audio"&&(a=Xs(l),c=a[0]),n==="video"&&(s=Ks(l),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?c=this.forceVideoCodec:c=s[0]),c&&(r[n]=h.filter(({codecs:p})=>pi(p)===c))}else{let l=new Set(h.map(({codecs:p})=>p));c=Ys(l),c&&(r[n]=h.filter(({codecs:p})=>p.startsWith(c)))}if(n==="video"){let l=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);D.display.isHDR&&l&&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=Rn(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 Bn,this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(Je(l,"error").pipe(ha(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 l=document.createElement("source");r(l),l.type="application/x-mpegurl",l.src=i.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;this.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((l,p)=>[...l,...p.representations],[]);if(this.videoBufferManager=new Mr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],_r(t)){let l=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new Mr("audio",this.source,l,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(l=>Je(this.element,l))).pipe(Ei(l=>this.element?le(this.element.buffered,this.element.currentTime*1e3):0),Or(),ap(l=>{l>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=Dn())),this.subscription.add(Je(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Mn(1e3).subscribe(p=>{let m=pt(this.manifestUrlString,2);this.manifestUrlString=ee(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(ha(({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(ha(({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 v=1;Math.abs(T)>g&&(v=1+Math.sign(T)*y),hi(this.element,v)})),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 l=0;this.representationSubscription.add(Ii({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ud(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,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,k=isFinite(p)?p:m,$=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),P=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(P);let x="none";if($?x="active_low_latency":this.isLowLatency$.getValue()&&P?(this.bufferManagers.forEach(M=>M.proceedLowLatencyLive()),x="active_low_latency"):b!==0&&k<y?x="live_forward_buffering":k<y+v&&(x="live_with_target_offset"),isFinite(p)&&(l=p>l?p:l),x==="live_forward_buffering"||x==="live_with_target_offset"){let M=l-(y+T),E=this.normolizeLiveOffset(Math.trunc(b+M/f)),_=Math.abs(E-b),L=0;!p||_<=this.tuning.dashCmafLive.offsetCalculationError?L=b:E>0&&_>this.tuning.dashCmafLive.offsetCalculationError&&(L=E),this.manifestUrlString=ee(this.manifestUrlString,L,2)}(x==="live_with_target_offset"||x==="live_forward_buffering")&&(l=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ue.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let d=Qt(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(Ei(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),h=Qt(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(Ei(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),c=Ii({allBuffersFull:d,someBufferEnded:h}).pipe(Or(),Ei(({allBuffersFull:l,someBufferEnded:p})=>l&&p),ha(l=>l));if(this.representationSubscription.add(Qt(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(l=>!l.updating))try{this.source?.endOfStream()}catch(l){this.error$.next({id:"EndOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(Qt(...this.bufferManagers.map(l=>l.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 l=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{l&&(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 l=[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(...l)/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=Mn(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 ca({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=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"?Dn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ee(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Ti(this.element),this.state$.setState("running");let e=Je(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(ud(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=Dn(),a=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,d=this.videoBufferManager?.getForwardBufferDuration()??0,h=this.audioBufferManager?.getForwardBufferDuration()??0,c=d<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,l=this.audioBufferManager&&h<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||l)&&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?.unsubscribe(),this.stallWatchdogSubscription=Mn(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){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()]),!(od(this.element)||od(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.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=sp(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 d of n.gaps)(d.persistent||n.playingRepresentation$.getValue()===d.representation)&&d.from-u<=s&&d.to+u>s&&(this.element.duration*1e3-d.to<this.tuning.endGapTolerance?a=1/0:(a===null||d.to>a)&&(a=d.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 dp,observeElementSize as lp,Subscription as cp,ValueSubject as Vn,noop as hp}from"@vkontakte/videoplayer-shared/evergreen";var ma=class{constructor(){this.subscription=new cp;this.pipSize$=new Vn(void 0);this.videoSize$=new Vn(void 0);this.elementSize$=new Vn(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(lp(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(dp(({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 qt=class{constructor(e){this.subscription=new yp;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ai;this.stallsManager=new ra;this.elementSizeManager=new ma;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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(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=Ie(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(de(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 pa({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:dd.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(Cn(c=>!!c.length),cd()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ur(c=>c.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(Cn(ld),cd()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ur(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(We(this.video,t.isLooped,r)),this.subscription.add(me(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"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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"),w(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams(),p=this.player.getCodecs();if(fp(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of l.audio){f.push(xn(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 l.video){m.push(kn(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 l.text)for(let b of f.representations){let g=ed(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 c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,n=u&&rd(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(Cn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),l=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||l||c==="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);ld(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(bp({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Hr(fa([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Ur(c=>c.to)))}).pipe(Ur(({videoState:c,autoVideoTrackState:l})=>c.to!=="stopped"&&l),Nr()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Nr()).subscribe(c=>{let l=Ut(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=l,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(kn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Nr()).subscribe(c=>{let l=Ut(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===c);if(!l){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=l,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(xn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(l){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${l}`})}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 d=t.playbackState.stateChangeStarted$.pipe(Ur(({to:c})=>c==="ready"),Nr());this.subscription.add(Hr(d,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,fa(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Hr(d,this.player.state$.stateChangeEnded$,fa(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Hr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fa(["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(),x=>x.id===u),d=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 c=Ut(this.videoStreamsMap.keys(),x=>x.id===h.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let p=le(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(),x=>x.id===g.id)||this.audioStreamsMap.keys().next().value,T=0;if(y){if(n&&!a){let x=e(n,l,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,x?.bitrate??-1/0)}if(d){let x=e(d,l,this.audioStreamsMap.get(y)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,x?.bitrate??-1/0)}}let v=n;(a||!v)&&(v=i(l,{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:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let k=y&&t(v,l,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}),$=this.videoTracksMap.get(v)?.representation,P=k&&this.audioTracksMap.get(k)?.representation;$&&P?(this.selectedRepresentations.video=$,this.selectedRepresentations.audio=P):$&&!P&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=$,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dd.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),Ee(this.video),this.tracer.end()}};var jr=class extends qt{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 On,merge as hd,filter as pd,filterChanged as md,isNullable as Fn,map as fd,ValueSubject as _n,isNonNullable as Tp}from"@vkontakte/videoplayer-shared/evergreen";var Qr=class extends qt{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 _n(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(md()).subscribe(n=>{let d=i.position$.getValue(),h=i.volume$.getValue(),c=!h.volume||h.muted;!n&&!d&&c?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(fd(n=>n.to)).subscribe(this.player.isLowLatency$)).add(On({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fd(({liveBufferTime:n,liveAvailabilityStartTime:d})=>n&&d?n+d:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(pd(n=>Tp(n))).subscribe(n=>i.isLiveEnded$.next(n!=="active"&&i.position$.getValue()===0))).add(On({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:hd(r.playbackRateState$,new _n(1))}).pipe(pd(({liveStreamStatus:n,liveDuration:d})=>n==="active"&&!!d)).subscribe(({liveDuration:n,playbackRate:d})=>{let h=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;c||d<1-l||this.video.paused||Fn(h)||(t=n-h)})).add(On({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:hd(r.playbackRateState$,new _n(1))}).pipe(md((n,d)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===d.liveDuration:n.time===d.time)).subscribe(({time:n,liveDuration:d,playbackRate:h})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:l}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&h>=1-l||Fn(n)||Fn(d))return;let p=-1*(d-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let d=td(n);this.params.output.availableTextTracks$.next([d])}}))}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 bd="X-Playback-Duration",Nn=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(bd)?parseInt(e.headers.get(bd),10):void 0};import{assertNever as Mp,combine as Dp,debounce as Bp,ErrorCategory as Sa,filter as Vp,filterChanged as Cp,isNonNullable as vd,isNullable as va,map as yd,merge as Op,observableFrom as Fp,Subscription as _p,ValueSubject as Hn,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},kp=(o,e)=>{let t=o.split(`
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 d=Object.fromEntries(u[1].split(",").map(b=>b.split("="))),h=d.QUALITY??`stream-${d.BANDWIDTH}`,c=xp(d),l;d.BANDWIDTH&&(l=parseInt(d.BANDWIDTH,10)/1e3||void 0),!l&&d["AVERAGE-BANDWIDTH"]&&(l=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,m;if(d.RESOLUTION){let[b,g]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();c&&i.push({id:h,quality:c,url:f,bandwidth:l,size:m,fps:p})}if(n){let d=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=d.URI?.replace(/playlist$/,"subtitles.vtt"),c=d.LANGUAGE,l=d.NAME;h&&c&&r.push({type:"internal",id:c,label:l,language:c,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},wp=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),Un=0,gd=async(o,e=o,t,i)=>{let s=await(await fetch(o,i)).text();Un+=1;try{let{qualityManifests:a,textTracks:u}=kp(s,e);return{qualityManifests:a,textTracks:u}}catch{if(Un<=t.manifestRetryMaxCount)return await wp(Ep(Un-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),gd(o,e,t)}return{qualityManifests:[],textTracks:[]}},ba=gd;import{isNonNullable as Ap,Subscription as $p,throttle as Pp,ValueSubject as Sd,Subject as Lp,ErrorCategory as Rp}from"@vkontakte/videoplayer-shared/evergreen";var ga=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 Sd(null);this.getCurrentTime$=new Sd(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],d=new URL(n,t).toString(),h=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+h},url:d}),s=s+h,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),l=new Date(i.programDateTime).valueOf();i.segmentStartTime=l-c}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 d=new Date(n);d.setMilliseconds(0),s=d.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 qr=class{constructor(e){this.subscription=new _p;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Hn([]);this.liveOffset=new Bt;this.manifestStartTime$=new Hn(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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(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),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position&&d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(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"&&w(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"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Mp(t)}};this.params=e,this.video=Ie(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)=>ba(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 ga(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:Sa.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Sa.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Hn(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:Sa.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(me(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"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(),yd(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(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&vd(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let l=this.manifests$.getValue().find(p=>p.id===c);l&&(this.params.output.currentVideoTrack$.next(l),this.params.output.hostname$.next(de(l.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(vd)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:n})=>this.params.output.liveTime$.next(u+n*1e3),i)),this.subscription.add(this.manifests$.pipe(yd(u=>u.map(({id:n,quality:d,size:h,bandwidth:c,fps:l})=>({id:n,quality:d,size:h,fps:l,bitrate:c})))).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),Ee(this.video)}prepare(){let e=this.selectManifest();if(va(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[d,h]of[[u,"mq"],[n,"lq"]]){let c=String(parseFloat(d||""));h&&d&&r.searchParams.set(h,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=ee(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),Nn(a).then(u=>{if(!va(u))this.maxSeekBackTime$.next(u);else{let n=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(va(n)||!isFinite(n))&&fetch(a).then(d=>d.text()).then(d=>{let h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(d)?.[1];if(h){let c=new URL(h,a).toString();Nn(c).then(l=>{va(l)||this.maxSeekBackTime$.next(l)})}}).catch(()=>{})}})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Sa.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ee(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as Up,debounce as Hp,ErrorCategory as jn,filter as Td,fromEvent as Qn,isNonNullable as jp,isNullable as Qp,map as qn,merge as Id,observableFrom as Ed,once as xd,Subscription as qp,ValueSubject as kd,VideoQuality as Wp}from"@vkontakte/videoplayer-shared/evergreen";var Wr=class{constructor(e){this.subscription=new qp;this.videoState=new O("stopped");this.manifests$=new kd([]);this.unmuteAfterBrowserResetsHappened=new kd(!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"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h);let{currentTime:c}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&w(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=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Wp.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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),ba(ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.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:jn.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:jn.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(qn(u=>u.to)),this.params.output.playbackState$),this.subscription.add(We(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)),this.subscription.add(t.volume.stateChangeStarted$.pipe(qn(()=>{let u=t.volume.getTransition(),n=this.params.output.element$.getValue();return!n||!u?!1:!u.to.muted&&n.muted}),Td(u=>!!u),xd()).subscribe(()=>{this.unmuteAfterBrowserResetsHappened.next(!0)})),this.subscription.add(me(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.playbackRateState$.pipe(Td(()=>this.unmuteAfterBrowserResetsHappened.getValue()),xd()).subscribe(()=>{let u=this.params.output.element$.getValue(),n=t.playbackRate.getState();u&&n!==u.playbackRate&&(u.playbackRate=n)})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&jp(d.to)){let p=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(de(m.url)))}let c=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(c!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}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"),w(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(qn(u=>u.map(({id:n,quality:d,size:h,bandwidth:c,fps:l})=>({id:n,quality:d,size:h,fps:l,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!D.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(Id(Qn(u,"addtrack"),Qn(u,"removetrack"),Qn(u,"change"),Ed(["init"])).subscribe(()=>{for(let n=0;n<u.length;n++)u[n].mode="hidden"},i))}let a=Id(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ed(["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),Ee(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 d=String(parseFloat(u||""));n&&u&&r.searchParams.set(n,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as zp,assertNonNullable as wd,debounce as Gp,ErrorCategory as Ad,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 O("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"),w(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"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return zp(e)}};this.params=e,this.video=Ie(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:Ad.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(We(this.video,t.isLooped,i)),this.subscription.add(me(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"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(),d=this.params.output.element$.getValue()?.playbackRate;if(n!==d){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"),w(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),Ee(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;wd(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wd(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(de(t))}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ad.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=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{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:d,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(d=>d.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 Pd,debounce as am,merge as Ld,observableFrom as nm,Subscription as om,map as Rd,ValueSubject as um,ErrorCategory as zn,VideoQuality as dm}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as im}from"@vkontakte/videoplayer-shared/evergreen";var $d=["stun:videostun.mycdn.me:80"],rm=1e3,sm=3,Wn=()=>null,ya=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=Wn;this.externalStopCallback=Wn;this.externalErrorCallback=Wn;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:$d}]};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:$d,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 O("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"),w(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"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return Pd(e)}};this.subscription=new om,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ie(e.container,e.tuning),this.liveStreamClient=new ya(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),Ee(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:zn.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(Ld(this.videoState.stateChangeStarted$.pipe(Rd(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Rd(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(me(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 Pd(a.to)}},i)).add(Ld(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(de(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:dm.INVARIANT}),this.video.srcObject=e,w(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:zn.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zn.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 wt,ErrorCategory as Ta,filter as Od,isNonNullable as Fd,isNullable as bm,map as gm,merge as Sm,once as vm,Subject as te,Subscription as _d,ValueSubject as V,flattenObject as Gn}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as lm,map as Md,Subscription as cm,Subject as hm}from"@vkontakte/videoplayer-shared/evergreen";var Dd=o=>new lm(e=>{let t=new cm,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Md(({from:d,to:h})=>`${d}-${h}`)),r=o.desiredPlaybackState$.stateChangeEnded$,s=o.providerChanged$.pipe(Md(({type:d})=>d!==void 0)),a=new hm,u=0,n="unknown";return t.add(i.subscribe(d=>{u&&window.clearTimeout(u),n=d,u=window.setTimeout(()=>a.next(d),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),n="unknown",u=0})),t.add(s.subscribe(d=>{u&&(window.clearTimeout(u),u=0,d&&(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 Vd,once as Cd}from"@vkontakte/videoplayer-shared/evergreen";function Bd(){return new(window.AudioContext||window.webkitAudioContext)}var ki=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(Vd(s=>!!s.type),Cd()).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(Vd(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Cd()).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=Bd();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 te;this.noAvailableProvidersError$=new te;this.volumeMultiplierError$=new te;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 te,fetcherError$:new te,fetcherRecoverableError$:new te,warning$:new te,willSeekEvent$:new te,soundProhibitedEvent$:new te,seekedEvent$:new te,loopedEvent$:new te,endedEvent$:new te,manifestRequested$:new te,manifestReceived$:new te,firstBytesRequested$:new te,firstBytesReceived$:new te,firstBytesEvent$:new te,loadedMetadataEvent$:new te,firstFrameEvent$:new te,canplay$:new te,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 te,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 _d;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=Va([...Vu(this.params.tuning),...Bu(this.params.tuning)]).filter(d=>Fd(e.sources[d])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(d=>!r.includes(d)),...t.filter(d=>r.includes(d))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Gn(s)),this.screenFormatsIterator=new xi(s);let a=[...ln(!0),...ln(!1)];this.chromecastFormatsIterator=new xi(a.filter(d=>Fd(e.sources[d]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:n}}=this.params;n&&u!==1&&ki.isSupported()&&(this.volumeMultiplierManager=new ki(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:Ta.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]),d=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return wt(n),this.params.tuning.useNewDashProvider?new jr({...u,source:n,sourceHls:d,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Pr({...u,source:n,sourceHls:d,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return wt(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 wt(n),new Wr({...u,source:n})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return wt(n),new qr({...u,source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let n=this.applyFailoverHost(t[e]);return wt(n),new zr({...u,source:n})}case"DASH_LIVE":{let n=this.applyFailoverHost(t[e]);return wt(n),new lu({...u,source:n,config:{...ym,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let n=this.applyFailoverHost(t[e]);return wt(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 wt(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 _d,t=!1,i=0;return e.add(Sm(this.providerOutput.error$.pipe(Od(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Dd({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(gm(r=>({id:`ProviderHangup:${r}`,category:Ta.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(Od(({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===Ta.NETWORK,n=r.category===Ta.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),h=i<this.params.tuning.providerErrorLimit&&!n,c=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,l=d&&!n&&(u&&t||!h);a={...a,isNetworkError:u,isFatalError:n,haveFailoverHost:d,tryFailover:l,canReinitProvider:h},h?(i++,this.reinitProvider()):l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Gn(a)):this.tracer.error("providerError",Gn(a))})),e}};import{fromEvent as Ia,once as Tm,combine as Im,Subscription as Nd,ValueSubject as Yn,map as Em,filter as xm,isNonNullable as Ea,now as Le,safeStorage as Kn}from"@vkontakte/videoplayer-shared/evergreen";var km=5e3,Ud="one_video_throughput",Hd="one_video_rtt",Xr=window.navigator.connection,jd=()=>{let o=Xr?.downlink;if(Ea(o)&&o!==10)return o*1e3},Qd=()=>{let o=Xr?.rtt;if(Ea(o)&&o!==3e3)return o},qd=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},Xn=class o{constructor(e){this.subscription=new Nd;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=o.load(Ud)||(e.useBrowserEstimation?jd():void 0)||km,i=o.load(Hd)??(e.useBrowserEstimation?Qd():void 0)??0;if(this.throughput$=new Yn(t),this.rtt$=new Yn(i),this.rttAdjustedThroughput$=new Yn(qd(t,i,e.rttPenaltyRequestSize)),this.throughput=nt.getSmoothedValue(t,-1,e),this.rtt=nt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=jd();a&&this.throughput.next(a);let u=Qd();Ea(u)&&this.rtt.next(u)};Xr&&"onchange"in Xr&&this.subscription.add(Ia(Xr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Kn.set(Ud,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Kn.set(Hd,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})=>qd(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 Nd;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Ia(e,"progress").pipe(Tm()).subscribe(s=>{t=s.loaded,i=Le()}));break;case 1:case 0:r.add(Ia(e,"loadstart").subscribe(()=>{t=0,i=Le()}));break}r.add(Ia(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,u=Le(),n=a-t,d=u-i;this.addRawSpeed(n,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Le(),a=0,u=Le(),n=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},d=async({done:h,value:c})=>{if(h)!t&&this.addRawSpeed(r,Le()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let l=Le();if(l-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||l-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(a,m,1,t),a=c.byteLength,s=Le()}else a+=c.byteLength;u=Le()}else r+=c.byteLength,a+=c.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(d,n)}};this.concurrentDownloads.add(e),i?.read().then(d,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=Kn.get(e);if(Ea(t))return parseInt(t,10)??void 0}},Wd=Xn;import{fillWithDefault as wm,VideoQuality as xa}from"@vkontakte/videoplayer-shared/evergreen";var zd={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:xa.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:xa.Q_720P,trafficSavingLimit:xa.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:xa.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},dashCmafLive:{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},Gd=o=>({...wm(o,zd),configName:[...o.configName??[],...zd.configName]});import{assertNonNullable as Zn,combine as ut,ErrorCategory as ka,filter as C,filterChanged as z,fromEvent as eo,isNonNullable as Jd,isNullable as Dm,Logger as Bm,map as q,mapTo as Zd,merge as At,now as wa,once as F,Subject as Q,Subscription as el,tap as to,ValueSubject as A,isHigher as Vm,isInvariantQuality as tl,flattenObject as $t,throttle as io,getTraceSubscriptionMethod as il,TracerFactory as Cm,InternalsExposure as Om,getPlayerId as Fm}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Am,map as $m,filter as Yd,isNonNullable as Pm}from"@vkontakte/videoplayer-shared/evergreen";var Jn=({seekState:o,position$:e})=>Am(o.stateChangeEnded$.pipe($m(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Yd(Pm)),e.pipe(Yd(()=>o.getState().state==="none")));import{assertNonNullable as Lm}from"@vkontakte/videoplayer-shared/evergreen";var Kd=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 Xd=(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 Aa=class{constructor(e={configName:[]},t=Cm.createRootTracer(!1),i){this.subscription=new el;this.logger=new Bm;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new A(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new A(void 0),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),predefinedQualityLimitType$:new A("unknown"),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),isLiveEnded$:new A(null),canPlayLiveTailBuffer$:new A(!1),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willReady$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,fetcherRecoverableError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,manifestRequested$:new Q,manifestReceived$:new Q,firstBytesRequested$:new Q,firstBytesReceived$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q,fetcherError$:new Q,severeStallOccured$:new Q};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:No,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=Gd(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 ds({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Wd(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(d){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}>`})),c=`Player.${String(s)}`,l=`Exception calling ${c} (${h.join(", ")})`;throw this.events.fatalError$.next({id:c,category:ka.WTF,message:l,thrown:d}),d}}}})}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=Kd(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(C(s=>!!s),F()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),eo(document,"visibilitychange").pipe(F()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{Zn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(C(i=>i.length>0),F()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",$t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.desiredState.playbackRate.startTransitionTo(e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",$t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{Xd(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(C(t=>!!t),F()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(C(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(C(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(C(e=>!!e),F()).subscribe(()=>{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 Jd(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(q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ho(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(C(({from:e})=>e==="stopped"),F()).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:ka.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(F()).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(q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(q(a=>a.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ut({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(q(({availableVideoTracks:a,currentVideoStream:u})=>a.filter(n=>u?u.id===n.streamId:!0).map(({quality:n})=>n).sort((n,d)=>tl(n)?1:tl(d)?-1:Vm(d,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(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(C(a=>Jd(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(q(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(to(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(q(a=>a.to),z(),q(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:Jn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(q(({isLive:a,position:u,isLowLatency:n})=>{let d=this.getActiveLiveDelay(n);return a&&Math.abs(u)<d/1e3}),z(),to(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(q(({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(q(({isLive:a,position:u,duration:n})=>a&&(Math.abs(n)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),z(),to(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(q(a=>a.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(q(a=>a.volume),z()).subscribe(this.info.volume$)).add(Jn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(At(e.providerOutput.endedEvent$.pipe(Zd(!0)),e.providerOutput.seekedEvent$.pipe(Zd(!1))).pipe(z()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(q(a=>({id:a?`No${a}`:"NoProviders",category:ka.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(F()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe(F()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(F()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(F()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(F(),q(a=>a??wa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),q(()=>wa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),q(()=>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 A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new A(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(C(({to:a})=>a==="playing"),F()).subscribe(()=>i.next(!1)));let r=0,s=At(e.providerOutput.isBuffering$,t,i).pipe(q(()=>{let a=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return a&&!u}),z());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(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(),d=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue(),c;h==="CONNECTED"?c="second_screen":n?d?a?c="pip":u?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new el;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(C(i=>i.length>0),F()).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(q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(q(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;Zn(this.providerContainer),Zn(e),_o(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Fo(t)),this.providerContainer.current$.subscribe(({type:t})=>Vi("provider",t)),e.duration$.subscribe(t=>Vi("duration",t)),e.availableVideoTracks$.pipe(C(t=>!!t.length),F()).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(q(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=il(this.tracer.log.bind(this.tracer)),t=il(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(z()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ut({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(C(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(C(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(C(i=>i>0),z()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ut({currentBuffer:this.info.currentBuffer$.pipe(C(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(io(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(ut({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(C(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),io(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),C(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),C(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),C(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ut({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(C(({throughputEstimation:i,rtt:r})=>!!i&&!!r),io(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),C(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:ka.DOM,message:String(r)})})};this.subscription.add(At(eo(document,"visibilitychange"),eo(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 BD,Observable as VD,Subject as CD,ValueSubject as OD,VideoQuality as FD}from"@vkontakte/videoplayer-shared/evergreen";var _D=`@vkontakte/videoplayer-core@${so}`;export{ns as ChromecastState,La as HttpConnectionType,VD as Observable,Te as PlaybackState,Aa as Player,os as PredefinedQualityLimits,_D as SDK_VERSION,CD as Subject,BD as Subscription,Ra as Surface,so as VERSION,OD as ValueSubject,et as VideoFormat,FD as VideoQuality,Il as areValidLiveRecordSources,D as clientChecker,Li as isMobile};