@vkontakte/videoplayer-core 2.0.145-dev.d9a3a83a.0 → 2.0.145

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/evergreen.esm.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.145-dev.d9a3a83a.0
3
- * Fri, 31 Oct 2025 09:58:10 GMT
2
+ * @vkontakte/videoplayer-core v2.0.145
3
+ * Thu, 06 Nov 2025 09:26:06 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-145/doc/
5
5
  */
6
- var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(fe||{}),tt=(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))(tt||{});var Mi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Mi||{}),Na=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Na||{});var Ua=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(Ua||{}),ps=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ps||{});import{assertNever as wo,assertNonNullable as Al,isNonNullable as ms,ValueSubject as Ha,Subject as $l,Subscription as Pl,merge as Ll,observableFrom as Ml,fromEvent as To,map as Io,tap as Eo,filterChanged as Rl,isNullable as ja,ErrorCategory as xo}from"@vkontakte/videoplayer-shared/evergreen";var yo=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 fs=class{constructor(e){this.connection$=new Ha(void 0);this.castState$=new Ha("NOT_AVAILABLE");this.errorEvent$=new $l;this.realCastState$=new Ha("NOT_AVAILABLE");this.subscription=new Pl;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=ms(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||yo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:xo.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ms(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ja(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ja(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(To(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 wo(r.sessionState)}})).add(Ll(To(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Eo(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Io(r=>r.castState)),Ml([i.getCastState()])).pipe(Rl(),Io(Dl),Eo(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=ms(this.connection$.getValue());if(s&&!a){let u=i.getCurrentSession();Al(u);let n=u.getCastDevice(),c=u.getMediaSession()?.media?.contentId;(ja(c)||c===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"?ms(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:xo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},Dl=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 wo(o)}};import{assertNonNullable as Wa,combine as za,debounce as Ga,ErrorCategory as zl,filter as ii,filterChanged as Bo,isNonNullable as ws,map as Gl,Subscription as Yl,ValueSubject as Ya}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Cl,assertNonNullable as Dt,ErrorCategory as Bl,getHighestQuality as Vl,isNonNullable as Ao}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as ko}from"@vkontakte/videoplayer-shared/evergreen";var Z=(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:ko(t)}return o},gt=(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:ko(e)}};var gs=o=>{let{source:e,format:t,meta:i,output:r}=o,s,a,u;switch(t){case"MPEG":{let l=e[t];Dt(l);let d=Vl(Object.keys(l));Dt(d);let p=l[d];Dt(p),s=p,a="video/mp4",u=bs();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=e[t];Dt(l),s=l.url,a="application/x-mpegurl",u=bs();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=e[t];Dt(l),s=l.url,a="application/dash+xml",u=bs();break}case"DASH_LIVE_CMAF":{let l=e[t];Dt(l),s=l.url,a="application/dash+xml",u=$o();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=e[t];Dt(l),s=Z(l.url),a="application/x-mpegurl",u=$o();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Bl.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return Cl(t)}let n=Ol(i.videoId??s,a);n.contentUrl=s,n.streamType=u,n.metadata=Fl();let{title:c,subtitle:h}=i;return Ao(c)&&(n.metadata.title=c),Ao(h)&&(n.metadata.subtitle=h),n};function bs(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function $o(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function Ol(o,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(o,e):{contentId:o,contentType:e,metadata:{title:"",subtitle:""},streamType:bs()}}function Fl(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var k=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};var Ss=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Co}from"@vkontakte/videoplayer-shared/evergreen";var vs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"].includes(this.current)}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,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||n||c||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 Ri=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var ys=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=Ri()}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 Ts=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,ti=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Po=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Is=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var _l=document.createElement("video"),Nl='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ul='video/mp4; codecs="hev1.1.6.L93.B0"',Lo='video/webm; codecs="vp09.00.10.08"',Mo='video/webm; codecs="av01.0.00M.08"',Hl='audio/mp4; codecs="mp4a.40.2"',jl='audio/webm; codecs="opus"',Ro,ql=async()=>{if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:Mo}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:Lo}})]);Ro={DASH_WEBM_AV1:e,DASH_WEBM:t}};ql().catch(o=>{console.log(_l),console.error(o)});var Es=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 Ro}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:ti(),mse:Po(),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?.(Nl),t=!!Ae()?.isTypeSupported?.(Ul),i=!!Ae()?.isTypeSupported?.(Hl);this._codecs={h264:e,h265:t,vp9:!!Ae()?.isTypeSupported?.(Lo),av1:!!Ae()?.isTypeSupported?.(Mo),aac:i,opus:!!Ae()?.isTypeSupported?.(jl),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 Do="audio/mpeg",xs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Do)},this._codecs={mp3:!!Ae()?.isTypeSupported?.(Do)}}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 Ql}from"@vkontakte/videoplayer-shared/evergreen";var qa=class{constructor(){this.isInited$=new Ql(!1);this._displayChecker=new Ts,this._deviceChecker=new ys(this._displayChecker),this._browserChecker=new vs,this._videoChecker=new Es(this._deviceChecker,this._browserChecker),this._audioChecker=new xs,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)}},R=new qa;var Qa=o=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=R.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 Co(u)}})},Di=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 Co(o)}},Wl=o=>{let t=Object.keys(o).filter(i=>!Di(i));return Qa(t).length>0};var Ci=class{constructor(e){this.subscription=new Yl;this.sessionId$=new Ya(null);this.mediaSessionId$=new Ya(null);this.contentId$=new Ya(null);this.media=null;this.syncMediaState=e=>{this.media=e??null,this.mediaSessionId$.next(e?.mediaSessionId??null),this.contentId$.next(e?.media?.contentId??null);let t=e?.playerState;this.syncPlaybackState(t);let i=e?.media?.duration;ws(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e?.currentTime;if(ws(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let a=this.params.output.isLive$.getValue();t==="PLAYING"&&!a?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new Ss(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastNewProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Di(e.format)),this.subscribe()}subscribe(){let e=i=>{this.params.output.error$.next({category:zl.WTF,id:"ChromecastNewProvider",message:i?.message??"Unknown error",thrown:i})};this.subscription.add(this.params.chromecastConnector.message$.pipe(ii(i=>!!i)).subscribe(i=>{this.handleMessage(i)},e)),this.subscription.add(this.sessionId$.pipe(ii(ws),Bo(),Ga(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(ii(ws),Bo(),Gl(Boolean));this.subscription.add(za({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(ii(({mediaLoaded:i})=>i)).subscribe(()=>{let i=this.params.desiredState.seekState.getState();i.state==="requested"&&this.seek(i.position/1e3)},e)),this.subscription.add(za({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t}).pipe(ii(({mediaLoaded:i})=>i),Ga(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(za({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Ga(30)),mediaLoaded:t}).pipe(ii(({mediaLoaded:i})=>i)).subscribe(({volumeState:i})=>{let{muted:r,volume:s}=i.to;this.setVolume(s,r)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;if(i){let{level:r,muted:s}=i;this.params.output.volume$.next({muted:s??!1,volume:r??0})}}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=gs(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),a=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:a,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Wa(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Wa(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Wa(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){this.log({message:`[setVolume] volume: ${e}, muted: ${t}`}),this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:e,muted:t?!0:null}})}syncPlaybackState(e){let t=this.params.output.isBuffering$.getValue(),i=e==="BUFFERING";switch(t!==i&&this.params.output.isBuffering$.next(i),e){case"PAUSED":k(this.params.desiredState.playbackState,"paused");break;case"PLAYING":k(this.params.desiredState.playbackState,"playing");break;case"IDLE":k(this.params.desiredState.playbackState,"ready");break;case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as Kl,ErrorCategory as Ka,filter as Xl,Subject as Jl,Subscription as Xa,tap as Zl,ValueSubject as Bi,fromEvent as ks}from"@vkontakte/videoplayer-shared/evergreen";var Vo=()=>({castDevice:{},remotePlayer:{},remotePlayerController:{},session:{}}),Oo=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Vi=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new Bi(null);this.sessionId$=new Bi(null);this.subscription=new Xa;this.subscriptionEvents=new Xa;this.sequenceNumber=0;this.presentationAvailable$=new Bi(!1);this.presentationConnection$=new Bi(null);this.message$=new Bi(null);this.errorEvent$=new Jl;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe()}disconnect(){this.log({message:"disconnect"}),this.stopMedia();let e=this.presentationRequest$.getValue();e&&(e.onconnectionavailable=null),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(ks(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),i.onconnectionavailable=r=>{this.log({message:"PresentationRequest connection available"}),this.presentationConnection$.next(r.connection)},window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(()=>{this.log({message:"PresentationRequest reconnect success"})}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();Kl(e,"connect with null presentationRequest"),await e.start()}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:Ka.WTF,id:"ChromecastConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(Zl(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),Xl(e=>!!e)).subscribe(e=>{let t=ks(e,"message").subscribe(s=>{let a=JSON.parse(s.data);a.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(a),this.message$.next(a))}),i=ks(e,"connect").subscribe(()=>{this.send("client_connect")}),r=ks(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:Ka.WTF,id:"ChromecastConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:Ka.WTF,id:"ChromecastConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":this.sessionId$.next(e.message.sessionId);break;case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Oo()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Xa}};import{ValueSubject as Fo,Subject as ed,map as td,Subscription as id,combine as rd,filterChanged as sd,assertNonNullable as ad}from"@vkontakte/videoplayer-shared/evergreen";var it=class o{constructor(e){this.subscription=new id;this.connection$=new Fo(void 0);this.castState$=new Fo("NOT_AVAILABLE");this.errorEvent$=new ed;let t=o.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastNewInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled)&&(this.chromecastConnector=new Vi({appId:e.receiverApplicationId??"07A4434E",logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator}subscribe(){ad(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=rd({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$});this.subscription.add(e.pipe(td(({connection:t})=>!!t),sd()).subscribe(t=>{this.connection$.next(t?Vo():void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};import{isNonNullable as nd,Subject as As,merge as _o}from"@vkontakte/videoplayer-shared/evergreen";var V=class{constructor(e){this.transitionStarted$=new As;this.transitionEnded$=new As;this.transitionUpdated$=new As;this.forceChanged$=new As;this.stateChangeStarted$=_o(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_o(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||nd(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 Oi,debounce as No,ErrorCategory as od,fromEvent as Ct,map as Uo,merge as Ho,observableFrom as ud,Subject as cd,Subscription as Ja,timeout as ld}from"@vkontakte/videoplayer-shared/evergreen";var dd=5,hd=5,pd=500,jo=7e3,Fi=class{constructor(e){this.subscription=new Ja;this.loadMediaTimeoutSubscription=new Ja;this.videoState=new V("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:Oi(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:Oi(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:Oi(e)}break}default:Oi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Di(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 Ja;this.subscription.add(e),this.subscription.add(Ho(this.videoState.stateChangeStarted$.pipe(Uo(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Uo(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 cd;e.add(r.pipe(No(pd)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ct(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)>dd)&&r.next(u),s=u})),e.add(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(a=>{this.logRemoteEvent(a),this.params.output.duration$.next(a.value)}))}t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ct(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<hd&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Oi(a)}}),t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Ct(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Ho(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ud(["init"])).pipe(No(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=gs(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}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(ld(jo).subscribe(()=>s(`timeout(${jo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:od.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Qo}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as md}from"@vkontakte/videoplayer-shared/evergreen";var qo=o=>{try{o.pause(),o.playbackRate=0,md(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as fd,Subscription as bd}from"@vkontakte/videoplayer-shared/evergreen";var Za=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)}},en=window.WeakMap?new WeakMap:new Za,tn=window.WeakMap?new WeakMap:new Map,gd=(o,e=20)=>{let t=0;return fd(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},Te=(o,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=o.querySelector("video"),r=!!i;i?Qo(i):(i=document.createElement("video"),o.appendChild(i)),en.set(i,r);let s=new bd;return s.add(gd(i,e)),tn.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ie=o=>{tn.get(o)?.unsubscribe(),tn.delete(o);let t=en.get(o);en.delete(o),t?Qo(o):qo(o)};import{assertNonNullable as Ni,isNonNullable as Ge,isNullable as yd,fromEvent as ri,merge as Wo,observableFrom as zo,filterChanged as Go,map as Ui,Subject as Yo,Subscription as Td,ValueSubject as Id,ErrorCategory as Ed}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as rn,isNullable as Sd,Subscription as vd}from"@vkontakte/videoplayer-shared/evergreen";var $s=(o,e,t,{equal:i=(a,u)=>a===u,changed$:r,onError:s}={})=>{let a=o.getState(),u=e(),n=Sd(r),c=new vd;return r&&c.add(r.subscribe(h=>{let l=o.getState();i(h,l)&&o.setState(h)},s)),i(u,a)||(t(a),n&&o.setState(a)),c.add(o.stateChangeStarted$.subscribe(h=>{t(h.to),n&&o.setState(h.to)},s)),c},ze=(o,e,t)=>$s(e,()=>o.loop,i=>{rn(i)&&(o.loop=i)},{onError:t}),Ee=(o,e,t,i)=>$s(e,()=>({muted:o.muted,volume:o.volume}),r=>{rn(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)=>$s(e,()=>o.playbackRate,r=>{rn(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),_i=$s;var xd=o=>["__",o.language,o.label].join("|"),wd=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},sn=class o{constructor(e){this.available$=new Yo;this.current$=new Id(void 0);this.error$=new Yo;this.subscription=new Td;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:Ed.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(_i(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ge(s)&&this.setInternal(s)},{equal:(s,a)=>Ge(s)&&Ge(a)&&s.length===a.length&&s.every(({id:u},n)=>u===a[n].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:a})=>a==="internal"))),onError:r})),this.subscription.add(_i(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ge(s)&&this.setExternal(s)},{equal:(s,a)=>Ge(s)&&Ge(a)&&s.length===a.length&&s.every(({id:u},n)=>u===a[n].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:a})=>a==="external"))),onError:r})),this.subscription.add(_i(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(_i(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ni(this.video);let{textTracks:e}=this.video;this.subscription.add(ri(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Wo(ri(e,"addtrack"),ri(e,"removetrack"),zo(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Go((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(Wo(ri(e,"change"),zo(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ui(i=>i&&this.htmlTextTrackToITextTrack(i).id),Go()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ri(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(ri(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;Ge(t.align)&&(r.align=t.align),Ge(t.position)&&(r.position=t.position),Ge(t.size)&&(r.size=t.size),Ge(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ni(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:xd(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){Ni(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(yd(e)||!wd(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){Ni(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){Ni(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)}},Ce=sn;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 Ko=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},an=o=>{let e=Ko(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},Xo=o=>{let e=Ko(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as be,map as Ye,merge as Ps,filterChanged as Zo,isNonNullable as eu,Subject as Ad,filter as nn,mapTo as on,combine as $d,once as Pd,shareReplay as ge,throttle as Ld,ErrorCategory as Md,ValueSubject as tu,Subscription as Rd}from"@vkontakte/videoplayer-shared/evergreen";var kd=3,Jo=(o,e,t=kd)=>{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=>be(o,E).pipe(on(void 0),ge(1)),t=new Rd,i=()=>t.unsubscribe(),r=Ps(be(o,"progress"),be(o,"timeupdate")).pipe(Ye(()=>Jo(o.buffered,o.currentTime)),ge(1)),s=R.browser.isSafari?$d({play:e("play").pipe(Pd()),playing:e("playing")}).pipe(on(void 0),ge(1)):e("playing"),a=be(o,"volumechange").pipe(Ye(()=>({muted:o.muted,volume:o.volume})),ge(1)),u=be(o,"ratechange").pipe(Ye(()=>o.playbackRate),ge(1)),n=be(o,"error").pipe(nn(()=>!!(o.error||o.played.length)),Ye(()=>{let E=o.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:Md.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:o.error??void 0}}),ge(1)),c=be(o,"timeupdate").pipe(Ye(()=>o.currentTime),ge(1)),h=["waiting","seeking","seeked","timeupdate"],l=new Ad,d=.3,p;t.add(Ps(...h.map(E=>be(o,E))).subscribe(E=>{let O=o.currentTime;o.loop&&eu(p)&&eu(O)&&p>=o.duration-d&&O<=d&&l.next(p),p=O}));let m=e("pause").pipe(nn(()=>!o.error&&p!==o.duration),ge(1)),f=be(o,"enterpictureinpicture").pipe(ge(1)),b=be(o,"leavepictureinpicture").pipe(ge(1)),g=new tu(Xo(o));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let S=new tu(an(o)),y=be(o,"fullscreenchange").pipe(ge(1));t.add(y.pipe(Ye(()=>an(o))).subscribe(S));let v=.1,w=1e3,A=be(o,"timeupdate").pipe(Ye(E=>o.duration-o.currentTime<v),Zo(),ge(1)),L=Ps(A.pipe(nn(E=>!o.loop&&E)),be(o,"ended")).pipe(Ld(w),on(void 0),ge(1)),M=Ps(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>be(o,E)),A.pipe(Ye(E=>({type:E?"ended":"unknown"})))).pipe(Ye(E=>R.browser.isFirefox&&E.type==="ended"?o.readyState<2:o.readyState<3),Zo(),ge(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,looped$:l,error$:n,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:be(o,"durationchange").pipe(Ye(()=>o.duration),ge(1)),isBuffering$:M,currentBuffer$:r,volumeState$:a,playbackRateState$:u,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as St}from"@vkontakte/videoplayer-shared/evergreen";var vt=o=>{switch(o){case"mobile":return St.Q_144P;case"lowest":return St.Q_240P;case"low":return St.Q_360P;case"sd":case"medium":return St.Q_480P;case"hd":case"high":return St.Q_720P;case"fullhd":case"full":return St.Q_1080P;case"quadhd":case"quad":return St.Q_1440P;case"ultrahd":case"ultra":return St.Q_2160P}};import{isNonNullable as W,isNullable as Ds,now as hu,isHigher as Cs,isHigherOrEqual as Vt,isInvariantQuality as Bs,isLowerOrEqual as ai,videoSizeToQuality as pu,assertNotEmptyArray as Vs,assertNonNullable as mu}from"@vkontakte/videoplayer-shared/evergreen";var un=!1,rt={},iu=o=>{un=o},ru=()=>{rt={}},su=o=>{o(rt)},Hi=(o,e)=>{un&&(rt.meta=rt.meta??{},rt.meta[o]=e)},Se=class{constructor(e){this.name=e}next(e){if(!un)return;rt.series=rt.series??{};let t=rt.series[this.name]??[];t.push([Date.now(),e]),rt.series[this.name]=t}};import{isHigher as Dd,isHigherOrEqual as fS,isLower as au,isLowerOrEqual as bS,isNonNullable as Ls,isNullable as Cd,videoHeightToQuality as Ms}from"@vkontakte/videoplayer-shared/evergreen";function nu(o,e,t){return!o.max&&o.min===e?"high_quality":!o.min&&o.max===t?"traffic_saving":"unknown"}function si(o,e,t){return Cd(o)||Ls(o.min)&&Ls(o.max)&&au(o.max,o.min)||Ls(o.min)&&e&&Dd(o.min,e)||Ls(o.max)&&t&&au(o.max,t)}function ou({limits:o,highestAvailableHeight:e,lowestAvailableHeight:t}){return si({max:o?.max?Ms(o.max):void 0,min:o?.min?Ms(o.min):void 0},e?Ms(e):void 0,t?Ms(t):void 0)}var fu=new Se("best_bitrate"),Os=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t;var ni=o=>(e,t)=>o*(Number(e.bitrate)-Number(t.bitrate)),yt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=hu()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Fs='Assertion "ABR Tracks is empty array" failed',Rs=new WeakMap,uu=new WeakMap,cu=new WeakMap,ji=(o,e,t,i)=>{let r=[...e].sort(ni(1)),s=[...t].sort(ni(1)),a=s.filter(n=>W(n.bitrate)&&W(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)},qi=(o,e,t,i)=>{let r=Rs.get(e);r||(r=[...e].sort(ni(1)),Rs.set(e,r));let s=Rs.get(t);s||(s=[...t].sort(ni(1)),Rs.set(t,s));let a=cu.get(o);a||(a=s.filter(n=>W(n.bitrate)&&W(o.bitrate)?o.bitrate/n.bitrate>i:!0),cu.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)},lu=o=>"quality"in o,_s=(o,e,t,i)=>{let r=W(i?.last?.bitrate)&&W(t?.bitrate)&&i.last.bitrate<t.bitrate?o.trackCooldownIncreaseQuality:o.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&hu()-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=lu(a)?"video":"audio",n=lu(a)?a.quality:a.bitrate;return e({message:`
6
+ var io="2.0.145";var ye=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ye||{}),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||{}),Pa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Pa||{});var La=(a=>(a.NONE="none",a.INLINE="inline",a.FULLSCREEN="fullscreen",a.SECOND_SCREEN="second_screen",a.PIP="pip",a.INVISIBLE="invisible",a))(La||{}),os=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(os||{});import{assertNever as uo,assertNonNullable as od,isNonNullable as us,ValueSubject as Ra,Subject as ud,Subscription as ld,merge as dd,observableFrom as cd,fromEvent as so,map as ao,tap as no,filterChanged as hd,isNullable as Ma,ErrorCategory as oo}from"@vkontakte/videoplayer-shared/evergreen";var ro=o=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",o),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ls=class{constructor(e){this.connection$=new Ra(void 0);this.castState$=new Ra("NOT_AVAILABLE");this.errorEvent$=new ud;this.realCastState$=new Ra("NOT_AVAILABLE");this.subscription=new ld;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=us(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||ro("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oo.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){us(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ma(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ma(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(so(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return uo(r.sessionState)}})).add(dd(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)),cd([i.getCastState()])).pipe(hd(),ao(pd),no(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",a=us(this.connection$.getValue());if(s&&!a){let u=i.getCurrentSession();od(u);let n=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;(Ma(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:n}))}else!s&&a&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?us(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:oo.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},pd=o=>{switch(o){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return uo(o)}};import{assertNever as lo}from"@vkontakte/videoplayer-shared/evergreen";var Z=(o,e=0,t=0)=>{switch(t){case 0:return o.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return o;let i=new URL(o);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(o);return!i.searchParams.get("offset_p")&&e===0?o:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:lo(t)}return o},ft=(o,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(o);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(o);return Number(t.searchParams.get("offset_p")??0)}default:lo(e)}};var k=(o,e,t=!1)=>{let i=o.getTransition();(t||!i||i.to===e)&&o.setState(e)};import{isNonNullable as md,Subject as ds,merge as co}from"@vkontakte/videoplayer-shared/evergreen";var C=class{constructor(e){this.transitionStarted$=new ds;this.transitionEnded$=new ds;this.transitionUpdated$=new ds;this.forceChanged$=new ds;this.stateChangeStarted$=co(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=co(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||md(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as go}from"@vkontakte/videoplayer-shared/evergreen";var cs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"].includes(this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,a=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,n=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||a||n||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Li=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var hs=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||e.includes(this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Li()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,a=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||a||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),a=parseFloat(s);this._iosVersion=a;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var ps=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Ae=()=>window.ManagedMediaSource||window.MediaSource,ei=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),ho=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),ms=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var fd=document.createElement("video"),bd='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gd='video/mp4; codecs="hev1.1.6.L93.B0"',po='video/webm; codecs="vp09.00.10.08"',mo='video/webm; codecs="av01.0.00M.08"',Sd='audio/mp4; codecs="mp4a.40.2"',vd='audio/webm; codecs="opus"',fo,yd=async()=>{if(!window.navigator.mediaCapabilities)return;let o={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:mo}}),window.navigator.mediaCapabilities.decodingInfo({...o,video:{...o.video,contentType:po}})]);fo={DASH_WEBM_AV1:e,DASH_WEBM:t}};yd().catch(o=>{console.log(fd),console.error(o)});var fs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return fo}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:ei(),mse:ho(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Ae()?.isTypeSupported?.(bd),t=!!Ae()?.isTypeSupported?.(gd),i=!!Ae()?.isTypeSupported?.(Sd);this._codecs={h264:e,h265:t,vp9:!!Ae()?.isTypeSupported?.(po),av1:!!Ae()?.isTypeSupported?.(mo),aac:i,opus:!!Ae()?.isTypeSupported?.(vd),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};var bo="audio/mpeg",bs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(bo)},this._codecs={mp3:!!Ae()?.isTypeSupported?.(bo)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}destroyAudioElement(){if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as Td}from"@vkontakte/videoplayer-shared/evergreen";var Da=class{constructor(){this.isInited$=new Td(!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)}},M=new Da;var Ba=o=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=M.video,s=(i.h264||i.h265)&&i.aac,a=t.mse||t.mms;return o.filter(u=>{switch(u){case"DASH_SEP":return a&&e.mp4&&s;case"DASH_WEBM":return a&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return a&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return a&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return a&&e.mp4&&s;case"DASH_LIVE_CMAF":return a&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return a&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return go(u)}})},Va=o=>{switch(o){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return go(o)}},Id=o=>{let t=Object.keys(o).filter(i=>!Va(i));return Ba(t).length>0};import{assertNever as ti,assertNonNullable as Mt,debounce as So,ErrorCategory as vo,fromEvent as Dt,isNonNullable as yo,map as To,merge as Io,observableFrom as Ed,Subject as xd,Subscription as Ca,timeout as wd,getHighestQuality as kd}from"@vkontakte/videoplayer-shared/evergreen";var Ad=5,$d=5,Pd=500,Eo=7e3,Ri=class{constructor(e){this.subscription=new Ca;this.loadMediaTimeoutSubscription=new Ca;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:ti(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:ti(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:ti(e)}break}default:ti(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Va(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Ca;this.subscription.add(e),this.subscription.add(Io(this.videoState.stateChangeStarted$.pipe(To(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(To(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new xd;e.add(r.pipe(So(Pd)).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)>Ad)&&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<$d&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:ti(a)}}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Io(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ed(["init"])).pipe(So(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];Mt(l);let h=kd(Object.keys(l));Mt(h);let d=l[h];Mt(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];Mt(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Mt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Mt(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Mt(l),i=Z(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",h=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:vo.VIDEO_PIPELINE,message:l,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ti(e)}let a=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);a.contentUrl=i,a.streamType=s,a.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:n}=this.params.meta;return yo(u)&&(a.metadata.title=u),yo(n)&&(a.metadata.subtitle=n),a}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(wd(Eo).subscribe(()=>s(`timeout(${Eo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:vo.VIDEO_PIPELINE,message:s,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as wo}from"@vkontakte/videoplayer-shared/evergreen";import{clearVideoElement as Ld}from"@vkontakte/videoplayer-shared/evergreen";var xo=o=>{try{o.pause(),o.playbackRate=0,Ld(o),o.remove()}catch(e){console.error(e)}};import{fromEvent as Rd,Subscription as Md}from"@vkontakte/videoplayer-shared/evergreen";var Oa=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Fa=window.WeakMap?new WeakMap:new Oa,_a=window.WeakMap?new WeakMap:new Map,Dd=(o,e=20)=>{let t=0;return Rd(o,"ratechange").subscribe(i=>{t++,t>=e&&(o.currentTime=o.currentTime,t=0)})},Te=(o,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=o.querySelector("video"),r=!!i;i?wo(i):(i=document.createElement("video"),o.appendChild(i)),Fa.set(i,r);let s=new Md;return s.add(Dd(i,e)),_a.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ie=o=>{_a.get(o)?.unsubscribe(),_a.delete(o);let t=Fa.get(o);Fa.delete(o),t?wo(o):xo(o)};import{assertNonNullable as Di,isNonNullable as ze,isNullable as Cd,fromEvent as ii,merge as ko,observableFrom as Ao,filterChanged as $o,map as Bi,Subject as Po,Subscription as Od,ValueSubject as Fd,ErrorCategory as _d}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Na,isNullable as Bd,Subscription as Vd}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=Bd(r),l=new Vd;return r&&l.add(r.subscribe(h=>{let d=o.getState();i(h,d)&&o.setState(h)},s)),i(u,a)||(t(a),n&&o.setState(a)),l.add(o.stateChangeStarted$.subscribe(h=>{t(h.to),n&&o.setState(h.to)},s)),l},qe=(o,e,t)=>gs(e,()=>o.loop,i=>{Na(i)&&(o.loop=i)},{onError:t}),Ee=(o,e,t,i)=>gs(e,()=>({muted:o.muted,volume:o.volume}),r=>{Na(r)&&(o.muted=r.muted,o.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),De=(o,e,t,i)=>gs(e,()=>o.playbackRate,r=>{Na(r)&&(o.playbackRate=r)},{changed$:t,onError:i}),Mi=gs;var Nd=o=>["__",o.language,o.label].join("|"),Ud=(o,e)=>{if(o.id===e)return!0;let[t,i,r]=e.split("|");return o.language===i&&o.label===r},Ua=class o{constructor(e){this.available$=new Po;this.current$=new Fd(void 0);this.error$=new Po;this.subscription=new Od;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:_d.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(ii(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ko(ii(e,"addtrack"),ii(e,"removetrack"),Ao(["init"])).pipe(Bi(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),$o((i,r)=>i.length===r.length&&i.every(({id:s},a)=>s===r[a].id))).subscribe(this.available$)),this.subscription.add(ko(ii(e,"change"),Ao(["init"])).pipe(Bi(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Bi(i=>i&&this.htmlTextTrackToITextTrack(i).id),$o()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(ii(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(ii(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:Nd(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))(Cd(e)||!Ud(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Di(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Di(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Be=Ua;var Bt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Lo=o=>{let e=o;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Ha=o=>{let e=Lo(o);return!!(e&&e.fullscreenElement&&e.fullscreenElement===o)},Ro=o=>{let e=Lo(o);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===o)};import{fromEvent as fe,map as Ge,merge as Ss,filterChanged as Do,isNonNullable as Bo,Subject as jd,filter as ja,mapTo as Qa,combine as Qd,once as Wd,shareReplay as be,throttle as qd,ErrorCategory as zd,ValueSubject as Vo,Subscription as Gd}from"@vkontakte/videoplayer-shared/evergreen";var Hd=3,Mo=(o,e,t=Hd)=>{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 Gd,i=()=>t.unsubscribe(),r=Ss(fe(o,"progress"),fe(o,"timeupdate")).pipe(Ge(()=>Mo(o.buffered,o.currentTime)),be(1)),s=M.browser.isSafari?Qd({play:e("play").pipe(Wd()),playing:e("playing")}).pipe(Qa(void 0),be(1)):e("playing"),a=fe(o,"volumechange").pipe(Ge(()=>({muted:o.muted,volume:o.volume})),be(1)),u=fe(o,"ratechange").pipe(Ge(()=>o.playbackRate),be(1)),n=fe(o,"error").pipe(ja(()=>!!(o.error||o.played.length)),Ge(()=>{let E=o.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:zd.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:o.error??void 0}}),be(1)),l=fe(o,"timeupdate").pipe(Ge(()=>o.currentTime),be(1)),h=["waiting","seeking","seeked","timeupdate"],d=new jd,c=.3,p;t.add(Ss(...h.map(E=>fe(o,E))).subscribe(E=>{let O=o.currentTime;o.loop&&Bo(p)&&Bo(O)&&p>=o.duration-c&&O<=c&&d.next(p),p=O}));let m=e("pause").pipe(ja(()=>!o.error&&p!==o.duration),be(1)),f=fe(o,"enterpictureinpicture").pipe(be(1)),b=fe(o,"leavepictureinpicture").pipe(be(1)),g=new Vo(Ro(o));t.add(f.subscribe(()=>g.next(!0))),t.add(b.subscribe(()=>g.next(!1)));let S=new Vo(Ha(o)),y=fe(o,"fullscreenchange").pipe(be(1));t.add(y.pipe(Ge(()=>Ha(o))).subscribe(S));let v=.1,w=1e3,A=fe(o,"timeupdate").pipe(Ge(E=>o.duration-o.currentTime<v),Do(),be(1)),L=Ss(A.pipe(ja(E=>!o.loop&&E)),fe(o,"ended")).pipe(qd(w),Qa(void 0),be(1)),R=Ss(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>fe(o,E)),A.pipe(Ge(E=>({type:E?"ended":"unknown"})))).pipe(Ge(E=>M.browser.isFirefox&&E.type==="ended"?o.readyState<2:o.readyState<3),Do(),be(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,looped$:d,error$:n,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:fe(o,"durationchange").pipe(Ge(()=>o.duration),be(1)),isBuffering$:R,currentBuffer$:r,volumeState$:a,playbackRateState$:u,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b,destroy:i}};import{VideoQuality as bt}from"@vkontakte/videoplayer-shared/evergreen";var gt=o=>{switch(o){case"mobile":return bt.Q_144P;case"lowest":return bt.Q_240P;case"low":return bt.Q_360P;case"sd":case"medium":return bt.Q_480P;case"hd":case"high":return bt.Q_720P;case"fullhd":case"full":return bt.Q_1080P;case"quadhd":case"quad":return bt.Q_1440P;case"ultrahd":case"ultra":return bt.Q_2160P}};import{isNonNullable as q,isNullable as Is,now as qo,isHigher as Es,isHigherOrEqual as Vt,isInvariantQuality as xs,isLowerOrEqual as si,videoSizeToQuality as zo,assertNotEmptyArray as ws,assertNonNullable as Go}from"@vkontakte/videoplayer-shared/evergreen";var Wa=!1,it={},Co=o=>{Wa=o},Oo=()=>{it={}},Fo=o=>{o(it)},Vi=(o,e)=>{Wa&&(it.meta=it.meta??{},it.meta[o]=e)},ge=class{constructor(e){this.name=e}next(e){if(!Wa)return;it.series=it.series??{};let t=it.series[this.name]??[];t.push([Date.now(),e]),it.series[this.name]=t}};import{isHigher as Yd,isHigherOrEqual as qb,isLower as _o,isLowerOrEqual as zb,isNonNullable as vs,isNullable as Kd,videoHeightToQuality as ys}from"@vkontakte/videoplayer-shared/evergreen";function No(o,e,t){return!o.max&&o.min===e?"high_quality":!o.min&&o.max===t?"traffic_saving":"unknown"}function ri(o,e,t){return Kd(o)||vs(o.min)&&vs(o.max)&&_o(o.max,o.min)||vs(o.min)&&e&&Yd(o.min,e)||vs(o.max)&&t&&_o(o.max,t)}function Uo({limits:o,highestAvailableHeight:e,lowestAvailableHeight:t}){return ri({max:o?.max?ys(o.max):void 0,min:o?.min?ys(o.min):void 0},e?ys(e):void 0,t?ys(t):void 0)}var Yo=new ge("best_bitrate"),ks=(o,e,t)=>(e-t)*Math.pow(2,-10*o)+t;var ai=o=>(e,t)=>o*(Number(e.bitrate)-Number(t.bitrate)),St=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=qo()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},As='Assertion "ABR Tracks is empty array" failed',Ts=new WeakMap,Ho=new WeakMap,jo=new WeakMap,Ci=(o,e,t,i)=>{let r=[...e].sort(ai(1)),s=[...t].sort(ai(1)),a=s.filter(n=>q(n.bitrate)&&q(o.bitrate)?o.bitrate/n.bitrate>i:!0),u=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Oi=(o,e,t,i)=>{let r=Ts.get(e);r||(r=[...e].sort(ai(1)),Ts.set(e,r));let s=Ts.get(t);s||(s=[...t].sort(ai(1)),Ts.set(t,s));let a=jo.get(o);a||(a=s.filter(n=>q(n.bitrate)&&q(o.bitrate)?o.bitrate/n.bitrate>i:!0),jo.set(o,a));let u=s.at(Math.round(s.length*r.indexOf(o)/(r.length+1)))??s.at(-1);return u&&a.includes(u)?u:a.length?a.at(-1):s.at(0)},Qo=o=>"quality"in o,$s=(o,e,t,i)=>{let r=q(i?.last?.bitrate)&&q(t?.bitrate)&&i.last.bitrate<t.bitrate?o.trackCooldownIncreaseQuality:o.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&qo()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let a=i.last;i?.recordSwitch(a);let u=Qo(a)?"video":"audio",n=Qo(a)?a.quality:a.bitrate;return e({message:`
7
7
  [last ${u} selected] ${n}
8
- `}),a}return i?.recordSwitch(t),t},Bd=(o,e)=>Math.log(e)/Math.log(o),bu=({tuning:o,container:e,limits:t,panelSize:i})=>{let r=o.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(o.usePixelRatio&&R.display.pixelRatio){let s=R.display.pixelRatio;if(o.pixelRatioMultiplier)r*=o.pixelRatioMultiplier*(s-1)+1;else{let a=o.pixelRatioLogBase,[u=0,n=0,c=0]=o.pixelRatioLogCoefficients,h=Bd(a,u*s+n)+c;Number.isFinite(h)&&(r*=h)}}return W(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}},du=new WeakMap,Ke=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:n,history:c,visible:h,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{Vs(o,Fs);let{containerSizeFactor:b,containerSizeLimit:g}=bu({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&W(u)?u:1,y=du.get(o);y||(y=o.filter(I=>!Bs(I.quality)).sort((I,T)=>Cs(I.quality,T.quality)?-1:1),du.set(o,y));let v=y.at(-1)?.quality,w=y.at(0)?.quality,A=si(r,w,v),L=S*Os(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},M=null;for(let I of y){let T=!0;if(g)if(I.size)T=I.size.width<=g.width&&I.size.height<=g.height;else{let U=g&&pu(g);T=U?ai(I.quality,U):!0}if(!T){x[I.quality]="FitsContainer";continue}let F=p||t,P=W(F)&&isFinite(F)&&W(I.bitrate)?F-s>=I.bitrate*L:!0,N=r?.min===I.quality;if(!P&&!N){x[I.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&W(i.minBufferToSwitchUp)&&n&&!Bs(n.quality)&&(a??0)<i.minBufferToSwitchUp&&Cs(I.quality,n.quality)){x[I.quality]="Buffer";continue}if(!!l&&Vt(I.quality,l)&&!N){x[I.quality]="DroppedFramesLimit";continue}if(!!d&&Vt(I.quality,d)&&!N){x[I.quality]="StallsLimit";continue}let oe=A||(Ds(r?.max)||ai(I.quality,r.max))&&(Ds(r?.min)||Vt(I.quality,r.min)),ue=W(h)&&!h?ai(I.quality,i.backgroundVideoQualityLimit):!0;if(!oe||!ue){x[I.quality]="FitsQualityLimits";continue}M||(M=I)}M&&M.bitrate&&fu.next(M.bitrate);let E=M??y.at(-1)??o[0],O=c?.last,D=_s(i,m,E,c);return W(c)&&D.quality!==O?.quality&&m({message:`
8
+ `}),a}return i?.recordSwitch(t),t},Xd=(o,e)=>Math.log(e)/Math.log(o),Ko=({tuning:o,container:e,limits:t,panelSize:i})=>{let r=o.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(o.usePixelRatio&&M.display.pixelRatio){let s=M.display.pixelRatio;if(o.pixelRatioMultiplier)r*=o.pixelRatioMultiplier*(s-1)+1;else{let a=o.pixelRatioLogBase,[u=0,n=0,l=0]=o.pixelRatioLogCoefficients,h=Xd(a,u*s+n)+l;Number.isFinite(h)&&(r*=h)}}return q(t?.min)&&Vt(t.min,o.highQualityLimit)&&(r*=2),{containerSizeLimit:o.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Wo=new WeakMap,Ye=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:n,history:l,visible:h,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{ws(o,As);let{containerSizeFactor:b,containerSizeLimit:g}=Ko({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&q(u)?u:1,y=Wo.get(o);y||(y=o.filter(I=>!xs(I.quality)).sort((I,T)=>Es(I.quality,T.quality)?-1:1),Wo.set(o,y));let v=y.at(-1)?.quality,w=y.at(0)?.quality,A=ri(r,w,v),L=S*ks(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},R=null;for(let I of y){let T=!0;if(g)if(I.size)T=I.size.width<=g.width&&I.size.height<=g.height;else{let U=g&&zo(g);T=U?si(I.quality,U):!0}if(!T){x[I.quality]="FitsContainer";continue}let F=p||t,P=q(F)&&isFinite(F)&&q(I.bitrate)?F-s>=I.bitrate*L:!0,N=r?.min===I.quality;if(!P&&!N){x[I.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&n&&!xs(n.quality)&&(a??0)<i.minBufferToSwitchUp&&Es(I.quality,n.quality)){x[I.quality]="Buffer";continue}if(!!d&&Vt(I.quality,d)&&!N){x[I.quality]="DroppedFramesLimit";continue}if(!!c&&Vt(I.quality,c)&&!N){x[I.quality]="StallsLimit";continue}let oe=A||(Is(r?.max)||si(I.quality,r.max))&&(Is(r?.min)||Vt(I.quality,r.min)),ue=q(h)&&!h?si(I.quality,i.backgroundVideoQualityLimit):!0;if(!oe||!ue){x[I.quality]="FitsQualityLimits";continue}R||(R=I)}R&&R.bitrate&&Yo.next(R.bitrate);let E=R??y.at(-1)??o[0],O=l?.last,D=$s(i,m,E,l);return q(l)&&D.quality!==O?.quality&&m({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
11
  ${o.map(I=>`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate}, size: ${I.size?.width}:${I.size?.height} }`).join(`
@@ -26,8 +26,8 @@ var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
26
26
  forwardBufferHealth: ${a},
27
27
  bitrateFactor: ${L},
28
28
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
29
- droppedVideoMaxQualityLimit: ${l},
30
- stallsVideoMaxQualityLimit: ${d},
29
+ droppedVideoMaxQualityLimit: ${d},
30
+ stallsVideoMaxQualityLimit: ${c},
31
31
  limitsAreInvalid: ${A},
32
32
  maxQualityLimit: ${r?.max},
33
33
  minQualityLimit: ${r?.min},
@@ -36,9 +36,9 @@ var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
36
36
  ${Object.entries(x).map(([I,T])=>`${I}: ${T}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
- [best video track] ${M?.quality}
39
+ [best video track] ${R?.quality}
40
40
  [selected video track] ${D?.quality}
41
- `}),D},Ns=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:n,history:c,visible:h,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{Vs(o,Fs);let{containerSizeFactor:b,containerSizeLimit:g}=bu({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&W(u)?u:1,y=o.filter(T=>!Bs(T.quality)).sort((T,F)=>Cs(T.quality,F.quality)?-1:1),v=y.at(-1)?.quality,w=y.at(0)?.quality,A=si(r,w,v),L=S*Os(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},E=y.filter(T=>{let F=!0;if(g)if(T.size)F=T.size.width<=g.width&&T.size.height<=g.height;else{let _=g&&pu(g);F=_?ai(T.quality,_):!0}if(!F)return x[T.quality]="FitsContainer",!1;let P=p||t,N=W(P)&&isFinite(P)&&W(T.bitrate)?P-s>=T.bitrate*L:!0,z=r?.min===T.quality;if(!N&&!z)return x[T.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&W(i.minBufferToSwitchUp)&&n&&!Bs(n.quality)&&(a??0)<i.minBufferToSwitchUp&&Cs(T.quality,n.quality))return x[T.quality]="Buffer",!1;if(!!l&&Vt(T.quality,l)&&!z)return x[T.quality]="DroppedFramesLimit",!1;if(!!d&&Vt(T.quality,d)&&!z)return x[T.quality]="StallsLimit",!1;let ue=A||(Ds(r?.max)||ai(T.quality,r.max))&&(Ds(r?.min)||Vt(T.quality,r.min)),U=W(h)&&!h?ai(T.quality,i.backgroundVideoQualityLimit):!0;return!ue||!U?(x[T.quality]="FitsQualityLimits",!1):!0})[0];E&&E.bitrate&&fu.next(E.bitrate);let O=E??y.at(-1)??o[0],D=c?.last,I=_s(i,m,O,c);return W(c)&&I.quality!==D?.quality&&m({message:`
41
+ `}),D},Ps=(o,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:a,playbackRate:u,current:n,history:l,visible:h,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:p,abrLogger:m,panelSize:f})=>{ws(o,As);let{containerSizeFactor:b,containerSizeLimit:g}=Ko({container:e,tuning:i,limits:r,panelSize:f}),S=i.considerPlaybackRate&&q(u)?u:1,y=o.filter(T=>!xs(T.quality)).sort((T,F)=>Es(T.quality,F.quality)?-1:1),v=y.at(-1)?.quality,w=y.at(0)?.quality,A=ri(r,w,v),L=S*ks(a??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},E=y.filter(T=>{let F=!0;if(g)if(T.size)F=T.size.width<=g.width&&T.size.height<=g.height;else{let _=g&&zo(g);F=_?si(T.quality,_):!0}if(!F)return x[T.quality]="FitsContainer",!1;let P=p||t,N=q(P)&&isFinite(P)&&q(T.bitrate)?P-s>=T.bitrate*L:!0,z=r?.min===T.quality;if(!N&&!z)return x[T.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&q(i.minBufferToSwitchUp)&&n&&!xs(n.quality)&&(a??0)<i.minBufferToSwitchUp&&Es(T.quality,n.quality))return x[T.quality]="Buffer",!1;if(!!d&&Vt(T.quality,d)&&!z)return x[T.quality]="DroppedFramesLimit",!1;if(!!c&&Vt(T.quality,c)&&!z)return x[T.quality]="StallsLimit",!1;let ue=A||(Is(r?.max)||si(T.quality,r.max))&&(Is(r?.min)||Vt(T.quality,r.min)),U=q(h)&&!h?si(T.quality,i.backgroundVideoQualityLimit):!0;return!ue||!U?(x[T.quality]="FitsQualityLimits",!1):!0})[0];E&&E.bitrate&&Yo.next(E.bitrate);let O=E??y.at(-1)??o[0],D=l?.last,I=$s(i,m,O,l);return q(l)&&I.quality!==D?.quality&&m({message:`
42
42
  [VIDEO TRACKS ABR]
43
43
  [available video tracks]
44
44
  ${o.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${T.size?.width}:${T.size?.height} }`).join(`
@@ -59,8 +59,8 @@ var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
59
59
  forwardBufferHealth: ${a},
60
60
  bitrateFactor: ${L},
61
61
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
62
- droppedVideoMaxQualityLimit: ${l},
63
- stallsVideoMaxQualityLimit: ${d},
62
+ droppedVideoMaxQualityLimit: ${d},
63
+ stallsVideoMaxQualityLimit: ${c},
64
64
  limitsAreInvalid: ${A},
65
65
  maxQualityLimit: ${r?.max},
66
66
  minQualityLimit: ${r?.min},
@@ -71,7 +71,7 @@ var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
71
71
 
72
72
  [best video track] ${E?.quality}
73
73
  [selected video track] ${I?.quality}
74
- `}),I},Us=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:n,stallsPredictedThroughput:c})=>{Vs(t,Fs);let h=r.considerPlaybackRate&&W(s)?s:1,l=[...t].sort(ni(-1)),d=o.bitrate;mu(d);let p=h*Os(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=ji(o,e,t,r.minVideoAudioRatio),b=c||i;W(b)&&isFinite(b)&&(m=l.find(y=>W(y.bitrate)&&W(f?.bitrate)?b-d>=y.bitrate*p&&y.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,S=m&&_s(r,n,m,u);return W(u)&&S?.bitrate!==g?.bitrate&&n({message:`
74
+ `}),I},Ls=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:n,stallsPredictedThroughput:l})=>{ws(t,As);let h=r.considerPlaybackRate&&q(s)?s:1,d=[...t].sort(ai(-1)),c=o.bitrate;Go(c);let p=h*ks(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Ci(o,e,t,r.minVideoAudioRatio),b=l||i;q(b)&&isFinite(b)&&(m=d.find(y=>q(y.bitrate)&&q(f?.bitrate)?b-c>=y.bitrate*p&&y.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,S=m&&$s(r,n,m,u);return q(u)&&S?.bitrate!==g?.bitrate&&n({message:`
75
75
  [AUDIO TRACKS ABR]
76
76
  [available audio tracks]
77
77
  ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
@@ -83,8 +83,8 @@ var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
83
83
 
84
84
  [limit params]
85
85
  estimatedThroughput: ${i},
86
- stallsPredictedThroughput: ${c},
87
- reserve: ${d},
86
+ stallsPredictedThroughput: ${l},
87
+ reserve: ${c},
88
88
  playbackRate: ${s},
89
89
  playbackRateFactor: ${h},
90
90
  forwardBufferHealth: ${a},
@@ -92,7 +92,7 @@ var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
92
92
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
93
93
 
94
94
  [selected audio track] ${S?.id}
95
- `}),S},Hs=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:n,stallsPredictedThroughput:c})=>{Vs(t,Fs);let h=r.considerPlaybackRate&&W(s)?s:1,l=uu.get(t);l||(l=[...t].sort(ni(-1)),uu.set(t,l));let d=o.bitrate;mu(d);let p=h*Os(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=qi(o,e,t,r.minVideoAudioRatio),b=c||i;W(b)&&isFinite(b)&&(m=l.find(y=>W(y.bitrate)&&W(f?.bitrate)?b-d>=y.bitrate*p&&y.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,S=m&&_s(r,n,m,u);return W(u)&&S?.bitrate!==g?.bitrate&&n({message:`
95
+ `}),S},Rs=(o,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:a,history:u,abrLogger:n,stallsPredictedThroughput:l})=>{ws(t,As);let h=r.considerPlaybackRate&&q(s)?s:1,d=Ho.get(t);d||(d=[...t].sort(ai(-1)),Ho.set(t,d));let c=o.bitrate;Go(c);let p=h*ks(a??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,f=Oi(o,e,t,r.minVideoAudioRatio),b=l||i;q(b)&&isFinite(b)&&(m=d.find(y=>q(y.bitrate)&&q(f?.bitrate)?b-c>=y.bitrate*p&&y.bitrate>=f.bitrate:!1)),m||(m=f);let g=u?.last,S=m&&$s(r,n,m,u);return q(u)&&S?.bitrate!==g?.bitrate&&n({message:`
96
96
  [AUDIO TRACKS ABR]
97
97
  [available audio tracks]
98
98
  ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
@@ -104,8 +104,8 @@ var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
104
104
 
105
105
  [limit params]
106
106
  estimatedThroughput: ${i},
107
- stallsPredictedThroughput: ${c},
108
- reserve: ${d},
107
+ stallsPredictedThroughput: ${l},
108
+ reserve: ${c},
109
109
  playbackRate: ${s},
110
110
  playbackRateFactor: ${h},
111
111
  forwardBufferHealth: ${a},
@@ -113,14 +113,14 @@ var vo="2.0.145-dev.d9a3a83a.0";var fe=(r=>(r.STOPPED="stopped",r.READY="ready",
113
113
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
114
114
 
115
115
  [selected audio track] ${S?.id}
116
- `}),S};var le=o=>new URL(o).hostname;import{assertNever as Iu,assertNonNullable as Eu,combine as ih,debounce as rh,ErrorCategory as xu,filter as wu,filterChanged as sh,isNonNullable as pn,map as Ws,merge as ku,observableFrom as ah,once as nh,Subscription as oh,ValueSubject as mn,videoQualityToHeight as Au,videoSizeToQuality as uh}from"@vkontakte/videoplayer-shared/evergreen";var gu=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"))},we=async(o,e)=>{let t=o.muted;try{await o.play()}catch(i){if(!gu(i))return!1;if(e&&e(),t)return console.warn(i),!1;o.muted=!0;try{await o.play()}catch(r){return gu(r)&&(o.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as qs,isNullable as Fd,assertNonNullable as zi}from"@vkontakte/videoplayer-shared/evergreen";import{isNonNullable as Su,assertNonNullable as js,now as Vd}from"@vkontakte/videoplayer-shared/evergreen";function ae(){return Vd()}function cn(o){return ae()-o}function ln(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 c=a.indexOf("?")>-1?"&":"?";return n&&(a+=c+"lowLat=1",c="&"),u&&(a+=c+"_rnd="+Math.floor(999999999*Math.random())),a}}}function vu(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function oi(o,e,t,i){let r=window.XMLHttpRequest,s,a,u,n=!1,c=0,h,l,d=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(n)return;js(h);let D=cn(h),I;if(D<f){I=f-D,setTimeout(b,I);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,A()},g=D=>(s=D,O),S=D=>(l=D,O),y=()=>(p="json",O),v=()=>{if(!n){if(--c>=0){b(),i&&i();return}n=!0,l&&l(),t&&t()}},w=D=>(d=D,O),A=()=>{h=ae(),a=new r,a.open("get",o);let D=0,I,T=0,F=()=>(js(h),Math.max(h,Math.max(I||0,T||0)));if(s&&a.addEventListener("progress",P=>{let N=ae();s.updateChunk&&P.loaded>D&&(s.updateChunk(F(),P.loaded-D),D=P.loaded,I=N)}),u&&(a.timeout=u,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(n)return;js(a);let P=a.status;if(P>=200&&P<300){let{response:N,responseType:z}=a,J=N?.byteLength;if(typeof J=="number"&&s){let ee=J-D;ee&&s.updateChunk&&s.updateChunk(F(),ee)}z==="json"&&(!N||!Object.values(N).length)?v():(l&&l(),e(N))}else v()}),a.addEventListener("error",()=>{v()}),d){let P=()=>{js(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(T=ae(),a.removeEventListener("readystatechange",P))};a.addEventListener("readystatechange",P)}return a.responseType=p,a.send(),O},O={withBitrateReporting:g,withParallel:w,withJSONResponse:y,withRetryCount:D=>(c=D,O),withRetryInterval:(D,I)=>(Su(D)&&(f=D),Su(I)&&(m=I),O),withTimeout:D=>(u=D,O),withFinally:S,send:A,abort:()=>{a&&(a.abort(),a=void 0),n=!0,l&&l()}};return O}var Qi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let a=t-s.start,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 Wi=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=ae(),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=ae()-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=oi(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=ae()}_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=ae();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 _d}from"@vkontakte/videoplayer-shared/evergreen";var Qs=1e4,dn=3;var Nd=6e4,Ud=10,Hd=1,jd=500,Gi=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 _d,this.chunkRateEstimator=new Qi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ln(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=ln(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*(R.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:n,min:c}=this.autoQualityLimits||{};!ou({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(n&&s.video.height>n||c&&s.video.height<c)||(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||qs(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=()=>{vu(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 Wi(dn,Qs,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,c=null,h=!1,l=()=>{let v=s&&(!h||h===this.rep);return v||t("Not running!"),v},d=(v,w,A)=>{n&&n.abort(),n=oi(this.urlResolver.resolve(v,!1),w,A,()=>this._retryCallback()).withTimeout(Qs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(dn).withFinally(()=>{n=null}).send()},p=(v,w,A)=>{zi(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),w,A,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=v=>{let w=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${w}=>${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 A=ae()-1e4,L=0;for(let M=0;M<this.bufferStates.length;M++){let E=this.bufferStates[M];v=Math.min(v,E.buf),E.ts<A&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${v} drop=${L} jitter=${this.sourceJitter}`);let x=v-Hd;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 w,A=()=>w&&w.start?w.start.length:0,L=P=>w.start[P]/1e3,x=P=>w.dur[P]/1e3,M=P=>w.fragIndex+P,E=(P,N)=>({chunkIdx:M(P),startTS:L(P),dur:x(P),discontinuity:N}),O=()=>{let P=0;if(w&&w.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=N;this.sourceJitter>1&&(J+=this.sourceJitter-1);let ee=w.dur.length-1;for(;ee>=0&&(J-=w.dur[ee],!(J<=0));--ee);P=Math.min(ee,w.dur.length-1-z),P=Math.max(P,0)}return E(P,!0)},D=P=>{let N=A();if(!(N<=0)){if(qs(P)){for(let z=0;z<N;z++)if(L(z)>P)return E(z)}return O()}},I=P=>{let N=A(),z=P?P.chunkIdx+1:0,J=z-w.fragIndex;if(!(N<=0)){if(!P||J<0||J-N>Ud)return t(`Resync: offset=${J} bChunks=${N} chunk=`+JSON.stringify(P)),O();if(!(J>=N))return E(z-w.fragIndex,!1)}},T=(P,N,z)=>{c&&c.abort(),c=oi(this.urlResolver.resolve(P,!0,this.lowLatency),N,z,()=>this._retryCallback()).withTimeout(Qs).withRetryCount(dn).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(P,N)=>{T(v,z=>{if(!l())return;w=z;let J=!!w.lowLatency;J!==this.lowLatency&&f(J);let ee=0;for(let oe=0;oe<w.dur.length;++oe)ee+=w.dur[oe];ee>0&&(zi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,P(D(N))},()=>this._handleNetworkError())},nextChunk:I}},S=()=>{s=!1,u&&u.abort(),n&&n.abort(),c&&c.abort(),zi(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:v=>{let{videoElement:w,logger:A}=this.params,L=g(e.jidxUrl),x,M,E,O,D=0,I,T,F,P=()=>{I&&(clearTimeout(I),I=void 0);let _=Math.max(jd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=D+_,pe=ae(),se=Math.min(1e4,ce-pe);D=pe;let Me=()=>{c||l()&&L.seek(()=>{l()&&(D=ae(),N(),P())})};se>0?I=window.setTimeout(()=>{this.paused?P():Me()},se):Me()},N=()=>{let _;for(;_=L.nextChunk(O);)O=_,ue(_);let ce=L.nextChunk(E);if(ce){if(E&&ce.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?P():(S(),this._initPlayerWith(e));return}oe(ce)}else P()},z=(_,ce)=>{if(!l()||!this.sourceBuffer)return;let pe,se,Me,pt=He=>{window.setTimeout(()=>{l()&&z(_,ce)},He)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),pt(100);else{let He=ae(),ke=w.currentTime;!this.paused&&w.buffered.length>1&&T===ke&&He-F>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),T!==ke&&(T=ke,F=He);let mt=this._getBufferSizeSec();if(mt>30)A(`Buffered ${mt} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:mt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(je){if(je.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Me=this.sourceBuffer.buffered.length,Me!==0&&(pe=this.sourceBuffer.buffered.start(0),se=ke,se-pe>4&&this.sourceBuffer.remove(pe,se-3)),pt(1e3);else throw je}}},J=()=>{M&&x&&(A([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(E)]),z(M,function(){M=null,N()}))},ee=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),oe=_=>{l()&&p(ee(_),(ce,pe)=>{if(l()){if(pe/=1e3,M=ce,E=_,a=_.startTS,pe){let se=Math.min(10,_.dur/pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*se:se}J()}},()=>this._handleNetworkError())},ue=_=>{l()&&(zi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(_),!1)))},U=_=>{l()&&(e.cachedHeader=_,z(_,()=>{x=!0,J()}))};s=!0,L.seek(_=>{if(l()){if(D=ae(),!_){P();return}O=_,!Fd(v)||_.startTS>v?oe(_):(E=_,N())}},v),e.cachedHeader?U(e.cachedHeader):d(e.headerUrl,U,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>a},h}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),qs(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,zi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return qs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let d,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(p=this._getBufferSizeSec(),m=l/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(l)}`);return}d=this._selectQuality(l),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(d,p)=>{let m=ae();if(this.chunkRateEstimator.addInterval(d,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-d,speed:b}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},a=-1/0,u,n=!0,c=()=>{let l=s.get();if(l&&u&&this.autoQuality){if(n&&l>u&&cn(a)<3e4)return;i(l)}n=this.autoQuality};return{updateChunk:(l,d)=>{let p=s.updateChunk(l,d);return p&&c(),p},notifySwitch:l=>{let d=ae();l<u&&(a=d),u=l}}}_fetchManifest(e,t,i){this.manifestRequest=oi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Qs).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;we(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,c)=>{n.video&&r.canPlayType(n.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(n.codecs)&&(n.index=c,u.push(n))}),u.sort(function(n,c){return n.video&&c.video?c.video.height-n.video.height:c.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))},Nd))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as qd,filter as yu,fromEvent as Qd,interval as Wd,isHigher as zd,isInvariantQuality as Gd,isLower as Yd,merge as Kd,Subject as Tu,Subscription as Xd}from"@vkontakte/videoplayer-shared/evergreen";var hn=class{constructor(){this.onDroopedVideoFramesLimit$=new Tu;this.subscription=new Xd;this.playing=!1;this.tracks=[];this.forceChecker$=new Tu;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&&!Gd(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&&zd(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Qd(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Wd(this.droppedFramesChecker.checkTime).pipe(yu(()=>this.playing),yu(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(qd(this.droppedFramesChecker.checkTime)),i=Kd(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])=>Yd(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}},ui=hn;import{map as Jd,Observable as Zd}from"@vkontakte/videoplayer-shared/evergreen";import{fromEvent as eh}from"@vkontakte/videoplayer-shared/evergreen";var Yi=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var th=(o,e)=>new Zd(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((a,u)=>{a.forEach(n=>t.next(n.isIntersecting||Yi()))},{...i,...e});r.observe(o);let s=eh(document,"visibilitychange").pipe(Jd(a=>!document.hidden||Yi())).subscribe(a=>t.next(a));return()=>{r.unobserve(o),s.unsubscribe()}}),Be=th;var ch=["paused","playing","ready"],lh=["paused","playing","ready"],Ki=class{constructor(e){this.subscription=new oh;this.videoState=new V("stopped");this.representations$=new mn([]);this.droppedFramesManager=new ui;this.maxSeekBackTime$=new mn(1/0);this.zeroTime$=new mn(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:xu.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=vt(r.name)??uh(r.video),u=r.bitrate/1e3,n={...r.video};if(!a)continue;let c={id:s,quality:a,bitrate:u,size:n};i.push({track:c,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),pn(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(lh.includes(e)&&(a||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&ch.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Z(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(Z(this.params.source.url,n))}return;default:return Iu(e)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:xu.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(ku(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=Te(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(le(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(Ws(r=>r.map(({track:s})=>s)),wu(r=>!!r.length),nh()).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(sh(),Ws(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(ih({zeroTime:this.zeroTime$.pipe(wu(pn)),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(Ee(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(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Au(r),min:s&&Au(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 Iu(r.to)}},t)).add(ku(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,ah(["init"])).pipe(rh(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),Ie(this.video)}createLiveDashPlayer(){let e=new Gi({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&&pn(t)?t:Ke(e.map(({track:c})=>c),{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 c=e.find(({track:h})=>h.id===s)?.representation;Eu(c,"Representations missing"),this.dash.startPlay(c,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Eu(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(Z(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var $u=Ki;var de=(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 gp,assertNonNullable as Sp,combine as vp,debounce as yp,ErrorCategory as uc,filter as Cn,filterChanged as Dr,fromEvent as Tp,isNonNullable as cc,isNullable as Ip,map as Cr,merge as Br,observableFrom as ba,once as lc,Subscription as Ep,throttle as xp}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Xi}from"@vkontakte/videoplayer-shared/evergreen";var zs=o=>{if(!o)return{id:"EmptyResponse",category:Xi.PARSER,message:"Empty response"};if(o.length<=2&&o.match(/^\d+$/))return{id:`UVError#${o}`,category:Xi.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:Xi.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:Xi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Xi.PARSER,message:"Response is valid XML, but parser failed"}};var he=(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 kn,assertNonNullable as bi,combine as gi,ErrorCategory as Ve,filter as ca,filterChanged as Pr,flattenObject as Lr,fromEvent as ut,getTraceSubscriptionMethod as Xh,interval as An,isNonNullable as Mr,isNullable as ec,map as Si,merge as Ut,now as $n,Subject as ct,Subscription as tc,SubscriptionRemovable as Jh,tap as Zh,throttle as ep,ValueSubject as Y}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as dh,ErrorCategory as Pu,Subject as Lu}from"@vkontakte/videoplayer-shared/evergreen";var hh=18,Mu=!1;try{Mu=R.browser.isSafari&&!!R.browser.safariVersion&&R.browser.safariVersion<=hh}catch(o){console.error(o)}var fn=class{constructor(e){this.bufferFull$=new Lu;this.error$=new Lu;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:Pu.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)};Mu&&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:Pu.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:dh(t)}}},Ru=fn;var ci=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 It,assertNonNullable as ve,ErrorCategory as at,fromEvent as Tn,getExponentialDelay as In,isHigher as Vh,isNonNullable as Et,isNullable as te,now as Ks,once as Oh,Subject as Fh,Subscription as _h,ValueSubject as _t}from"@vkontakte/videoplayer-shared/evergreen";var Gs=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 li=class extends j{};import{assertNever as ph}from"@vkontakte/videoplayer-shared/evergreen";var Ji=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:ph(e)}}};var Zi=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 er=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var G=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 tr=class extends G{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 ir=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rr=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var Ot=class extends G{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,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:u,SAPType:n,SAPDeltaTime:c})}}}};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 G{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 or=class extends G{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ur=class extends G{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 cr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var lr=class extends G{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 dr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pr=class extends G{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var mr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fr=class extends G{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 br=class extends G{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 gr=class extends G{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 Sr=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var vr=class extends G{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 yr=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 fh={ftyp:Zi,moov:er,mvhd:tr,moof:ir,mdat:rr,sidx:Ot,trak:sr,mdia:cr,mfhd:pr,tkhd:lr,traf:mr,tfhd:fr,tfdt:br,trun:gr,minf:dr,sv3d:ar,st3d:nr,prhd:or,proj:hr,equi:ur,uuid:Ji,stbl:Sr,stsd:vr,avc1:yr,unknown:li},st=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||!Gs(a))break;t.push(a),i+=a.size}return t}createBox(e,t){let i=fh[e];return i?new i(t,new o):new li(t,new o)}};var Tt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{Gs(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 gh=new TextDecoder("ascii"),Sh=o=>gh.decode(new DataView(o.buffer,o.byteOffset+4,4))==="ftyp",vh=o=>{let e=new Ot(o,new st),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})},yh=(o,e)=>{let i=new st().parse(o),r=new Tt(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],c=u.source.byteOffset,l=n.source.byteOffset-u.source.byteOffset+n.size;return new DataView(o.buffer,c,l)},Th=o=>{let t=new st().parse(o),i=new Tt(t),r={},a=i.findAll("uuid").at(-1);return a?{serverDataReceivedTimestamp:a.userData.received,serverDataPreparedTime:a.userData.received}:r},Ih=o=>{let t=new st().parse(o);return new Tt(t).find("sidx")?.timescale},Eh=(o,e)=>{let i=new st().parse(o),s=new Tt(i).findAll("traf"),a=s[s.length-1].children.find(l=>l.type==="tfhd"),u=s[s.length-1].children.find(l=>l.type==="tfdt"),n=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return n.sampleDuration.length?c=n.sampleDuration.reduce((l,d)=>l+d,0):c=a.defaultSampleDuration*n.sampleCount,(Number(u.baseMediaDecodeTime)+c)/e*1e3},xh=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 st().parse(o),r=new Tt(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},Du={validateData:Sh,parseInit:xh,getIndexRange:()=>{},parseSegments:vh,parseFeedableSegmentChunk:yh,getChunkEndTime:Eh,getServerLatencyTimestamps:Th,getTimescaleFromIndex:Ih};import{assertNonNullable as bn,isNonNullable as Ou,isNullable as kh}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as wh}from"@vkontakte/videoplayer-shared/evergreen";var Cu={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"}},Bu=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=Ir(o,t),r=i in Cu,s=r?Cu[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),c=a&255>>u,h=Ir(n),l=c*2**((u-1)*8)+h,d=t+u,p;return d+l>o.byteLength?p=new DataView(o.buffer,o.byteOffset+d):p=new DataView(o.buffer,o.byteOffset+d,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+l,value:p,valueSize:l}},Ir=(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},_e=(o,e)=>{switch(e){case"int":return o.getInt8(0);case"uint":return Ir(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:wh(e)}},Ft=(o,e)=>{let t=0;for(;t<o.byteLength;){let i=new DataView(o.buffer,o.byteOffset+t),r=Bu(i);if(!e(r))return;r.type==="master"&&Ft(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},Vu=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=Bu(o);return Ft(r.value,({tag:s,type:a,value:u})=>(s===17143?e=_e(u,a):s===17026?t=_e(u,a):s===17029&&(i=_e(u,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Fu=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ah=[231,22612,22743,167,171,163,160,175],$h=o=>{let e,t,i,r,s=!1,a=!1,u=!1,n,c,h=!1,l=0;return Ft(o,({tag:d,type:p,value:m,valueSize:f})=>{if(d===21419){let b=_e(m,p);c=Ir(b)}else d!==21420&&(c=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+f):d===357149030?s=!0:d===290298740?a=!0:d===2807729?i=_e(m,p):d===17545?r=_e(m,p):d===21420&&c===475249515?n=_e(m,p):d===374648427?Ft(m,({tag:b,type:g,value:S})=>b===30321?(h=_e(S,g)===1,!1):!0):s&&a&&Fu.includes(d)&&(u=!0),!u}),bn(e,"Failed to parse webm Segment start"),bn(t,"Failed to parse webm Segment end"),bn(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:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ph=o=>{if(kh(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Lh=(o,e)=>{let t=!1,i=!1,r=u=>Ou(u.time)&&Ou(u.position),s=[],a;return Ft(o,({tag:u,type:n,value:c})=>{switch(u){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=_e(c,n));break;case 183:break;case 241:a&&(a.position=_e(c,n));break;default:t&&Fu.includes(u)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((u,n)=>{let{time:c,position:h}=u,l=s[n+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},Mh=o=>{let e=0,t=!1;try{Ft(o,i=>i.tag===524531317?i.tagSize<=o.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ah.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},_u={validateData:Vu,parseInit:$h,getIndexRange:Ph,parseSegments:Lh,parseFeedableSegmentChunk:Mh};var Xe=o=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(o);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return _u;case"mp4":return Du}}throw new ReferenceError(`Unsupported mime type ${o}`)};var Je=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var gn=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 Dh,isNullable as Hu}from"@vkontakte/videoplayer-shared/evergreen";var Nu=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var Uu=o=>{try{let e=Rh(),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 Rh(){let o="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",h=`^(?:(?<langtag>${`
116
+ `}),S};var de=o=>new URL(o).hostname;import{assertNever as iu,assertNonNullable as ru,combine as Sc,debounce as vc,ErrorCategory as su,filter as au,filterChanged as yc,isNonNullable as Ka,map as Vs,merge as nu,observableFrom as Tc,once as Ic,Subscription as Ec,ValueSubject as Xa,videoQualityToHeight as ou,videoSizeToQuality as xc}from"@vkontakte/videoplayer-shared/evergreen";var Xo=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"))},we=async(o,e)=>{let t=o.muted;try{await o.play()}catch(i){if(!Xo(i))return!1;if(e&&e(),t)return console.warn(i),!1;o.muted=!0;try{await o.play()}catch(r){return Xo(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 Jo,assertNonNullable as Ms,now as Jd}from"@vkontakte/videoplayer-shared/evergreen";function ae(){return Jd()}function qa(o){return ae()-o}function za(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 l=a.indexOf("?")>-1?"&":"?";return n&&(a+=l+"lowLat=1",l="&"),u&&(a+=l+"_rnd="+Math.floor(999999999*Math.random())),a}}}function Zo(o,e,t){let i=(...r)=>{t.apply(null,r),o.removeEventListener(e,i)};o.addEventListener(e,i)}function ni(o,e,t,i){let r=window.XMLHttpRequest,s,a,u,n=!1,l=0,h,d,c=!1,p="arraybuffer",m=7e3,f=2e3,b=()=>{if(n)return;Ms(h);let D=qa(h),I;if(D<f){I=f-D,setTimeout(b,I);return}f*=2,f>m&&(f=m),a&&a.abort(),a=new r,A()},g=D=>(s=D,O),S=D=>(d=D,O),y=()=>(p="json",O),v=()=>{if(!n){if(--l>=0){b(),i&&i();return}n=!0,d&&d(),t&&t()}},w=D=>(c=D,O),A=()=>{h=ae(),a=new r,a.open("get",o);let D=0,I,T=0,F=()=>(Ms(h),Math.max(h,Math.max(I||0,T||0)));if(s&&a.addEventListener("progress",P=>{let N=ae();s.updateChunk&&P.loaded>D&&(s.updateChunk(F(),P.loaded-D),D=P.loaded,I=N)}),u&&(a.timeout=u,a.addEventListener("timeout",()=>v())),a.addEventListener("load",()=>{if(n)return;Ms(a);let P=a.status;if(P>=200&&P<300){let{response:N,responseType:z}=a,J=N?.byteLength;if(typeof J=="number"&&s){let ee=J-D;ee&&s.updateChunk&&s.updateChunk(F(),ee)}z==="json"&&(!N||!Object.values(N).length)?v():(d&&d(),e(N))}else v()}),a.addEventListener("error",()=>{v()}),c){let P=()=>{Ms(a),a.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(T=ae(),a.removeEventListener("readystatechange",P))};a.addEventListener("readystatechange",P)}return a.responseType=p,a.send(),O},O={withBitrateReporting:g,withParallel:w,withJSONResponse:y,withRetryCount:D=>(l=D,O),withRetryInterval:(D,I)=>(Jo(D)&&(f=D),Jo(I)&&(m=I),O),withTimeout:D=>(u=D,O),withFinally:S,send:A,abort:()=>{a&&(a.abort(),a=void 0),n=!0,d&&d()}};return O}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=ae(),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=ae()-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=ni(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=ae()}_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=ae();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,Ga=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=za(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=za(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*(M.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:n,min:l}=this.autoQualityLimits||{};!Uo({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1).video.height})&&(n&&s.video.height>n||l&&s.video.height<l)||(s.bitrate<e&&a>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||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=()=>{Zo(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(Ga,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,l=null,h=!1,d=()=>{let v=s&&(!h||h===this.rep);return v||t("Not running!"),v},c=(v,w,A)=>{n&&n.abort(),n=ni(this.urlResolver.resolve(v,!1),w,A,()=>this._retryCallback()).withTimeout(Bs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ga).withFinally(()=>{n=null}).send()},p=(v,w,A)=>{Ni(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),w,A,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=v=>{let w=i.playbackRate;i.playbackRate!==v&&(t(`Playback rate switch: ${w}=>${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 A=ae()-1e4,L=0;for(let R=0;R<this.bufferStates.length;R++){let E=this.bufferStates[R];v=Math.min(v,E.buf),E.ts<A&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${v} drop=${L} 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 w,A=()=>w&&w.start?w.start.length:0,L=P=>w.start[P]/1e3,x=P=>w.dur[P]/1e3,R=P=>w.fragIndex+P,E=(P,N)=>({chunkIdx:R(P),startTS:L(P),dur:x(P),discontinuity:N}),O=()=>{let P=0;if(w&&w.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=N;this.sourceJitter>1&&(J+=this.sourceJitter-1);let ee=w.dur.length-1;for(;ee>=0&&(J-=w.dur[ee],!(J<=0));--ee);P=Math.min(ee,w.dur.length-1-z),P=Math.max(P,0)}return E(P,!0)},D=P=>{let N=A();if(!(N<=0)){if(Ds(P)){for(let z=0;z<N;z++)if(L(z)>P)return E(z)}return O()}},I=P=>{let N=A(),z=P?P.chunkIdx+1:0,J=z-w.fragIndex;if(!(N<=0)){if(!P||J<0||J-N>rc)return t(`Resync: offset=${J} bChunks=${N} chunk=`+JSON.stringify(P)),O();if(!(J>=N))return E(z-w.fragIndex,!1)}},T=(P,N,z)=>{l&&l.abort(),l=ni(this.urlResolver.resolve(P,!0,this.lowLatency),N,z,()=>this._retryCallback()).withTimeout(Bs).withRetryCount(Ga).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,N)=>{T(v,z=>{if(!d())return;w=z;let J=!!w.lowLatency;J!==this.lowLatency&&f(J);let ee=0;for(let oe=0;oe<w.dur.length;++oe)ee+=w.dur[oe];ee>0&&(Ni(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,P(D(N))},()=>this._handleNetworkError())},nextChunk:I}},S=()=>{s=!1,u&&u.abort(),n&&n.abort(),l&&l.abort(),Ni(this.filesFetcher),this.filesFetcher.abortAll()};return h={start:v=>{let{videoElement:w,logger:A}=this.params,L=g(e.jidxUrl),x,R,E,O,D=0,I,T,F,P=()=>{I&&(clearTimeout(I),I=void 0);let _=Math.max(ac,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=D+_,pe=ae(),se=Math.min(1e4,le-pe);D=pe;let Re=()=>{l||d()&&L.seek(()=>{d()&&(D=ae(),N(),P())})};se>0?I=window.setTimeout(()=>{this.paused?P():Re()},se):Re()},N=()=>{let _;for(;_=L.nextChunk(O);)O=_,ue(_);let le=L.nextChunk(E);if(le){if(E&&le.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?P():(S(),this._initPlayerWith(e));return}oe(le)}else P()},z=(_,le)=>{if(!d()||!this.sourceBuffer)return;let pe,se,Re,ct=He=>{window.setTimeout(()=>{d()&&z(_,le)},He)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),ct(100);else{let He=ae(),ke=w.currentTime;!this.paused&&w.buffered.length>1&&T===ke&&He-F>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),T!==ke&&(T=ke,F=He);let ht=this._getBufferSizeSec();if(ht>30)A(`Buffered ${ht} seconds; delaying appendBuffer`),ct(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:ht}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(je){if(je.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Re=this.sourceBuffer.buffered.length,Re!==0&&(pe=this.sourceBuffer.buffered.start(0),se=ke,se-pe>4&&this.sourceBuffer.remove(pe,se-3)),ct(1e3);else throw je}}},J=()=>{R&&x&&(A([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(E)]),z(R,function(){R=null,N()}))},ee=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),oe=_=>{d()&&p(ee(_),(le,pe)=>{if(d()){if(pe/=1e3,R=le,E=_,a=_.startTS,pe){let se=Math.min(10,_.dur/pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*se:se}J()}},()=>this._handleNetworkError())},ue=_=>{d()&&(Ni(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(_),!1)))},U=_=>{d()&&(e.cachedHeader=_,z(_,()=>{x=!0,J()}))};s=!0,L.seek(_=>{if(d()){if(D=ae(),!_){P();return}O=_,!ec(v)||_.startTS>v?oe(_):(E=_,N())}},v),e.cachedHeader?U(e.cachedHeader):c(e.headerUrl,U,()=>this._handleNetworkError())},stop:S,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=d=>{if(!this.autoQuality)return;let c,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/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(d)}`);return}c=this._selectQuality(d),c?this._switchToQuality(c):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(c,p)=>{let m=ae();if(this.chunkRateEstimator.addInterval(c,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-c,speed:b}),!0}},get:()=>{let c=this.chunkRateEstimator.getBitRate();return c?c*.85:0}},a=-1/0,u,n=!0,l=()=>{let d=s.get();if(d&&u&&this.autoQuality){if(n&&d>u&&qa(a)<3e4)return;i(d)}n=this.autoQuality};return{updateChunk:(d,c)=>{let p=s.updateChunk(d,c);return p&&l(),p},notifySwitch:d=>{let c=ae();d<u&&(a=c),u=d}}}_fetchManifest(e,t,i){this.manifestRequest=ni(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;we(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,l)=>{n.video&&r.canPlayType(n.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(n.codecs)&&(n.index=l,u.push(n))}),u.sort(function(n,l){return n.video&&l.video?l.video.height-n.video.height:l.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 eu,fromEvent as oc,interval as uc,isHigher as lc,isInvariantQuality as dc,isLower as cc,merge as hc,Subject as tu,Subscription as pc}from"@vkontakte/videoplayer-shared/evergreen";var Ya=class{constructor(){this.onDroopedVideoFramesLimit$=new tu;this.subscription=new pc;this.playing=!1;this.tracks=[];this.forceChecker$=new tu;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&&!dc(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&&lc(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(eu(()=>this.playing),eu(()=>{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}},oi=Ya;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 wc=["paused","playing","ready"],kc=["paused","playing","ready"],ji=class{constructor(e){this.subscription=new Ec;this.videoState=new C("stopped");this.representations$=new Xa([]);this.droppedFramesManager=new oi;this.maxSeekBackTime$=new Xa(1/0);this.zeroTime$=new Xa(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:su.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=gt(r.name)??xc(r.video),u=r.bitrate/1e3,n={...r.video};if(!a)continue;let l={id:s,quality:a,bitrate:u,size:n};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Ka(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(kc.includes(e)&&(a||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&wc.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Z(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(Z(this.params.source.url,n))}return;default:return iu(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:su.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(nu(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=Te(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)),au(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(au(Ka)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(qe(this.video,this.params.desiredState.isLooped,t)).add(Ee(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&&ou(r),min:s&&ou(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 iu(r.to)}},t)).add(nu(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),Ie(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&&Ka(t)?t:Ye(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,a=this.params.desiredState.videoTrack.getTransition(),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 l=e.find(({track:h})=>h.id===s)?.representation;ru(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;ru(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(Z(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}};var uu=ji;var ce=(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 Dh,assertNonNullable as Bh,combine as Vh,debounce as Ch,ErrorCategory as Hu,filter as Sn,filterChanged as kr,fromEvent as Oh,isNonNullable as ju,isNullable as Fh,map as Ar,merge as $r,observableFrom as aa,once as Qu,Subscription as _h,throttle 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 he=(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 dn,assertNonNullable as fi,combine as bi,ErrorCategory as Ce,filter as Js,filterChanged as Ir,flattenObject as Er,fromEvent as ot,getTraceSubscriptionMethod as ph,interval as cn,isNonNullable as xr,isNullable as Bu,map as gi,merge as Nt,now as hn,Subject as ut,Subscription as Vu,SubscriptionRemovable as mh,tap as fh,throttle as bh,ValueSubject as Y}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Ac,ErrorCategory as lu,Subject as du}from"@vkontakte/videoplayer-shared/evergreen";var $c=18,cu=!1;try{cu=M.browser.isSafari&&!!M.browser.safariVersion&&M.browser.safariVersion<=$c}catch(o){console.error(o)}var Ja=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:lu.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)};cu&&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:lu.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)}}},hu=Ja;var ui=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 yt,assertNonNullable as Se,ErrorCategory as st,fromEvent as an,getExponentialDelay as nn,isHigher as Jc,isNonNullable as Tt,isNullable as te,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 li=class extends j{};import{assertNever as Pc}from"@vkontakte/videoplayer-shared/evergreen";var Wi=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 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 G=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 G{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 G{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,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:a,subsegmentDuration:u,SAPType:n,SAPDeltaTime:l})}}}};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 G{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 G{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var tr=class extends G{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 G{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 G{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 G{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 lr=class extends G{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 G{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 G{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:qi,moov:zi,mvhd:Gi,moof:Yi,mdat:Ki,sidx:Ct,trak:Xi,mdia:ir,mfhd:nr,tkhd:rr,traf:or,tfhd:ur,tfdt:lr,trun:dr,minf:sr,sv3d:Ji,st3d:Zi,prhd:er,proj:ar,equi:tr,uuid:Wi,stbl:cr,stsd:hr,avc1:pr,unknown:li},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 li(t,new o)}};var vt=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 vt(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],l=u.source.byteOffset,d=n.source.byteOffset-u.source.byteOffset+n.size;return new DataView(o.buffer,l,d)},Oc=o=>{let t=new rt().parse(o),i=new vt(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 vt(t).find("sidx")?.timescale},_c=(o,e)=>{let i=new rt().parse(o),s=new vt(i).findAll("traf"),a=s[s.length-1].children.find(d=>d.type==="tfhd"),u=s[s.length-1].children.find(d=>d.type==="tfdt"),n=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return n.sampleDuration.length?l=n.sampleDuration.reduce((d,c)=>d+c,0):l=a.defaultSampleDuration*n.sampleCount,(Number(u.baseMediaDecodeTime)+l)/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 vt(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},pu={validateData:Bc,parseInit:Nc,getIndexRange:()=>{},parseSegments:Vc,parseFeedableSegmentChunk:Cc,getChunkEndTime:_c,getServerLatencyTimestamps:Oc,getTimescaleFromIndex:Fc};import{assertNonNullable as Za,isNonNullable as gu,isNullable as Hc}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as Uc}from"@vkontakte/videoplayer-shared/evergreen";var mu={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"}},fu=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 mu,s=r?mu[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),l=a&255>>u,h=fr(n),d=l*2**((u-1)*8)+h,c=t+u,p;return c+d>o.byteLength?p=new DataView(o.buffer,o.byteOffset+c):p=new DataView(o.buffer,o.byteOffset+c,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:c,tagSize:c+d,value:p,valueSize:d}},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},_e=(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=fu(i);if(!e(r))return;r.type==="master"&&Ot(r.value,e),t=r.value.byteOffset-o.byteOffset+r.valueSize}},bu=o=>{if(o.getUint32(0)!==440786851)return!1;let e,t,i,r=fu(o);return Ot(r.value,({tag:s,type:a,value:u})=>(s===17143?e=_e(u,a):s===17026?t=_e(u,a):s===17029&&(i=_e(u,a)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Su=[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,l,h=!1,d=0;return Ot(o,({tag:c,type:p,value:m,valueSize:f})=>{if(c===21419){let b=_e(m,p);l=fr(b)}else c!==21420&&(l=void 0);return c===408125543?(e=m.byteOffset,t=m.byteOffset+f):c===357149030?s=!0:c===290298740?a=!0:c===2807729?i=_e(m,p):c===17545?r=_e(m,p):c===21420&&l===475249515?n=_e(m,p):c===374648427?Ot(m,({tag:b,type:g,value:S})=>b===30321?(h=_e(S,g)===1,!1):!0):s&&a&&Su.includes(c)&&(u=!0),!u}),Za(e,"Failed to parse webm Segment start"),Za(t,"Failed to parse webm Segment end"),Za(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:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Wc=o=>{if(Hc(o.cuesSeekPosition))return;let e=o.segmentStart+o.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},qc=(o,e)=>{let t=!1,i=!1,r=u=>gu(u.time)&&gu(u.position),s=[],a;return Ot(o,({tag:u,type:n,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:a&&r(a)&&s.push(a),a={};break;case 179:a&&(a.time=_e(l,n));break;case 183:break;case 241:a&&(a.position=_e(l,n));break;default:t&&Su.includes(u)&&(i=!0)}return!(t&&i)}),a&&r(a)&&s.push(a),s.map((u,n)=>{let{time:l,position:h}=u,d=s[n+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+h,to:d?e.segmentStart+d.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},vu={validateData:bu,parseInit:Qc,getIndexRange:Wc,parseSegments:qc,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 vu;case"mp4":return pu}}throw new ReferenceError(`Unsupported mime type ${o}`)};var Xe=o=>o instanceof DOMException&&(o.name==="AbortError"||o.code===20);var en=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 Iu}from"@vkontakte/videoplayer-shared/evergreen";var yu=o=>{if(o.includes("/")){let e=o.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(o)};var Tu=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
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(h,"i")}var ju=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},Ne=(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)=>Hu(s)?u:Hu(n)?s:s.padStart(parseInt(n,10),"0"))}return t},Ys=(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",c=s.getAttribute("availabilityStartTime"),h=s.getAttribute("publishTime"),l=s.getElementsByTagName("vk:Attrs")[0],d=l?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=l?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=l?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=l?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;n&&(b={availabilityStartTime:c?new Date(c).getTime():0,publishTime:h?new Date(h).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],v=y.reduce((M,E)=>({...M,[E.id]:E.children}),{}),w=y.reduce((M,E)=>({...M,[E.id]:E.getAttribute("duration")}),{});S?g=ju(S):Object.values(w).filter(M=>M).length&&!n?g=Object.values(w).reduce((M,E)=>M+(ju(E)??0),0):f&&(g=parseInt(f,10));let A=0,L=s.getAttribute("profiles")?.split(",")??[];for(let M of y.map(E=>E.id))for(let E of v[M]){let O=E.getAttribute("id")??"id"+(A++).toString(10),D=E.getAttribute("mimeType")??"",I=E.getAttribute("codecs")??"",T=E.getAttribute("contentType")??D?.split("/")[0],F=E.getAttribute("profiles")?.split(",")??[],P=Uu(E.getAttribute("lang")??"")??{},N=E.querySelector("Label")?.textContent?.trim()??void 0,z=E.querySelectorAll("Representation"),J=E.querySelector("SegmentTemplate"),ee=E.querySelector("Role")?.getAttribute("value")??void 0,oe=T,ue={id:O,language:P.language,isDefault:ee==="main",label:N,codecs:I,hdr:oe==="video"&&gn(I),mime:D,representations:[]};for(let U of z){let _=U.getAttribute("lang")??void 0,ce=N??E.getAttribute("label")??U.getAttribute("label")??void 0,pe=U.querySelector("BaseURL")?.textContent?.trim()??"",se=new URL(pe||u,e).toString(),Me=U.getAttribute("mimeType")??D,pt=U.getAttribute("codecs")??I??"",He;if(T==="text"){let ke=U.getAttribute("id")||"",mt=P.privateuse?.includes("x-auto")||ke.includes("_auto"),je=U.querySelector("SegmentTemplate");if(je){let Ai={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},as=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,ns=parseInt(je.getAttribute("startNumber")??"",10)??1,Yt=parseInt(je.getAttribute("timescale")??"",10),Fa=je.querySelectorAll("SegmentTimeline S")??[],Kt=je.getAttribute("media");if(!Kt)continue;let os=[],us=0,cs="",Xt=0,$i=ns,me=0;for(let Oe of Fa){let Lt=parseInt(Oe.getAttribute("d")??"",10),Re=parseInt(Oe.getAttribute("r")??"",10)||0,ft=parseInt(Oe.getAttribute("t")??"",10);me=Number.isFinite(ft)?ft:me;let Mt=Lt/Yt*1e3,Jt=me/Yt*1e3;for(let qe=0;qe<Re+1;qe++){let bt=Ne(Kt,{...Ai,segmentNumber:$i.toString(10),segmentTime:(me+qe*Lt).toString(10)}),Zt=(Jt??0)+qe*Mt,Li=Zt+Mt;$i++,os.push({time:{from:Zt,to:Li},url:bt})}me+=(Re+1)*Lt,us+=(Re+1)*Mt}Xt=me/Yt*1e3,cs=Ne(Kt,{...Ai,segmentNumber:$i.toString(10),segmentTime:me.toString(10)});let Pi={time:{from:Xt,to:1/0},url:cs},et={type:"template",baseUrl:se,segmentTemplateUrl:Kt,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:Pi,timescale:Yt};He={id:ke,kind:"text",segmentReference:et,profiles:[],duration:g,bitrate:as,mime:"",codecs:"",width:0,height:0,isAuto:mt}}else He={id:ke,isAuto:mt,kind:"text",url:se}}else{let ke=U.getAttribute("contentType")??Me?.split("/")[0]??T,mt=E.getAttribute("profiles")?.split(",")??[],je=parseInt(U.getAttribute("width")??"",10),Ai=parseInt(U.getAttribute("height")??"",10),as=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,ns=U.getAttribute("frameRate")??"",Yt=U.getAttribute("quality")??void 0,Fa=ns?Nu(ns):void 0,Kt=U.getAttribute("id")??"id"+(A++).toString(10),os=ke==="video"?`${Ai}p`:ke==="audio"?`${as}Kbps`:pt,us=`${Kt}@${os}`,cs=[...L,...F,...mt],Xt,$i=U.querySelector("SegmentBase"),me=U.querySelector("SegmentTemplate")??J;if($i){let et=U.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Oe,Lt]=et.split("-").map(bt=>parseInt(bt,10)),Re={from:Oe,to:Lt},ft=U.querySelector("SegmentBase")?.getAttribute("indexRange"),[Mt,Jt]=ft?ft.split("-").map(bt=>parseInt(bt,10)):[],qe=ft?{from:Mt,to:Jt}:void 0;Xt={type:"byteRange",url:se,initRange:Re,indexRange:qe}}else if(me){let et={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},Oe=parseInt(me.getAttribute("timescale")??"",10),Lt=me.getAttribute("initialization")??"",Re=me.getAttribute("media"),ft=parseInt(me.getAttribute("startNumber")??"",10)??1,Mt=Ne(Lt,et);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let Jt=me.querySelectorAll("SegmentTimeline S")??[],qe=[],bt=0,Zt="",Li=0;if(Jt.length){let ls=ft,Fe=0;for(let ei of Jt){let Qe=parseInt(ei.getAttribute("d")??"",10),Rt=parseInt(ei.getAttribute("r")??"",10)||0,ds=parseInt(ei.getAttribute("t")??"",10);Fe=Number.isFinite(ds)?ds:Fe;let _a=Qe/Oe*1e3,xl=Fe/Oe*1e3;for(let hs=0;hs<Rt+1;hs++){let wl=Ne(Re,{...et,segmentNumber:ls.toString(10),segmentTime:(Fe+hs*Qe).toString(10)}),So=(xl??0)+hs*_a,kl=So+_a;ls++,qe.push({time:{from:So,to:kl},url:wl})}Fe+=(Rt+1)*Qe,bt+=(Rt+1)*_a}Li=Fe/Oe*1e3,Zt=Ne(Re,{...et,segmentNumber:ls.toString(10),segmentTime:Fe.toString(10)})}else if(Dh(g)){let Fe=parseInt(me.getAttribute("duration")??"",10)/Oe*1e3,ei=Math.ceil(g/Fe),Qe=0;for(let Rt=1;Rt<ei;Rt++){let ds=Ne(Re,{...et,segmentNumber:Rt.toString(10),segmentTime:Qe.toString(10)});qe.push({time:{from:Qe,to:Qe+Fe},url:ds}),Qe+=Fe}Li=Qe,Zt=Ne(Re,{...et,segmentNumber:ei.toString(10),segmentTime:Qe.toString(10)})}let El={time:{from:Li,to:1/0},url:Zt};Xt={type:"template",baseUrl:se,segmentTemplateUrl:Re,initUrl:Mt,totalSegmentsDurationMs:bt,segments:qe,nextSegmentBeyondManifest:El,timescale:Oe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Me)continue;let Pi={video:"video",audio:"audio",text:"text"}[ke];if(!Pi)continue;oe||=Pi,He={id:us,kind:Pi,segmentReference:Xt,profiles:cs,duration:g,bitrate:as,mime:Me,codecs:pt,width:je,height:Ai,fps:Fa,quality:Yt}}ue.language||=_,ue.label||=ce,ue.mime||=Me,ue.codecs||=pt,ue.hdr||=oe==="video"&&gn(pt),ue.representations.push(He)}if(oe){let U=r[oe].find(_=>_.id===ue.id);if(U&&ue.representations.every(_=>_.segmentReference.type==="template"))for(let _ of U.representations){let ce=ue.representations.find(Me=>Me.id===_.id);if(!ce)continue;let pe=ce.segmentReference,se=_.segmentReference;se.segments.push(...pe.segments),se.nextSegmentBeyondManifest=pe.nextSegmentBeyondManifest}else r[oe].push(ue)}}return{duration:g,streams:r,baseUrls:a,live:b}};import{videoSizeToQuality as Ch}from"@vkontakte/videoplayer-shared/evergreen";var Er=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?vt(s):void 0)??Ch({width:e,height:t});return u&&{id:o,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},qu=({id:o,bitrate:e})=>({id:o,bitrate:e}),Qu=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),Wu=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),Sn=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),vn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),yn=o=>"url"in o,$e=o=>o.type==="template";import{isNonNullable as zu}from"@vkontakte/videoplayer-shared/evergreen";var C=(o,e)=>zu(o)&&zu(e)&&o.readyState==="open"&&Bh(o,e);function Bh(o,e){for(let t=0;t<o.activeSourceBuffers.length;++t)if(o.activeSourceBuffers[t]===e)return!0;return!1}var xr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:n=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new _t(0);this.currentLowLatencySegmentLength$=new _t(0);this.currentSegmentLength$=new _t(0);this.onLastSegment$=new _t(!1);this.fullyBuffered$=new _t(!1);this.playingRepresentation$=new _t(void 0);this.playingRepresentationInit$=new _t(void 0);this.error$=new Fh;this.gaps=[];this.subscription=new _h;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=It(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 Ru(this.sourceBuffer),this.subscription.add(Tn(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},a=>{let u,n=this.mediaSource.readyState;n!=="open"&&(u={id:`SegmentEjection_source_${n}`,category:at.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a}),u??={id:"SegmentEjection",category:at.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:a},this.error$.next(u)})),this.subscription.add(Tn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:at.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!C(this.mediaSource,this.sourceBuffer))return;let n=Math.min(this.bufferLimit,ci(this.sourceBuffer.buffered)*.8);this.bufferLimit=n;let c=this.getForwardBufferDuration(u),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,c<h).catch(l=>{this.handleAsyncError(l,"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=It(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(te(s)||te(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||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();Et(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(!C(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(te(s)||te(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||!C(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();Et(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(n=>n.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let n of this.representations.keys()){let c=t.find(d=>d.id===n);c&&this.representations.set(n,c);let h=this.representations.get(n);if(!h||!$e(h.segmentReference)){this.isSeekingLive=!1;return}let l=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ve(r,`Representation not found by id ${i}`);let s=this.segments.get(i);ve(s,"No segments for starting representation");let a=this.initData.get(i);if(ve(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!c?.live,this.baseUrls=c?.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){!C(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);ve(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(te(u)||te(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||!C(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();Et(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(){!te(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(te(e)||te(this.downloadingRepresentationId)||te(this.playingRepresentationId)||te(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||Et(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}`),te(r)||te(s))return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);Et(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 d=this.getForwardBufferDuration(e),p=Er(i),m=Er(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Et(p)&&Et(m)&&Vh(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?u+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+n&&(u=a?a.time.to+n:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let w=v.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:y,status:w?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ci(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<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 d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))d="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(h,t,d).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 l=r.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Et(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations);for(let i of t){if(!i||!$e(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,n=r?.findIndex(c=>u>=c.time.from+s&&u<=c.time.to+s);if(n===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(n+1);this.segments.set(i.id,[...a,...c])}}}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)}}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),c=Ne(r.segmentTemplateUrl,{segmentTime:n});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(he(this.sourceBuffer.buffered,p)&&he(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,n=0,c=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<a.length&&(u<=h||n<=l);d++){let p=a[d];if(u+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}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:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await It(u,async function*(){let h=In(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,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=Ks(),!h)return;let l=new DataView(h),d=Xe(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(l,f)}n&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(l);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Je(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 It(a,async function*(){let n=In(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,n),Tn(window,"online").pipe(Oh()).subscribe(()=>{c(),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=Ks(),this.failedDownloads=0}catch(n){this.abortActiveSegments(e),Je(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=Ks(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:n,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}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?(c,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ks();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:at.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}: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||!C(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 c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=Xe(a.mime).parseFeedableSegmentChunk(c,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||!C(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let n of this.activeSegments){let{segment:c}=n;if(n.representationId!==t)continue;if(s.aborted){await a();continue}let h=c.byte.from-i,l=c.byte.to-i,d=l-h+1,p=h<r,m=l<=r;if(!p)continue;let f=Xe(u.mime);if(c.status==="downloading"&&m){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+h,d);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(n,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(n.loadedBytes=Math.min(d,r-h),n.loadedBytes>n.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+h+n.feedingBytes,n.loadedBytes-n.feedingBytes),g=n.loadedBytes===d?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(c.status="partially_fed",n.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(n.fedBytes+=g.byteLength,n.fedBytes===d&&this.onSegmentFullyAppended(n,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(te(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&R.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(he(this.sourceBuffer.buffered,e.segment.time.from,100)&&he(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:at.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",yn(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",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,u=(!i&&this.failedDownloads>0?It(this.destroyAbortController.signal,async function*(){let n=In(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Xe(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async n=>{if(!n)return;let{init:c,dataView:h,segments:l}=n,d=h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&$e(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,n=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:at.WTF,message:"loadInit threw",thrown:n})});return this.initData.set(e.id,u),u}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||te(e))return!1;let r=[],s=0,a=n=>{n.sort((h,l)=>h.from-l.from);let c=[n[0]];for(let h=1;h<n.length;h++){let{from:l,to:d}=n[h],p=c[c.length-1];p.to>=l?p.to=Math.max(p.to,d):c.push(n[h])}return c},u=n=>{if(s>=t)return r;r.push({...n.time}),r=a(r);let c=yn(n)?n.size??0:n.byte.to-n.byte.from;s+=c};for(let n of this.segments.values())for(let c of n){let h=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(h||l)&&c.status==="fed"&&u(c)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let c=this.sourceBuffer.buffered.start(n)*1e3,h=this.sourceBuffer.buffered.end(n)*1e3,l=0;for(let d of this.segments.values())for(let p of d)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)&&l++;if(l===this.segments.size){let d={time:{from:c,to:h},url:"",status:"none"};u(d)}}if(r.length&&i){let n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let h of c)h.time.from>=e+n&&h.status==="fed"&&u(h)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,h)=>c||h,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||te(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!C(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||!C(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:at.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(te(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||te(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),c=e.filter(h=>a>=h.from&&a<h.to-t||u>h.from+t&&u<=h.to);n||(c.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:at.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var xt=o=>{let e=new URL(o);return e.searchParams.set("quic","1"),e.toString()};var Xs=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 wr,assertNever as Gu,fromEvent as Yu,merge as Nh,now as kr,Subject as Nt,ValueSubject as En,flattenObject as pi,ErrorCategory as Ar,SubscriptionRemovable as Uh}from"@vkontakte/videoplayer-shared/evergreen";var Js=o=>{let e=new URL(o);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ea=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new Nt;this.firstBytesManifest$=new Nt;this.manifestReceived$=new Nt;this.firstBytesRequested$=new Nt;this.firstBytesReceived$=new Nt;this.lastConnectionType$=new En(void 0);this.lastConnectionReused$=new En(void 0);this.lastRequestFirstBytes$=new En(void 0);this.recoverableError$=new Nt;this.error$=new Nt;this.abortAllController=new AbortController;this.subscription=new Uh;this.fetchManifest=wr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=xt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Js(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},{type:"manifest"}).catch(Zs);return r?(t.log("success",pi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",pi({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:n=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:h=!1}={}){let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(l,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),l=T.toString();break}default:Gu(t)}this.requestQuic&&(l=xt(l));let m=this.abortAllController.signal,f;if(a){let T=new AbortController;if(f=Nh(Yu(this.abortAllController.signal,"abort"),Yu(a,"abort")).subscribe(()=>{try{T.abort()}catch(F){Zs(F)}}),this.subscription.add(f),this.abortAllController.signal.aborted||a.aborted)try{T.abort()}catch(F){Zs(F)}m=T.signal}let b=0,g=kr();p.log("startRequest",pi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:n,requestStartedAt:g})),this.firstBytesRequested$.next();let S=yield this.doFetch(l,{priority:s,headers:d,signal:m},{ignoreNetworkErrors:h}),y=kr();if(!S)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(y-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let T=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:T}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let T=kr(),F={requestStartedAt:g,requestEndedAt:T,duration:T-g};return p.log("endRequest",pi(F)),p.end(),S.arrayBuffer()}let v=S.body;if(u){let T;[v,T]=S.body.tee(),this.throughputEstimator?.trackStream(T,n)}let w=v.getReader(),A,L=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(L)&&(A=L),!A&&i&&(A=i.to-i.from+1);let x=A?new Uint8Array(A):new Uint8Array(0),M=!1,E=T=>{this.unsubscribeAbortSubscription(f),M=!0,Zs(T)},O=wr(m,async function*({done:T,value:F}){if(b===0&&(this.lastRequestFirstBytes$.next(kr()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!T&&F){if(c&&A)x.set(F,b),b+=F.byteLength;else{let P=new Uint8Array(x.length+F.length);P.set(x),P.set(F,x.length),x=P,b+=F.byteLength}r?.(new DataView(x.buffer),b),yield w?.read().then(O,E)}}.bind(this));yield w?.read().then(O,E),this.unsubscribeAbortSubscription(f);let D=kr(),I={failed:M,requestStartedAt:g,requestEndedAt:D,duration:D-g};return M?(p.error("endRequest",pi(I)),p.end(),null):(p.log("endRequest",pi(I)),p.end(),x.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,n=!1,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,n=s+1===c,n&&(a=Math.min(c,r),u=Math.max(h,s))),a=Math.min(a,0);let l=yield this.fetch(e.url,{range:{from:a,to:u},measureThroughput:!1,...i});if(!l)return null;let d=new DataView(l,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let p=t.parseInit(d),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(n)f=new DataView(l,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(l),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,{measureThroughput:!1,...t});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}=Xs(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){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:Gu(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await fetch(e,t);if(r.ok)return i?.type==="manifest"&&this.firstBytesManifest$.next(),r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),a=parseInt(s);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ar.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ar.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ar.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ar.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Ar.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Zs=o=>{if(!Je(o))throw o};var nt=(o,e,t)=>t*e+(1-t)*o,xn=(o,e)=>o.reduce((t,i)=>t+i,0)/e,Ku=(o,e,t,i)=>{let r=0,s=t,a=xn(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 Hh,ValueSubject as Xu}from"@vkontakte/videoplayer-shared/evergreen";var wt=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 Xu(e.initial),this.debounced$=new Xu(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Se(`raw_${t}`),this.smoothedSeries$=new Se(`smoothed_${t}`),this.reportedSeries$=new Se(`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)&&(Hh(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 ta=class extends wt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=nt(this.slow,e,this.params.emaAlphaSlow),this.fast=nt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ia=class extends wt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=xn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=nt(this.emaSmoothed,e,this.params.emaAlpha);let i=Ku(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ra=class extends wt{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?nt(this.smoothed,t,this.params.emaAlpha):t}};var ot=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ta({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ia({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 ra({initial:e,label:"liveEdgeDelay",...t})}};var mi=(o,e)=>{o&&o.playbackRate!==e&&(o.playbackRate=e)};import{isNullable as jh,ValueSubject as qh}from"@vkontakte/videoplayer-shared/evergreen";var $r=class o{constructor(e,t){this.currentRepresentation$=new qh(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!jh(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,a=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<a||e>u)continue;let n=r.segments.find(c=>c.time.from<=e&&c.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 aa}from"@vkontakte/videoplayer-shared/evergreen";var sa=o=>{let{webmDecodingInfo:e}=R.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:aa(o)}},Ju=({webmCodec:o,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...sa(o),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(R.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",...sa(o),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...sa(o),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...sa(o),...s,"HLS","HLS_ONDEMAND"];default:aa(e)}if(R.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:aa(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},Zu=({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=R.device.isMac&&R.browser.isSafari;if(R.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:aa(o)}else R.video.nativeHlsSupported&&!n&&!R.browser.isChromiumBased?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"]},wn=o=>o?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],na=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)},oa=o=>{let e=o.map(i=>fi(i)),{codecs:t}=R.video;return Gh().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})},ua=o=>{let e=o.map(i=>fi(i)),{codecs:t}=R.video;return Yh().filter(i=>{if(e.includes(i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},fi=o=>o.split(".")[0].replace("0",""),Gh=()=>["av1","vp9","hev1","avc1"],Yh=()=>["opus","mp4a"];var tp=["timeupdate","progress","play","seeked","stalled","waiting"],ip=["timeupdate","progress","loadeddata","playing","seeked"];var la=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new tc;this.subscriptionRemovable=new Jh;this.representationSubscription=new tc;this.state$=new V("none");this.currentVideoRepresentation$=new Y(void 0);this.currentVideoRepresentationInit$=new Y(void 0);this.currentAudioRepresentation$=new Y(void 0);this.currentVideoSegmentLength$=new Y(0);this.currentAudioSegmentLength$=new Y(0);this.error$=new ct;this.manifestRequested$=new ct;this.firstBytesManifest$=new ct;this.manifestReceived$=new ct;this.firstBytesRequested$=new ct;this.firstBytesReceived$=new ct;this.lastConnectionType$=new Y(void 0);this.lastConnectionReused$=new Y(void 0);this.lastRequestFirstBytes$=new Y(void 0);this.currentLiveTextRepresentation$=new Y(null);this.isLive$=new Y(!1);this.isActiveLive$=new Y(!1);this.isLowLatency$=new Y(!1);this.liveDuration$=new Y(0);this.liveSeekableDuration$=new Y(0);this.liveAvailabilityStartTime$=new Y(0);this.liveStreamStatus$=new Y(void 0);this.bufferLength$=new Y(0);this.liveLatency$=new Y(void 0);this.liveLoadBufferLength$=new Y(0);this.livePositionFromPlayer$=new Y(0);this.currentStallDuration$=new Y(0);this.videoLastDataObtainedTimestamp$=new Y(0);this.fetcherRecoverableError$=new ct;this.fetcherError$=new ct;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ct;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new AbortController;this.initManifest=kn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Z(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:Ve.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=kn(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:Ve.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Ys(e??"",this.manifestUrlString)}catch(n){let c=zs(e)??{id:"ManifestParsing",category:Ve.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(c)}if(!t)return null;let i=(n,c,h)=>!!(this.element?.canPlayType?.(c)&&Ae()?.isTypeSupported?.(`${c}; codecs="${h}"`)||n==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:n,latestSegmentPublishTime:c,streamIsUnpublished:h,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((c-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";if(l||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p),l&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(f=>{this.error$.next({id:"updateManifest",category:Ve.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let n of["video","audio"]){let h=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p));r[n]=h;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let d=h.map(({codecs:p})=>p);n==="audio"&&(a=ua(d),l=a[0]),n==="video"&&(s=oa(d),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?l=this.forceVideoCodec:l=s[0]),l&&(r[n]=h.filter(({codecs:p})=>fi(p)===l))}else{let d=new Set(h.map(({codecs:p})=>p));l=na(d),l&&(r[n]=h.filter(({codecs:p})=>p.startsWith(l)))}if(n==="video"){let d=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);R.display.isHDR&&d&&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",Lr(u)),u}.bind(this));this.initRepresentations=kn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Lr({initialVideo:e,initialAudio:t,sourceHls:i})),bi(this.manifest),bi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=l=>{this.representationSubscription.add(ut(l,"error").pipe(ca(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:Ve.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Is();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ti())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,d)=>[...l,...d.representations],[]);if(this.videoBufferManager=new xr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],Mr(t)){let l=this.manifest.streams.audio.reduce((d,p)=>[...d,...p.representations],[]);this.audioBufferManager=new xr("audio",this.source,l,a),this.bufferManagers.push(this.audioBufferManager)}if($r.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new $r(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ut(...ip.map(l=>ut(this.element,l))).pipe(Si(l=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),Pr(),Zh(l=>{l>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ut(ut(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Pr()).subscribe(d=>this.liveStreamEndTimestamp=$n())),this.subscription.add(ut(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=An(d).subscribe(p=>{let m=gt(this.manifestUrlString,2);this.manifestUrlString=Z(this.manifestUrlString,m+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ut(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(gi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Si(({isActiveLive:d,isLowLatency:p})=>d&&p),Pr()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||mi(this.element,1)})),this.representationSubscription.add(gi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ca(({bufferLength:d,isActiveLive:p,isLowLatency:m})=>p&&m&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let p=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(p,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add(gi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ca(({isLive:d})=>d),Pr((d,p)=>p.bufferLength<d.bufferLength),Si(({rtt:d,bufferLength:p,segmentServerLatency:m})=>{let f=gt(this.manifestUrlString,2);return(d/2+p+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(gi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:p,isLowLatency:m})=>{if(!m||!p)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=d-f;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(S)>b&&(y=1+Math.sign(S)*g),mi(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let p=0;if(d){let m=(this.element?.currentTime??0)*1e3;p=Math.min(...this.bufferManagers.map(b=>b.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==p&&this.liveLoadBufferLength$.next(p)}));let l=0;this.representationSubscription.add(gi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ep(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:p})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=gt(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,v=isFinite(d)?d:p,w=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let L="none";if(w?L="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(x=>x.proceedLowLatencyLive()),L="active_low_latency"):f!==0&&v<g?L="live_forward_buffering":v<g+y&&(L="live_with_target_offset"),isFinite(d)&&(l=d>l?d:l),L==="live_forward_buffering"||L==="live_with_target_offset"){let x=l-(g+S),M=this.normalizeLiveOffset(Math.trunc(f+x/m)),E=Math.abs(M-f),O=0;!d||E<=this.tuning.dashCmafLive.offsetCalculationError?O=f:M>0&&E>this.tuning.dashCmafLive.offsetCalculationError&&(O=M),this.manifestUrlString=Z(this.manifestUrlString,O,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(l=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:Ve.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let n=Ut(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(Si(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),c=Ut(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(Si(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue()))),h=gi({allBuffersFull:n,someBufferEnded:c}).pipe(Pr(),Si(({allBuffersFull:l,someBufferEnded:d})=>l&&d),ca(l=>l));if(this.representationSubscription.add(Ut(this.forceEnded$,h).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:Ve.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:l})}})),this.representationSubscription.add(Ut(...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(d=>{l&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();return}this.error$.next({id:"OpenOfStream",category:Ve.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),d()},{once:!0})})}if(!this.isLive$.getValue()){let l=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(d=>d.representations).flatMap(d=>{let p=[];return d.duration&&p.push(d.duration),$e(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&p.push(d.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...l)/1e3}this.audioBufferManager&&Mr(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=An(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ve.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 ea({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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=ot.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){bi(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?$n()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Z(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){bi(this.element),this.state$.setState("running"),this.subscription.add(Ut(...tp.map(e=>ut(this.element,e)),ut(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ve.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ut(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ut(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&he(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:a}=this.tuning.dash,u=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let h=this.currentStallDuration$.getValue();h+=a,this.currentStallDuration$.next(h);let l={timeInWaiting:h},d=$n(),p=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let f=this.audioBufferManager?.lastDataObtainedTimestamp??0,b=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,S=b<p&&d-m>r,y=this.audioBufferManager&&g<p&&d-f>r;if((!t||c)&&((S||y)&&h>r||h>=i))throw new Error(`Stall timeout exceeded: ${h} ms`);if(u&&h%s===0){let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(v),this.updateManifest()):this.seekLive(v).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Ve.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),l.liveLastOffset=v}else{let v=this.element.currentTime*1e3;this.videoBufferManager?.maintain(v),this.audioBufferManager?.maintain(v),l.position=v}this.tracer.log("stallIntervalCallback",Lr(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=An(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ve.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){bi(this.element),bi(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),he(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ec(this.element)||ec(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Lr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Mr(this.element)&&Mr(this.source)&&Mr(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Xh(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))}normalizeLiveOffset(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 c of n.gaps)(r&&c.persistent||n.playingRepresentation$.getValue()===c.representation)&&c.from-u<=s&&c.to+u>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?a.push(1/0):a.push(c.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",Lr(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var da=class{constructor(e,t){this.fov=e,this.orientation=t}};var ha=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 rc=`attribute vec2 a_vertex;
123
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(h,"i")}var Eu=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},Ne=(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)=>Iu(s)?u:Iu(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(R=>R.textContent?.trim()??""),u=a.at(0)??"",n=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),h=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],c=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;n&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:h?new Date(h).getTime():0,latestSegmentPublishTime:c?new Date(c).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],v=y.reduce((R,E)=>({...R,[E.id]:E.children}),{}),w=y.reduce((R,E)=>({...R,[E.id]:E.getAttribute("duration")}),{});S?g=Eu(S):Object.values(w).filter(R=>R).length&&!n?g=Object.values(w).reduce((R,E)=>R+(Eu(E)??0),0):f&&(g=parseInt(f,10));let A=0,L=s.getAttribute("profiles")?.split(",")??[];for(let R of y.map(E=>E.id))for(let E of v[R]){let O=E.getAttribute("id")??"id"+(A++).toString(10),D=E.getAttribute("mimeType")??"",I=E.getAttribute("codecs")??"",T=E.getAttribute("contentType")??D?.split("/")[0],F=E.getAttribute("profiles")?.split(",")??[],P=Tu(E.getAttribute("lang")??"")??{},N=E.querySelector("Label")?.textContent?.trim()??void 0,z=E.querySelectorAll("Representation"),J=E.querySelector("SegmentTemplate"),ee=E.querySelector("Role")?.getAttribute("value")??void 0,oe=T,ue={id:O,language:P.language,isDefault:ee==="main",label:N,codecs:I,hdr:oe==="video"&&en(I),mime:D,representations:[]};for(let U of z){let _=U.getAttribute("lang")??void 0,le=N??E.getAttribute("label")??U.getAttribute("label")??void 0,pe=U.querySelector("BaseURL")?.textContent?.trim()??"",se=new URL(pe||u,e).toString(),Re=U.getAttribute("mimeType")??D,ct=U.getAttribute("codecs")??I??"",He;if(T==="text"){let ke=U.getAttribute("id")||"",ht=P.privateuse?.includes("x-auto")||ke.includes("_auto"),je=U.querySelector("SegmentTemplate");if(je){let ki={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},Jr=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,Zr=parseInt(je.getAttribute("startNumber")??"",10)??1,Gt=parseInt(je.getAttribute("timescale")??"",10),Aa=je.querySelectorAll("SegmentTimeline S")??[],Yt=je.getAttribute("media");if(!Yt)continue;let es=[],ts=0,is="",Kt=0,Ai=Zr,me=0;for(let Oe of Aa){let Pt=parseInt(Oe.getAttribute("d")??"",10),Me=parseInt(Oe.getAttribute("r")??"",10)||0,pt=parseInt(Oe.getAttribute("t")??"",10);me=Number.isFinite(pt)?pt:me;let Lt=Pt/Gt*1e3,Xt=me/Gt*1e3;for(let Qe=0;Qe<Me+1;Qe++){let mt=Ne(Yt,{...ki,segmentNumber:Ai.toString(10),segmentTime:(me+Qe*Pt).toString(10)}),Jt=(Xt??0)+Qe*Lt,Pi=Jt+Lt;Ai++,es.push({time:{from:Jt,to:Pi},url:mt})}me+=(Me+1)*Pt,ts+=(Me+1)*Lt}Kt=me/Gt*1e3,is=Ne(Yt,{...ki,segmentNumber:Ai.toString(10),segmentTime:me.toString(10)});let $i={time:{from:Kt,to:1/0},url:is},Ze={type:"template",baseUrl:se,segmentTemplateUrl:Yt,initUrl:"",totalSegmentsDurationMs:ts,segments:es,nextSegmentBeyondManifest:$i,timescale:Gt};He={id:ke,kind:"text",segmentReference:Ze,profiles:[],duration:g,bitrate:Jr,mime:"",codecs:"",width:0,height:0,isAuto:ht}}else He={id:ke,isAuto:ht,kind:"text",url:se}}else{let ke=U.getAttribute("contentType")??Re?.split("/")[0]??T,ht=E.getAttribute("profiles")?.split(",")??[],je=parseInt(U.getAttribute("width")??"",10),ki=parseInt(U.getAttribute("height")??"",10),Jr=parseInt(U.getAttribute("bandwidth")??"",10)/1e3,Zr=U.getAttribute("frameRate")??"",Gt=U.getAttribute("quality")??void 0,Aa=Zr?yu(Zr):void 0,Yt=U.getAttribute("id")??"id"+(A++).toString(10),es=ke==="video"?`${ki}p`:ke==="audio"?`${Jr}Kbps`:ct,ts=`${Yt}@${es}`,is=[...L,...F,...ht],Kt,Ai=U.querySelector("SegmentBase"),me=U.querySelector("SegmentTemplate")??J;if(Ai){let Ze=U.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Oe,Pt]=Ze.split("-").map(mt=>parseInt(mt,10)),Me={from:Oe,to:Pt},pt=U.querySelector("SegmentBase")?.getAttribute("indexRange"),[Lt,Xt]=pt?pt.split("-").map(mt=>parseInt(mt,10)):[],Qe=pt?{from:Lt,to:Xt}:void 0;Kt={type:"byteRange",url:se,initRange:Me,indexRange:Qe}}else if(me){let Ze={representationId:U.getAttribute("id")??void 0,bandwidth:U.getAttribute("bandwidth")??void 0},Oe=parseInt(me.getAttribute("timescale")??"",10),Pt=me.getAttribute("initialization")??"",Me=me.getAttribute("media"),pt=parseInt(me.getAttribute("startNumber")??"",10)??1,Lt=Ne(Pt,Ze);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let Xt=me.querySelectorAll("SegmentTimeline S")??[],Qe=[],mt=0,Jt="",Pi=0;if(Xt.length){let rs=pt,Fe=0;for(let Zt of Xt){let We=parseInt(Zt.getAttribute("d")??"",10),Rt=parseInt(Zt.getAttribute("r")??"",10)||0,ss=parseInt(Zt.getAttribute("t")??"",10);Fe=Number.isFinite(ss)?ss:Fe;let $a=We/Oe*1e3,sd=Fe/Oe*1e3;for(let as=0;as<Rt+1;as++){let ad=Ne(Me,{...Ze,segmentNumber:rs.toString(10),segmentTime:(Fe+as*We).toString(10)}),to=(sd??0)+as*$a,nd=to+$a;rs++,Qe.push({time:{from:to,to:nd},url:ad})}Fe+=(Rt+1)*We,mt+=(Rt+1)*$a}Pi=Fe/Oe*1e3,Jt=Ne(Me,{...Ze,segmentNumber:rs.toString(10),segmentTime:Fe.toString(10)})}else if(Yc(g)){let Fe=parseInt(me.getAttribute("duration")??"",10)/Oe*1e3,Zt=Math.ceil(g/Fe),We=0;for(let Rt=1;Rt<Zt;Rt++){let ss=Ne(Me,{...Ze,segmentNumber:Rt.toString(10),segmentTime:We.toString(10)});Qe.push({time:{from:We,to:We+Fe},url:ss}),We+=Fe}Pi=We,Jt=Ne(Me,{...Ze,segmentNumber:Zt.toString(10),segmentTime:We.toString(10)})}let rd={time:{from:Pi,to:1/0},url:Jt};Kt={type:"template",baseUrl:se,segmentTemplateUrl:Me,initUrl:Lt,totalSegmentsDurationMs:mt,segments:Qe,nextSegmentBeyondManifest:rd,timescale:Oe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Re)continue;let $i={video:"video",audio:"audio",text:"text"}[ke];if(!$i)continue;oe||=$i,He={id:ts,kind:$i,segmentReference:Kt,profiles:is,duration:g,bitrate:Jr,mime:Re,codecs:ct,width:je,height:ki,fps:Aa,quality:Gt}}ue.language||=_,ue.label||=le,ue.mime||=Re,ue.codecs||=ct,ue.hdr||=oe==="video"&&en(ct),ue.representations.push(He)}if(oe){let U=r[oe].find(_=>_.id===ue.id);if(U&&ue.representations.every(_=>_.segmentReference.type==="template"))for(let _ of U.representations){let le=ue.representations.find(Re=>Re.id===_.id);if(!le)continue;let pe=le.segmentReference,se=_.segmentReference;se.segments.push(...pe.segments),se.nextSegmentBeyondManifest=pe.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?gt(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}},xu=({id:o,bitrate:e})=>({id:o,bitrate:e}),wu=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),ku=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),tn=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),rn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),sn=o=>"url"in o,$e=o=>o.type==="template";import{isNonNullable as Au}from"@vkontakte/videoplayer-shared/evergreen";var B=(o,e)=>Au(o)&&Au(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:l}){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=yt(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 hu(this.sourceBuffer),this.subscription.add(an(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(an(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,ui(this.sourceBuffer.buffered)*.8);this.bufferLimit=n;let l=this.getForwardBufferDuration(u),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,l<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);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=yt(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(te(s)||te(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();Tt(a)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=yt(this.destroyAbortController.signal,async function*(e,t=!1){if(!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(te(s)||te(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();Tt(a)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=yt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(n=>n.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let n of this.representations.keys()){let l=t.find(c=>c.id===n);l&&this.representations.set(n,l);let h=this.representations.get(n);if(!h||!$e(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);Se(r,`Representation not found by id ${i}`);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)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,yt(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(te(u)||te(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();Tt(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(){!te(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(te(e)||te(this.downloadingRepresentationId)||te(this.playingRepresentationId)||te(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||Tt(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}`),te(r)||te(s))return;let a=r.find(c=>e>=c.time.from&&e<c.time.to);Tt(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let u=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=br(i),m=br(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Tt(p)&&Tt(m)&&Jc(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+n&&(u=a?a.time.to+n:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let w=v.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:y,status:w?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ui(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=[];if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,u),h.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))c="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(h,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Tt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations);for(let i of t){if(!i||!$e(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,n=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(n===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(n+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;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),l=Ne(r.segmentTemplateUrl,{segmentTime:n});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.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:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(c==="none"||c==="partially_ejected"&&g&&y&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(he(this.sourceBuffer.buffered,p)&&he(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,n=0,l=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<a.length&&(u<=h||n<=d);c++){let p=a[c];if(u+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){$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:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await yt(u,async function*(){let h=nn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:n,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=_s(),!h)return;let d=new DataView(h),c=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(d,f)}n&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Xe(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())$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 yt(a,async function*(){let n=nn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,n),an(window,"online").pipe(Zc()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=_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(l){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}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?(l,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=_s();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:st.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:n,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let u of this.activeSegments){let{segment:n}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=Ke(a.mime).parseFeedableSegmentChunk(l,this.isLive);h?.byteLength&&(n.status="partially_fed",u.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),u.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let n of this.activeSegments){let{segment:l}=n;if(n.representationId!==t)continue;if(s.aborted){await a();continue}let h=l.byte.from-i,d=l.byte.to-i,c=d-h+1,p=h<r,m=d<=r;if(!p)continue;let f=Ke(u.mime);if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+h,c);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(n,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(n.loadedBytes=Math.min(c,r-h),n.loadedBytes>n.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+h+n.feedingBytes,n.loadedBytes-n.feedingBytes),g=n.loadedBytes===c?b:f.parseFeedableSegmentChunk(b);g?.byteLength&&(l.status="partially_fed",n.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(n.fedBytes+=g.byteLength,n.fedBytes===c&&this.onSegmentFullyAppended(n,t)):await a())}}}onSegmentFullyAppended(e,t){if(!(te(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&M.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(he(this.sourceBuffer.buffered,e.segment.time.from,100)&&he(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",sn(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",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,u=(!i&&this.failedDownloads>0?yt(this.destroyAbortController.signal,async function*(){let n=nn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,n))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async n=>{if(!n)return;let{init:l,dataView:h,segments:d}=n,c=h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&$e(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,n=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:st.WTF,message:"loadInit threw",thrown:n})});return this.initData.set(e.id,u),u}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||te(e))return!1;let r=[],s=0,a=n=>{n.sort((h,d)=>h.from-d.from);let l=[n[0]];for(let h=1;h<n.length;h++){let{from:d,to:c}=n[h],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,c):l.push(n[h])}return l},u=n=>{if(s>=t)return r;r.push({...n.time}),r=a(r);let l=sn(n)?n.size??0:n.byte.to-n.byte.from;s+=l};for(let n of this.segments.values())for(let l of n){let h=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(h||d)&&l.status==="fed"&&u(l)}for(let n=0;n<this.sourceBuffer.buffered.length;n++){let l=this.sourceBuffer.buffered.start(n)*1e3,h=this.sourceBuffer.buffered.end(n)*1e3,d=0;for(let c of this.segments.values())for(let p of c)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(h)&&d++;if(d===this.segments.size){let c={time:{from:l,to:h},url:"",status:"none"};u(c)}}if(r.length&&i){let n=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let h of l)h.time.from>=e+n&&h.status==="fed"&&u(h)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,h)=>l||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||te(e)?0:ce(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(te(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||te(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),l=e.filter(h=>a>=h.from&&a<h.to-t||u>h.from+t&&u<=h.to);n||(l.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 It=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 $u,fromEvent as Pu,merge as ih,now as vr,Subject as _t,ValueSubject as on,flattenObject as hi,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 _t;this.firstBytesManifest$=new _t;this.manifestReceived$=new _t;this.firstBytesRequested$=new _t;this.firstBytesReceived$=new _t;this.lastConnectionType$=new on(void 0);this.lastConnectionReused$=new on(void 0);this.lastRequestFirstBytes$=new on(void 0);this.recoverableError$=new _t;this.error$=new _t;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=It(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Us(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},{type:"manifest"}).catch(Hs);return r?(t.log("success",hi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",hi({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:l=!1,ignoreNetworkErrors:h=!1}={}){let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(d,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),d=T.toString();break}default:$u(t)}this.requestQuic&&(d=It(d));let m=this.abortAllController.signal,f;if(a){let T=new AbortController;if(f=ih(Pu(this.abortAllController.signal,"abort"),Pu(a,"abort")).subscribe(()=>{try{T.abort()}catch(F){Hs(F)}}),this.subscription.add(f),this.abortAllController.signal.aborted||a.aborted)try{T.abort()}catch(F){Hs(F)}m=T.signal}let b=0,g=vr();p.log("startRequest",hi({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:n,requestStartedAt:g})),this.firstBytesRequested$.next();let S=yield this.doFetch(d,{priority:s,headers:c,signal:m},{ignoreNetworkErrors:h}),y=vr();if(!S)return p.error("error",{message:"No response in request"}),p.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(y-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let T=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:T}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!u){this.unsubscribeAbortSubscription(f);let T=vr(),F={requestStartedAt:g,requestEndedAt:T,duration:T-g};return p.log("endRequest",hi(F)),p.end(),S.arrayBuffer()}let v=S.body;if(u){let T;[v,T]=S.body.tee(),this.throughputEstimator?.trackStream(T,n)}let w=v.getReader(),A,L=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(L)&&(A=L),!A&&i&&(A=i.to-i.from+1);let x=A?new Uint8Array(A):new Uint8Array(0),R=!1,E=T=>{this.unsubscribeAbortSubscription(f),R=!0,Hs(T)},O=Sr(m,async function*({done:T,value:F}){if(b===0&&(this.lastRequestFirstBytes$.next(vr()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!T&&F){if(l&&A)x.set(F,b),b+=F.byteLength;else{let P=new Uint8Array(x.length+F.length);P.set(x),P.set(F,x.length),x=P,b+=F.byteLength}r?.(new DataView(x.buffer),b),yield w?.read().then(O,E)}}.bind(this));yield w?.read().then(O,E),this.unsubscribeAbortSubscription(f);let D=vr(),I={failed:R,requestStartedAt:g,requestEndedAt:D,duration:D-g};return R?(p.error("endRequest",hi(I)),p.end(),null):(p.log("endRequest",hi(I)),p.end(),x.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,l,h;e.indexRange&&(l=e.indexRange.from,h=e.indexRange.to,n=s+1===l,n&&(a=Math.min(l,r),u=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:u},measureThroughput:!1,...i});if(!d)return null;let c=new DataView(d,r-a,s-a+1);if(!t.validateData(c))throw new Error("Invalid media file");let p=t.parseInit(c),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(n)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=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,{measureThroughput:!1,...t});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){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:$u(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await fetch(e,t);if(r.ok)return i?.type==="manifest"&&this.firstBytesManifest$.next(),r;if(i?.ignoreNetworkErrors)return;let s=await r.text(),a=parseInt(s);if(!isNaN(a))switch(a){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 (${a})`,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,un=(o,e)=>o.reduce((t,i)=>t+i,0)/e,Lu=(o,e,t,i)=>{let r=0,s=t,a=un(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 Ru}from"@vkontakte/videoplayer-shared/evergreen";var Et=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 Ru(e.initial),this.debounced$=new Ru(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 Et{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 Ws=class extends Et{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=un(this.pastMeasures,this.takenMeasures);this.emaSmoothed=at(this.emaSmoothed,e,this.params.emaAlpha);let i=Lu(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var qs=class extends Et{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 Ws({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 qs({initial:e,label:"liveEdgeDelay",...t})}};var pi=(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(l=>l.time.from<=e&&l.time.to>=e);!n||this.currentSegment?.time.from===n.time.from&&this.currentSegment.time.to===n.time.to||(this.currentSegment=n,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(n.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=o.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&$e(t.segmentReference))}};import{assertNever as Gs}from"@vkontakte/videoplayer-shared/evergreen";var zs=o=>{let{webmDecodingInfo:e}=M.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)}},Mu=({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(M.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(M.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"]},Du=({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=M.device.isMac&&M.browser.isSafari;if(M.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 M.video.nativeHlsSupported&&!n&&!M.browser.isChromiumBased?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=>mi(i)),{codecs:t}=M.video;return dh().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=>mi(i)),{codecs:t}=M.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})},mi=o=>o.split(".")[0].replace("0",""),dh=()=>["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 Vu;this.subscriptionRemovable=new mh;this.representationSubscription=new Vu;this.state$=new C("none");this.currentVideoRepresentation$=new Y(void 0);this.currentVideoRepresentationInit$=new Y(void 0);this.currentAudioRepresentation$=new Y(void 0);this.currentVideoSegmentLength$=new Y(0);this.currentAudioSegmentLength$=new Y(0);this.error$=new ut;this.manifestRequested$=new ut;this.firstBytesManifest$=new ut;this.manifestReceived$=new ut;this.firstBytesRequested$=new ut;this.firstBytesReceived$=new ut;this.lastConnectionType$=new Y(void 0);this.lastConnectionReused$=new Y(void 0);this.lastRequestFirstBytes$=new Y(void 0);this.currentLiveTextRepresentation$=new Y(null);this.isLive$=new Y(!1);this.isActiveLive$=new Y(!1);this.isLowLatency$=new Y(!1);this.liveDuration$=new Y(0);this.liveSeekableDuration$=new Y(0);this.liveAvailabilityStartTime$=new Y(0);this.liveStreamStatus$=new Y(void 0);this.bufferLength$=new Y(0);this.liveLatency$=new Y(void 0);this.liveLoadBufferLength$=new Y(0);this.livePositionFromPlayer$=new Y(0);this.currentStallDuration$=new Y(0);this.videoLastDataObtainedTimestamp$=new Y(0);this.fetcherRecoverableError$=new ut;this.fetcherError$=new ut;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new ut;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new AbortController;this.initManifest=dn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Z(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:Ce.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=dn(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:Ce.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Fs(e??"",this.manifestUrlString)}catch(n){let l=Cs(e)??{id:"ManifestParsing",category:Ce.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(l)}if(!t)return null;let i=(n,l,h)=>!!(this.element?.canPlayType?.(l)&&Ae()?.isTypeSupported?.(`${l}; codecs="${h}"`)||n==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:n,latestSegmentPublishTime:l,streamIsUnpublished:h,streamIsAlive:d}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";if(d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p),d&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let m=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(m).catch(f=>{this.error$.next({id:"updateManifest",category:Ce.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:f})})}}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let n of["video","audio"]){let h=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p));r[n]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=h.map(({codecs:p})=>p);n==="audio"&&(a=Xs(c),d=a[0]),n==="video"&&(s=Ks(c),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[n]=h.filter(({codecs:p})=>mi(p)===d))}else{let c=new Set(h.map(({codecs:p})=>p));d=Ys(c),d&&(r[n]=h.filter(({codecs:p})=>p.startsWith(d)))}if(n==="video"){let c=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);M.display.isHDR&&c&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Er(u)),u}.bind(this));this.initRepresentations=dn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Er({initialVideo:e,initialAudio:t,sourceHls:i})),fi(this.manifest),fi(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(ot(d,"error").pipe(Js(c=>!!this.element?.played.length)).subscribe(c=>{this.error$.next({id:"VideoSource",category:Ce.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:c})}))};this.source=ms();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ei())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,c)=>[...d,...c.representations],[]);if(this.videoBufferManager=new gr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],xr(t)){let d=this.manifest.streams.audio.reduce((c,p)=>[...c,...p.representations],[]);this.audioBufferManager=new gr("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}if(Tr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Tr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Nt(...Sh.map(d=>ot(this.element,d))).pipe(gi(d=>this.element?ce(this.element.buffered,this.element.currentTime*1e3):0),Ir(),fh(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Nt(ot(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ir()).subscribe(c=>this.liveStreamEndTimestamp=hn())),this.subscription.add(ot(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:c}=this.tuning.dash;this.livePauseWatchdogSubscription=cn(c).subscribe(p=>{let m=ft(this.manifestUrlString,2);this.manifestUrlString=Z(this.manifestUrlString,m+c,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ot(this.element,"play").subscribe(c=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(bi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(gi(({isActiveLive:c,isLowLatency:p})=>c&&p),Ir()).subscribe(c=>{this.isManualDecreasePlaybackInLive()||pi(this.element,1)})),this.representationSubscription.add(bi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Js(({bufferLength:c,isActiveLive:p,isLowLatency:m})=>p&&m&&!!c)).subscribe(({bufferLength:c})=>this.liveBuffer.next(c))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(c=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!c)return;let p=this.liveSeekableDuration$.getValue()-c/1e3;this.liveSeekableDuration$.next(Math.max(p,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+c/1e3)})),this.representationSubscription.add(bi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Js(({isLive:c})=>c),Ir((c,p)=>p.bufferLength<c.bufferLength),gi(({rtt:c,bufferLength:p,segmentServerLatency:m})=>{let f=ft(this.manifestUrlString,2);return(c/2+p+m+f)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(bi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:c,isActiveLive:p,isLowLatency:m})=>{if(!m||!p)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=c-f;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(S)>b&&(y=1+Math.sign(S)*g),pi(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(c=>{let p=0;if(c){let m=(this.element?.currentTime??0)*1e3;p=Math.min(...this.bufferManagers.map(b=>b.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==p&&this.liveLoadBufferLength$.next(p)}));let d=0;this.representationSubscription.add(bi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(bh(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:c,bufferLength:p})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,f=ft(this.manifestUrlString,2),b=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(b,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,v=isFinite(c)?c:p,w=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=b<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let L="none";if(w?L="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(x=>x.proceedLowLatencyLive()),L="active_low_latency"):f!==0&&v<g?L="live_forward_buffering":v<g+y&&(L="live_with_target_offset"),isFinite(c)&&(d=c>d?c:d),L==="live_forward_buffering"||L==="live_with_target_offset"){let x=d-(g+S),R=this.normalizeLiveOffset(Math.trunc(f+x/m)),E=Math.abs(R-f),O=0;!c||E<=this.tuning.dashCmafLive.offsetCalculationError?O=f:R>0&&E>this.tuning.dashCmafLive.offsetCalculationError&&(O=R),this.manifestUrlString=Z(this.manifestUrlString,O,2)}(L==="live_with_target_offset"||L==="live_forward_buffering")&&(d=0,await this.updateLive())},c=>{this.error$.next({id:"updateLive",category:Ce.VIDEO_PIPELINE,thrown:c,message:"Failed to update live with subscription"})}))}let n=Nt(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(gi(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),l=Nt(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(gi(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),h=bi({allBuffersFull:n,someBufferEnded:l}).pipe(Ir(),gi(({allBuffersFull:d,someBufferEnded:c})=>d&&c),Js(d=>d));if(this.representationSubscription.add(Nt(this.forceEnded$,h).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Ce.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(Nt(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(c=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){c();return}this.error$.next({id:"OpenOfStream",category:Ce.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),c()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(c=>c.representations).flatMap(c=>{let p=[];return c.duration&&p.push(c.duration),$e(c.segmentReference)&&c.segmentReference.totalSegmentsDurationMs&&p.push(c.segmentReference.totalSegmentsDurationMs),p})];this.source.duration=Math.max(...d)/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=cn(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ce.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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),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){fi(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?hn()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Z(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){fi(this.element),this.state$.setState("running"),this.subscription.add(Nt(...gh.map(e=>ot(this.element,e)),ot(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ce.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&&he(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:a}=this.tuning.dash,u=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let h=this.currentStallDuration$.getValue();h+=a,this.currentStallDuration$.next(h);let d={timeInWaiting:h},c=hn(),p=100,m=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(m);let f=this.audioBufferManager?.lastDataObtainedTimestamp??0,b=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,S=b<p&&c-m>r,y=this.audioBufferManager&&g<p&&c-f>r;if((!t||l)&&((S||y)&&h>r||h>=i))throw new Error(`Stall timeout exceeded: ${h} ms`);if(u&&h%s===0){let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(v),this.updateManifest()):this.seekLive(v).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Ce.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),d.liveLastOffset=v}else{let v=this.element.currentTime*1e3;this.videoBufferManager?.maintain(v),this.audioBufferManager?.maintain(v),d.position=v}this.tracer.log("stallIntervalCallback",Er(d))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=cn(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ce.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){fi(this.element),fi(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),he(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Bu(this.element)||Bu(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.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=ph(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))}normalizeLiveOffset(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 l of n.gaps)(r&&l.persistent||n.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?a.push(1/0):a.push(l.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 Ou=`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 sc=`#ifdef GL_ES
134
+ `;var Fu=`#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 vi=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 da(this.params.fov,this.params.orientation),this.cameraRotationManager=new ha(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(rc,this.gl.VERTEX_SHADER),i=this.createShader(sc,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,c=e+i,h=t+r,l=e-i,d=t+r;return[s,a,u,n,c,h,l,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as ap,now as Rr,once as np,Subscription as op,ValueSubject as Pn,isNonNullable as up,safeStorage as Ln,filterChanged as cp}from"@vkontakte/videoplayer-shared/evergreen";var pa="stalls_manager_metrics",Mn="stalls_manager_abr_params",ac="stalls_manager_default_tuning_abr_params",Rn=class{constructor(){this.isSeeked$=new Pn(!1);this.isBuffering$=new Pn(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new op;this.severeStallOccurred$=new Pn(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(Mn):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Rr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Rr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(ac)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(Mn),this.setStoredData(ac,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(pa,"[]");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(pa,[]),this.setStoredData(Mn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:u}=this.tuning,n=a*Math.min(t/u,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-n,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-n,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+n,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+n,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+n,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-n,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(Ln.get(e)??t)}setStoredData(e,t){Ln.set(e,JSON.stringify(t))}removeStoredData(e){Ln.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(pa,"[]"),r=t/e,s=i.length?nt(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(pa,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(np()).subscribe(t=>this.providerStartWatchingTimestamp=Rr())),this.subscription.add(this.currentStallDuration$.pipe(cp()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:a}=this.tuning;if(ap(this.lastUniqueVideoTrackSelected)||a&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),n=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),h=Rr(),l=r&&this.currentStallsCount>=r,d=i&&h-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&h-c>=i+u&&t>=i;(l||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,up(this.lastUniqueVideoTrackSelected.bitrate)&&n>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Rr()-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}))}},ma=Rn;import{combine as lp,map as dp,observeElementSize as hp,Subscription as pp,ValueSubject as Dn,noop as mp}from"@vkontakte/videoplayer-shared/evergreen";var fa=class{constructor(){this.subscription=new pp;this.pipSize$=new Dn(void 0);this.videoSize$=new Dn(void 0);this.elementSize$=new Dn(void 0);this.pictureInPictureWindowRemoveEventListener=mp}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(hp(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(lp({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()}};import{filter as nc,map as fp,once as oc}from"@vkontakte/videoplayer-shared/evergreen";var yi=({subscription:o,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!R.browser.isSafari)return;let r=0,s=!1;o.add(e.volume.stateChangeStarted$.pipe(fp(()=>{let a=e.volume.getTransition(),u=t.getValue();return!u||!a?!1:!a.to.muted&&u.muted}),nc(a=>!!a),oc()).subscribe(()=>{r=performance.now(),s=!0})),o.add(i.playbackRateState$.pipe(nc(()=>s),oc()).subscribe(()=>{let a=t.getValue(),u=e.playbackRate.getState();a&&u!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=u)}))};var Ht=class{constructor(e){this.subscription=new Ep;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new ui;this.stallsManager=new ma;this.elementSizeManager=new fa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return gp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new vi(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 Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new la({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;Ip(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:uc.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(l=>!!l.length),lc()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Cr(l=>l.to.state!=="none"),Dr());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Cn(cc),lc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Cr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),yi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),p=this.player.getCodecs();if(Sp(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of d.audio){f.push(Sn(b));let g=[];for(let S of b.representations){let y=qu(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of d.video){m.push(vn(f));let b=[];for(let g of f.representations){let S=Er({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of d.text)for(let b of f.representations){let g=Qu(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let u=Br(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$,Tp(this.video,"progress")).pipe(Cn(()=>this.videoTracksMap.size>0)),{abrThrottle:n}=this.params.tuning.dash;n&&(u=u.pipe(xp(n))),this.subscription.add(u.subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||d)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(S=>this.videoTracksMap.get(S)?.representation.id===m.id);cc(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(vp({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Br(ba([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Cr(l=>l.to)))}).pipe(Cr(({videoState:l,autoVideoTrackState:d})=>l.to!=="stopped"&&d),Dr()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Dr()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(vn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Dr()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Sn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Cr(({to:l})=>l==="ready"),Dr());this.subscription.add(Br(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ba(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Br(c,this.player.state$.stateChangeEnded$,ba(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Br(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ba(["init"])).pipe(yp(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?qi:ji,t=this.params.tuning.useNewAutoSelectVideoTrack?Hs:Us,i=this.params.tuning.useNewAutoSelectVideoTrack?Ke:Ns,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:x})=>x===u),c=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 l=[...this.videoStreamsMap.keys()].find(({id:x})=>x===h.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let p=de(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=[...this.audioStreamsMap.keys()].find(({id:x})=>x===g?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(n&&!a){let x=e(n,d,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,x?.bitrate??-1/0)}if(c){let x=e(c,d,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,x?.bitrate??-1/0)}}let v=n;(a||!v)&&(v=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,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 w=S&&t(v,d,this.audioStreamsMap.get(S)??[],{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}),A=this.videoTracksMap.get(v)?.representation,L=w&&this.audioTracksMap.get(w)?.representation;if(A&&L)return[A,L];if(A&&!L&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:uc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var Vr=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 Bn,merge as dc,filter as hc,filterChanged as pc,isNullable as Vn,map as mc,ValueSubject as On,isNonNullable as wp}from"@vkontakte/videoplayer-shared/evergreen";var Or=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 On(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(pc()).subscribe(n=>{let c=i.position$.getValue(),h=i.volume$.getValue(),l=!h.volume||h.muted;!n&&!c&&l?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(mc(n=>n.to)).subscribe(this.player.isLowLatency$)).add(Bn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(mc(({liveBufferTime:n,liveAvailabilityStartTime:c})=>n&&c?n+c:void 0)).subscribe(i.liveTime$)).add(Bn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:dc(r.playbackRateState$,new On(1))}).pipe(hc(({liveStreamStatus:n,liveDuration:c})=>n==="active"&&!!c)).subscribe(({liveDuration:n,playbackRate:c})=>{let h=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-d||this.video.paused||Vn(h)||(t=n-h)})).add(Bn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:dc(r.playbackRateState$,new On(1))}).pipe(pc((n,c)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===c.liveDuration:n.time===c.time)).subscribe(({time:n,liveDuration:c,playbackRate:h})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&h>=1-d||Vn(n)||Vn(c))return;let p=-1*(c-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let c=Wu(n);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(hc(n=>wp(n))).subscribe(n=>i.isLiveEnded$.next(n==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as Zp,assertNonNullable as em,combine as tm,debounce as im,ErrorCategory as Pc,filter as Xn,filterChanged as zr,fromEvent as rm,isNonNullable as Lc,isNullable as sm,map as Gr,merge as Yr,observableFrom as wa,once as Mc,Subscription as am}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as Wn,assertNonNullable as Ii,combine as Ei,ErrorCategory as Ue,filter as Ia,filterChanged as qr,flattenObject as Qr,fromEvent as Ze,getTraceSubscriptionMethod as Hp,interval as zn,isNonNullable as Wr,isNullable as Ac,map as xi,merge as zt,now as Gn,Subject as lt,Subscription as Yn,SubscriptionRemovable as jp,tap as qp,throttle as $c,ValueSubject as K}from"@vkontakte/videoplayer-shared/evergreen";import{assertNever as kp,ErrorCategory as fc,Subject as bc}from"@vkontakte/videoplayer-shared/evergreen";var Ap=18,gc=!1;try{gc=R.browser.isSafari&&!!R.browser.safariVersion&&R.browser.safariVersion<=Ap}catch(o){console.error(o)}var Fn=class{constructor(e){this.bufferFull$=new bc;this.error$=new bc;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:fc.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)};gc&&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:fc.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:kp(t)}}},Sc=Fn;import{abortable as kt,assertNonNullable as ye,ErrorCategory as qt,fromEvent as Hn,getExponentialDelay as jn,isHigher as Rp,isNonNullable as At,isNullable as ie,now as va,once as Dp,Subject as Cp,Subscription as Bp,ValueSubject as Qt}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as $p,throttleFn as Pp}from"@vkontakte/videoplayer-shared/evergreen";var Fr=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?vt(s):void 0)??$p({width:e,height:t});return u&&{id:o,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:a}},vc=({id:o,bitrate:e})=>({id:o,bitrate:e}),yc=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),Tc=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),_n=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),Nn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),Un=o=>"url"in o,Pe=o=>o.type==="template";var Ic=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},jt=(o,e)=>{for(let t of o)if(e(t))return t;return null},Ec=o=>{let e=!1,t=Pp(()=>{e=!0},o);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as Lp,Subscription as Mp}from"@vkontakte/videoplayer-shared/evergreen";var ga=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 Sa=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Mp;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Lp(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!C(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=ga(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 _r=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:n=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new Qt(0);this.currentLowLatencySegmentLength$=new Qt(0);this.currentSegmentLength$=new Qt(0);this.onLastSegment$=new Qt(!1);this.fullyBuffered$=new Qt(!1);this.playingRepresentation$=new Qt(void 0);this.playingRepresentationInit$=new Qt(void 0);this.error$=new Cp;this.gaps=[];this.subscription=new Bp;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=kt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ye(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Sc(this.sourceBuffer),this.sourceBufferBufferedDiff=new Sa(this.mediaSource,this.sourceBuffer),this.subscription.add(Hn(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Hn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:qt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(a=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!C(this.mediaSource,this.sourceBuffer))return;let n=Math.min(this.bufferLimit,ci(this.sourceBuffer.buffered)*.8);this.bufferLimit=n;let c=de(this.sourceBuffer.buffered,u),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,c<h).catch(l=>{this.handleAsyncError(l,"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);ye(i,"No init buffer for starting representation"),ye(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=kt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ye(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ye(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();At(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=kt(this.destroyAbortController.signal,async function*(e,t=!1){if(!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ye(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ye(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();At(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=kt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(n=>n.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let n of this.representations.keys()){let c=t.find(d=>d.id===n);c&&this.representations.set(n,c);let h=this.representations.get(n);if(!h||!Pe(h.segmentReference)){this.isSeekingLive=!1;return}let l=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,l)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ye(r,`Representation not found by id ${i}`);let s=this.segments.get(i);ye(s,"No segments for starting representation");let a=this.initData.get(i);if(ye(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!c?.live,this.baseUrls=c?.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){!C(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,kt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ye(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(ie(u)||ie(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),ye(a,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!C(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();At(n)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(n,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ie(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ie(e)||ie(this.downloadingRepresentationId)||ie(this.playingRepresentationId)||ie(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||At(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(ye(t,`No such representation ${this.downloadingRepresentationId}`),ye(i,`No such representation ${this.playingRepresentationId}`),ie(r)||ie(s))return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);At(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 d=this.getForwardBufferDuration(e),p=Fr(i),m=Fr(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&At(p)&&At(m)&&Rp(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?u+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+n&&(u=a?a.time.to+n:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let w=v.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:y,status:w?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ci(this.sourceBuffer.buffered)>=this.bufferLimit){let d=de(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<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 d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))d="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(h,t,d).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h?.length&&de(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=r.at(-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-de(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;At(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Pe(i.segmentReference))return;let r=i.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,n=r?.findIndex(c=>u>=c.time.from+s&&u<=c.time.to+s);if(n===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,c)}else{let c=r.slice(n+1);this.segments.set(i.id,[...a,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ye(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),c=Ne(r.segmentTemplateUrl,{segmentTime:n});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:d,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&C(this.mediaSource,this.sourceBuffer)&&!(he(this.sourceBuffer.buffered,p)&&he(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,n=0,c=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<a.length&&(u<=h||n<=l);d++){let p=a[d];if(u+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")c.push(p);else break}return c}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:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await kt(u,async function*(){let h=jn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,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=va(),!h)return;let l=new DataView(h),d=Xe(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(l,f)}n&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(l);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Je(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 kt(a,async function*(){let n=jn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,n),Hn(window,"online").pipe(Dp()).subscribe(()=>{c(),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=va(),this.failedDownloads=0}catch(n){this.abortActiveSegments(e),Je(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=va(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:n,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}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?(c,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=va();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:qt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}: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||!C(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 c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=Xe(a.mime).parseFeedableSegmentChunk(c,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||!C(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:c}=n,h=c.byte.from-i,l=c.byte.to-i,d=l-h+1,p=h<r,m=l<=r;if(p){if(c.status==="downloading"&&m){c.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+h,d);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(n,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(n.loadedBytes=Math.min(d,r-h),n.loadedBytes>n.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+h+n.feedingBytes,n.loadedBytes-n.feedingBytes),b=n.loadedBytes===d?f:Xe(u.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(c.status="partially_fed",n.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(n.fedBytes+=b.byteLength,n.fedBytes===d&&this.onSegmentFullyAppended(n,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(ie(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer))){!this.isLive&&R.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(he(this.sourceBuffer.buffered,e.segment.time.from,100)&&he(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:qt.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",Un(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?kt(this.destroyAbortController.signal,async function*(){let u=jn(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(n=>setTimeout(n,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Xe(e.mime),r)).then(u=>{if(!u)return;let{init:n,dataView:c,segments:h}=u,l=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,l);let d=h;this.isLive&&Pe(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:qt.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||!C(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ie(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=u=>{if(s>=t)return;r.push({...u.time});let n=Un(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 c=n.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=n.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||h)&&n.status==="fed"&&a(n)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let n=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,h=0;for(let l of this.segments.values())for(let d of l)["none","partially_ejected"].includes(d.status)&&Math.round(d.time.from)<=Math.round(n)&&Math.round(d.time.to)>=Math.round(c)&&h++;if(h===this.segments.size){let l={time:{from:n,to:c},url:"",status:"none"};a(l)}}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 c of n)c.time.from>=e+u&&c.status==="fed"&&a(c)}return r.length?(r=Ic(r),(await Promise.all(r.map(n=>this.sourceBufferTaskQueue.remove(n.from,n.to)))).reduce((n,c)=>n||c,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!C(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ie(e)?0:de(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!C(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||!C(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:qt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ie(this.sourceBuffer)||!C(this.mediaSource,this.sourceBuffer)||ie(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=ga(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,c=0;for(let h=0;h<e.length;h+=2){let l=e[h],d=e[h+1];n||(n=l-t<=a&&d+t>=u),(a>=l&&a<d-t||u>l+t&&u<=d)&&(c+=1)}n||(c===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:qt.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 Nr,assertNever as xc,fromEvent as wc,merge as Vp,now as Ur,Subject as Wt,ValueSubject as qn,flattenObject as Ti,ErrorCategory as Hr,SubscriptionRemovable as Op}from"@vkontakte/videoplayer-shared/evergreen";var Ta=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new Wt;this.firstBytesManifest$=new Wt;this.manifestReceived$=new Wt;this.firstBytesRequested$=new Wt;this.firstBytesReceived$=new Wt;this.lastConnectionType$=new qn(void 0);this.lastConnectionReused$=new qn(void 0);this.lastRequestFirstBytes$=new qn(void 0);this.recoverableError$=new Wt;this.error$=new Wt;this.abortAllController=new AbortController;this.subscription=new Op;this.fetchManifest=Nr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=xt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Js(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},"manifest").catch(ya);return r?(t.log("success",Ti({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",Ti({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Nr(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:c=!1}={}){let h=e,l=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(h,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),h=I.toString();break}default:xc(t)}this.requestQuic&&(h=xt(h));let p=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=Vp(wc(this.abortAllController.signal,"abort"),wc(a,"abort")).subscribe(()=>{try{I.abort()}catch(T){ya(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(T){ya(T)}p=I.signal}let f=0,b=Ur();d.log("startRequest",Ti({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:n,requestStartedAt:b})),this.firstBytesRequested$.next();let g=yield this.doFetch(h,{priority:s,headers:l,signal:p}),S=Ur();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:I}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let I=Ur(),T={requestStartedAt:b,requestEndedAt:I,duration:I-b};return d.log("endRequest",Ti(T)),d.end(),g.arrayBuffer()}let y=g.body;if(u){let I;[y,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,n)}let v=y.getReader(),w,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(w=A),!w&&i&&(w=i.to-i.from+1);let L=w?new Uint8Array(w):new Uint8Array(0),x=!1,M=I=>{this.unsubscribeAbortSubscription(m),x=!0,ya(I)},E=Nr(p,async function*({done:I,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(Ur()-b),this.firstBytesReceived$.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&T){if(c&&w)L.set(T,f),f+=T.byteLength;else{let F=new Uint8Array(L.length+T.length);F.set(L),F.set(T,L.length),L=F,f+=T.byteLength}r?.(new DataView(L.buffer),f),yield v?.read().then(E,M)}}.bind(this));yield v?.read().then(E,M),this.unsubscribeAbortSubscription(m);let O=Ur(),D={failed:x,requestStartedAt:b,requestEndedAt:O,duration:O-b};return x?(d.error("endRequest",Ti(D)),d.end(),null):(d.log("endRequest",Ti(D)),d.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=Nr(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,c,h;e.indexRange&&(c=e.indexRange.from,h=e.indexRange.to,n=s+1===c,n&&(a=Math.min(c,r),u=Math.max(h,s))),a=Math.min(a,0);let l=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!l)return null;let d=new DataView(l,r-a,s-a+1);if(!t.validateData(d))throw new Error("Invalid media file");let p=t.parseInit(d),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(n)f=new DataView(l,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(l),segments:b}}.bind(this));this.fetchTemplateRepresentation=Nr(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}=Xs(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:xc(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t,i){let r=await fetch(e,t);if(r.ok)return i==="manifest"&&this.firstBytesManifest$.next(),r;let s=await r.text(),a=parseInt(s);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Hr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Hr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Hr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Hr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Hr.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ya=o=>{if(!Je(o))throw o};import{isNullable as Fp,ValueSubject as _p}from"@vkontakte/videoplayer-shared/evergreen";var jr=class o{constructor(e,t){this.currentRepresentation$=new _p(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(!Fp(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(c=>c.time.from<=e&&c.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 Qp=["progress","play","seeked","stalled","waiting"],Wp=["timeupdate","progress","loadeddata","playing","seeked"];var Ea=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Yn;this.subscriptionRemovable=new jp;this.representationSubscription=new Yn;this.state$=new V("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new lt;this.manifestRequested$=new lt;this.firstBytesManifest$=new lt;this.manifestReceived$=new lt;this.firstBytesRequested$=new lt;this.firstBytesReceived$=new lt;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new lt;this.fetcherError$=new lt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new lt;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Wn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Z(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=Wn(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=Ys(e??"",this.manifestUrlString)}catch(n){let c=zs(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(c)}if(!t)return null;let i=(n,c,h)=>!!(this.element?.canPlayType?.(c)&&Ae()?.isTypeSupported?.(`${c}; codecs="${h}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:c,streamIsUnpublished:h,streamIsAlive:l}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((c-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";l||(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:d,codecs:p})=>i(n,d,p));r[n]=h;let l;if(this.tuning.dash.codecsPrioritizeEnabled){let d=h.map(({codecs:p})=>p);n==="audio"&&(a=ua(d),l=a[0]),n==="video"&&(s=oa(d),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?l=this.forceVideoCodec:l=s[0]),l&&(r[n]=h.filter(({codecs:p})=>fi(p)===l))}else{let d=new Set(h.map(({codecs:p})=>p));l=na(d),l&&(r[n]=h.filter(({codecs:p})=>p.startsWith(l)))}if(n==="video"){let d=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);R.display.isHDR&&d&&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",Qr(u)),u}.bind(this));this.initRepresentations=Wn(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Qr({initialVideo:e,initialAudio:t,sourceHls:i})),Ii(this.manifest),Ii(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Yn,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Ze(d,"error").pipe(Ia(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=Is();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ti())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((d,p)=>[...d,...p.representations],[]);if(this.videoBufferManager=new _r("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],Wr(t)){let d=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new _r("audio",this.source,d,a),this.bufferManagers.push(this.audioBufferManager)}jr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new jr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let n=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(zt(...Wp.map(d=>Ze(this.element,d))).pipe(xi(d=>this.element?de(this.element.buffered,this.element.currentTime*1e3):0),qr(),qp(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&n()})).subscribe(this.bufferLength$)),this.representationSubscription.add(zt(Ze(this.element,"ended"),this.forceEnded$).subscribe(()=>{n()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(qr()).subscribe(p=>this.liveStreamEndTimestamp=Gn())),this.subscription.add(Ze(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=zn(1e3).subscribe(p=>{let m=gt(this.manifestUrlString,2);this.manifestUrlString=Z(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ze(this.element,"play").subscribe(p=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(Ei({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(xi(({isActiveLive:p,isLowLatency:m})=>p&&m),qr()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||mi(this.element,1)})),this.representationSubscription.add(Ei({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ia(({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(Ei({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ia(({isLive:p})=>p),qr((p,m)=>m.bufferLength<p.bufferLength),xi(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=gt(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ei({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,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=p-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(y)>g&&(v=1+Math.sign(y)*S),mi(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 d=0;this.representationSubscription.add(Ei({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe($c(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=gt(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,w=isFinite(p)?p:m,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let x="none";if(A?x="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(M=>M.proceedLowLatencyLive()),x="active_low_latency"):b!==0&&w<S?x="live_forward_buffering":w<S+v&&(x="live_with_target_offset"),isFinite(p)&&(d=p>d?p:d),x==="live_forward_buffering"||x==="live_with_target_offset"){let M=d-(S+y),E=this.normolizeLiveOffset(Math.trunc(b+M/f)),O=Math.abs(E-b),D=0;!p||O<=this.tuning.dashCmafLive.offsetCalculationError?D=b:E>0&&O>this.tuning.dashCmafLive.offsetCalculationError&&(D=E),this.manifestUrlString=Z(this.manifestUrlString,D,2)}(x==="live_with_target_offset"||x==="live_forward_buffering")&&(d=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ue.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let c=zt(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(xi(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),h=zt(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(xi(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),l=Ei({allBuffersFull:c,someBufferEnded:h}).pipe(qr(),xi(({allBuffersFull:d,someBufferEnded:p})=>d&&p),Ia(d=>d));if(this.representationSubscription.add(zt(this.forceEnded$,l).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(zt(...this.bufferManagers.map(d=>d.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{d&&(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 d=[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(...d)/1e3}this.audioBufferManager&&Wr(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=zn(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 Ta({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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=ot.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){Ii(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Gn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Z(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(){Ii(this.element),this.state$.setState("running");let e=Ze(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe($c(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(zt(...Qp.map(t=>Ze(this.element,t)),Ze(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Ue.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Ze(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(Ze(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&he(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=Gn(),a=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,c=this.videoBufferManager?.getForwardBufferDuration()??0,h=this.audioBufferManager?.getForwardBufferDuration()??0,l=c<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&h<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((l||d)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let 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",Qr(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=zn(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Ii(this.element),Ii(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),he(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(Ac(this.element)||Ac(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Qr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Wr(this.element)&&Wr(this.source)&&Wr(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=Hp(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 c of n.gaps)(c.persistent||n.playingRepresentation$.getValue()===c.representation)&&c.from-u<=s&&c.to+u>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?a=1/0:(a===null||c.to>a)&&(a=c.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",Qr({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 zp,map as Gp,observeElementSize as Yp,Subscription as Kp,ValueSubject as Kn,noop as Xp}from"@vkontakte/videoplayer-shared/evergreen";var xa=class{constructor(){this.subscription=new Kp;this.pipSize$=new Kn(void 0);this.videoSize$=new Kn(void 0);this.elementSize$=new Kn(void 0);this.pictureInPictureWindowRemoveEventListener=Xp}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(Yp(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(zp({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(Gp(({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 Gt=class{constructor(e){this.subscription=new am;this.videoState=new V("stopped");this.observableVideo=null;this.droppedFramesManager=new ui;this.stallsManager=new ma;this.elementSizeManager=new xa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new yt;this.audioTrackSwitchHistory=new yt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return Zp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new vi(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 Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ea({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;sm(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:Pc.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(Xn(l=>!!l.length),Mc()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Gr(l=>l.to.state!=="none"),zr());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Xn(Lc),Mc()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Gr(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ze(this.video,t.isLooped,r)),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),p=this.player.getCodecs();if(em(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of d.audio){f.push(_n(b));let g=[];for(let S of b.representations){let y=vc(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of d.video){m.push(Nn(f));let b=[];for(let g of f.representations){let S=Fr({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of d.text)for(let b of f.representations){let g=yc(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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,n=u&&Ec(u)||null;this.subscription.add(Yr(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$,rm(this.video,"progress")).pipe(Xn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||d||l==="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=jt(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);Lc(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="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(tm({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Yr(wa([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Gr(l=>l.to)))}).pipe(Gr(({videoState:l,autoVideoTrackState:d})=>l.to!=="stopped"&&d),zr()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(zr()).subscribe(l=>{let d=jt(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Nn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(zr()).subscribe(l=>{let d=jt(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(_n(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let c=t.playbackState.stateChangeStarted$.pipe(Gr(({to:l})=>l==="ready"),zr());this.subscription.add(Yr(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,wa(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Yr(c,this.player.state$.stateChangeEnded$,wa(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Yr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,wa(["init"])).pipe(im(0));this.subscription.add(h.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?qi:ji,t=this.params.tuning.useNewAutoSelectVideoTrack?Hs:Us,i=this.params.tuning.useNewAutoSelectVideoTrack?Ke:Ns,{desiredState:r,output:s}=this.params,a=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,n=jt(this.videoTracksMap.keys(),x=>x.id===u),c=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 l=jt(this.videoStreamsMap.keys(),x=>x.id===h.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let p=de(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=a?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(m,f||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),S=g?.id&&jt(this.audioStreamsMap.keys(),x=>x.id===g.id)||this.audioStreamsMap.keys().next().value,y=0;if(S){if(n&&!a){let x=e(n,d,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,x?.bitrate??-1/0)}if(c){let x=e(c,d,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,x?.bitrate??-1/0)}}let v=n;(a||!v)&&(v=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:b,current:c,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 w=S&&t(v,d,this.audioStreamsMap.get(S)??[],{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}),A=this.videoTracksMap.get(v)?.representation,L=w&&this.audioTracksMap.get(w)?.representation;A&&L?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=L):A&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var Kr=class extends Gt{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 Jn,merge as Rc,filter as Dc,filterChanged as Cc,isNullable as Zn,map as Bc,ValueSubject as eo,isNonNullable as nm}from"@vkontakte/videoplayer-shared/evergreen";var Xr=class extends Gt{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 eo(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(Cc()).subscribe(n=>{let c=i.position$.getValue(),h=i.volume$.getValue(),l=!h.volume||h.muted;!n&&!c&&l?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(Bc(n=>n.to)).subscribe(this.player.isLowLatency$)).add(Jn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Bc(({liveBufferTime:n,liveAvailabilityStartTime:c})=>n&&c?n+c:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(Dc(n=>nm(n))).subscribe(n=>i.isLiveEnded$.next(n!=="active"&&i.position$.getValue()===0))).add(Jn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Rc(r.playbackRateState$,new eo(1))}).pipe(Dc(({liveStreamStatus:n,liveDuration:c})=>n==="active"&&!!c)).subscribe(({liveDuration:n,playbackRate:c})=>{let h=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-d||this.video.paused||Zn(h)||(t=n-h)})).add(Jn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Rc(r.playbackRateState$,new eo(1))}).pipe(Cc((n,c)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===c.liveDuration:n.time===c.time)).subscribe(({time:n,liveDuration:c,playbackRate:h})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&h>=1-d||Zn(n)||Zn(c))return;let p=-1*(c-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let c=Tc(n);this.params.output.availableTextTracks$.next([c])}}))}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 Vc="X-Playback-Duration",to=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(Vc)?parseInt(e.headers.get(Vc),10):void 0};import{assertNever as gm,combine as Sm,debounce as vm,ErrorCategory as $a,filter as ym,filterChanged as Tm,isNonNullable as _c,isNullable as Pa,map as Nc,merge as Im,observableFrom as Em,Subscription as xm,ValueSubject as ro,VideoQuality as wm}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as om,getExponentialDelay as um}from"@vkontakte/videoplayer-shared/evergreen";var cm=o=>{let e=null;if(o.QUALITY&&(e=vt(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=om({width:t,height:i})}return e??null},lm=(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 c=Object.fromEntries(u[1].split(",").map(b=>b.split("="))),h=c.QUALITY??`stream-${c.BANDWIDTH}`,l=cm(c),d;c.BANDWIDTH&&(d=parseInt(c.BANDWIDTH,10)/1e3||void 0),!d&&c["AVERAGE-BANDWIDTH"]&&(d=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,m;if(c.RESOLUTION){let[b,g]=c.RESOLUTION.split("x").map(S=>parseInt(S,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();l&&i.push({id:h,quality:l,url:f,bandwidth:d,size:m,fps:p})}if(n){let c=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=c.URI?.replace(/playlist$/,"subtitles.vtt"),l=c.LANGUAGE,d=c.NAME;h&&l&&r.push({type:"internal",id:l,label:d,language:l,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},dm=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),io=0,Oc=async(o,e=o,t,i)=>{let s=await(await fetch(o,i)).text();io+=1;try{let{qualityManifests:a,textTracks:u}=lm(s,e);return{qualityManifests:a,textTracks:u}}catch{if(io<=t.manifestRetryMaxCount)return await dm(um(io-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Oc(o,e,t)}return{qualityManifests:[],textTracks:[]}},ka=Oc;import{isNonNullable as hm,Subscription as pm,throttle as mm,ValueSubject as Fc,Subject as fm,ErrorCategory as bm}from"@vkontakte/videoplayer-shared/evergreen";var Aa=class{constructor(e,t,i,r,s){this.subscription=new pm;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Fc(null);this.getCurrentTime$=new Fc(null);this.error$=new fm;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(mm(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],c=new URL(n,t).toString(),h=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+h},url:c}),s=s+h,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-l}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 c=new Date(n);c.setMilliseconds(0),s=c.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(hm(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:bm.WTF,thrown:t,message:e})}};var Jr=class{constructor(e){this.subscription=new xm;this.videoState=new V("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ro([]);this.liveOffset=new Bt;this.manifestStartTime$=new ro(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=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),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else r?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gm(t)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:wm.INVARIANT,url:this.params.source.url};let t=(i,r)=>ka(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 Aa(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ce(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:$a.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:$a.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ro(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:$a.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(Tm(),Nc(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(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&_c(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let d=this.manifests$.getValue().find(p=>p.id===l);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(le(d.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(Sm({startTime:this.manifestStartTime$.pipe(ym(_c)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:n})=>this.params.output.liveTime$.next(u+n*1e3),i)),this.subscription.add(this.manifests$.pipe(Nc(u=>u.map(({id:n,quality:c,size:h,bandwidth:l,fps:d})=>({id:n,quality:c,size:h,fps:d,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Im(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Em(["init"])).pipe(vm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Pa(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[c,h]of[[u,"mq"],[n,"lq"]]){let l=String(parseFloat(c||""));h&&c&&r.searchParams.set(h,l)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=Z(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),to(a).then(u=>{if(!Pa(u))this.maxSeekBackTime$.next(u);else{let n=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Pa(n)||!isFinite(n))&&fetch(a).then(c=>c.text()).then(c=>{let h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(c)?.[1];if(h){let l=new URL(h,a).toString();to(l).then(d=>{Pa(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$a.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=Z(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 km,debounce as Am,ErrorCategory as so,fromEvent as ao,isNonNullable as $m,isNullable as Pm,map as Uc,merge as Hc,observableFrom as jc,Subscription as Lm,ValueSubject as qc,VideoQuality as Mm}from"@vkontakte/videoplayer-shared/evergreen";var Zr=class{constructor(e){this.subscription=new Lm;this.videoState=new V("stopped");this.manifests$=new qc([]);this.unmuteAfterBrowserResetsHappened=new qc(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=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:l}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return km(t)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Mm.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),ka(Z(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.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:so.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:so.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(Uc(u=>u.to)),this.params.output.playbackState$),this.subscription.add(ze(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)),yi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),n=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&$m(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(le(m.url)))}let l=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(l!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),n&&n.from==="changing_manifest"&&this.videoState.setState(n.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(Uc(u=>u.map(({id:n,quality:c,size:h,bandwidth:l,fps:d})=>({id:n,quality:c,size:h,fps:d,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!R.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(Hc(ao(u,"addtrack"),ao(u,"removetrack"),ao(u,"change"),jc(["init"])).subscribe(()=>{for(let n=0;n<u.length;n++)u[n].mode="hidden"},i))}let a=Hc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,jc(["init"])).pipe(Am(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Pm(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 c=String(parseFloat(u||""));n&&u&&r.searchParams.set(n,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:so.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Rm,assertNonNullable as Qc,debounce as Dm,ErrorCategory as Wc,isHigherOrEqual as Cm,isLowerOrEqual as Bm,isNonNullable as Vm,merge as Om,observableFrom as Fm,Subscription as _m,map as Nm}from"@vkontakte/videoplayer-shared/evergreen";var es=class{constructor(e){this.subscription=new _m;this.videoState=new V("stopped");this.trackUrls={};this.textTracksManager=new Ce;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:n}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:n*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return Rm(e)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:Wc.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(Nm(u=>u.to)),this.params.output.playbackState$),this.subscription.add(ze(this.video,t.isLooped,i)),yi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&Vm(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(),c=this.params.output.element$.getValue()?.playbackRate;if(n!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(n),h.playbackRate=n)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=Om(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Fm(["init"])).pipe(Dm(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Qc(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Qc(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=xt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(le(t))}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wc.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=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Ke(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,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(c=>c.track);if(!r||!s||si(e,a[0].quality,a.at(-1)?.quality)){i();return}let u=e.max?Bm(r,e.max):!0,n=e.min?Cm(r,e.min):!0;u&&n||i(e)}};import{assertNever as Gc,debounce as qm,merge as Yc,observableFrom as Qm,Subscription as Wm,map as Kc,ValueSubject as zm,ErrorCategory as oo,VideoQuality as Gm}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as Um}from"@vkontakte/videoplayer-shared/evergreen";var zc=["stun:videostun.mycdn.me:80"],Hm=1e3,jm=3,no=()=>null,La=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=no;this.externalStopCallback=no;this.externalErrorCallback=no;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:zc}]};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:Um.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),Hm)}normalizeOptions(e={}){let t={stunServerList:zc,maxRetryNumber:jm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ts=class{constructor(e){this.videoState=new V("stopped");this.maxSeekBackTime$=new zm(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return Gc(e)}};this.subscription=new Wm,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Te(e.container,e.tuning),this.liveStreamClient=new La(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:oo.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(Yc(this.videoState.stateChangeStarted$.pipe(Kc(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Kc(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(Be(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ee(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Gc(a.to)}},i)).add(Yc(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Qm(["init"])).pipe(qm(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Gm.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:oo.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oo.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var wi=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 is,assertNonNullable as dt,ErrorCategory as Ma,filter as il,isNonNullable as rl,isNullable as tf,map as rf,merge as sf,once as af,Subject as X,Subscription as sl,ValueSubject as B,flattenObject as uo}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as Ym,map as Xc,Subscription as Km,Subject as Xm}from"@vkontakte/videoplayer-shared/evergreen";var Jc=o=>new Ym(e=>{let t=new Km,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Xc(({from:c,to:h})=>`${c}-${h}`)),r=o.desiredPlaybackState$.stateChangeEnded$,s=o.providerChanged$.pipe(Xc(({type:c})=>c!==void 0)),a=new Xm,u=0,n="unknown";return t.add(i.subscribe(c=>{u&&window.clearTimeout(u),n=c,u=window.setTimeout(()=>a.next(c),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),n="unknown",u=0})),t.add(s.subscribe(c=>{u&&(window.clearTimeout(u),u=0,c&&(u=window.setTimeout(()=>a.next(n),o.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as Jm,Subscription as Zm,combine as ef,filter as el,once as tl}from"@vkontakte/videoplayer-shared/evergreen";function Zc(){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 Zm;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(el(s=>!!s.type),tl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){R.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ef({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(el(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),tl()).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=Zc();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:Jm.VIDEO_PIPELINE,message:e?.message??`${o.errorId} exception`,thrown:e})}};var nf={chunkDuration:5e3,maxParallelRequests:5},rs=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new X;this.noAvailableProvidersError$=new X;this.volumeMultiplierError$=new X;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableVideoCodecs$:new B([]),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),availableAudioCodecs$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new X,fetcherError$:new X,fetcherRecoverableError$:new X,warning$:new X,willSeekEvent$:new X,soundProhibitedEvent$:new X,seekedEvent$:new X,loopedEvent$:new X,endedEvent$:new X,manifestRequested$:new X,firstBytesManifest$:new X,manifestReceived$:new X,firstBytesRequested$:new X,firstBytesReceived$:new X,firstBytesEvent$:new X,loadedMetadataEvent$:new X,firstFrameEvent$:new X,canplay$:new X,isLive$:new B(void 0),isLiveEnded$:new B(null),canPlayLiveTailBuffer$:new B(!1),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),severeStallOccurred$:new X,availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B(""),getCurrentTime$:new B(null)};this.subscription=new sl;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=Qa([...Zu(this.params.tuning),...Ju(this.params.tuning)]).filter(c=>rl(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!r.includes(c)),...t.filter(c=>r.includes(c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",uo(s)),this.screenFormatsIterator=new wi(s);let a=[...wn(!0),...wn(!1)];this.chromecastFormatsIterator=new wi(a.filter(c=>rl(e.sources[c]))),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 wi(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(tf(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 is(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]),c=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return dt(n),this.params.tuning.useNewDashProvider?new Kr({...u,source:n,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Vr({...u,source:n,sourceHls:c,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return dt(n),this.params.tuning.useNewDashProvider?new Xr({...u,source:n}):new Or({...u,source:n})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let n=this.applyFailoverHost(t[e]);return dt(n),new Zr({...u,source:n})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return dt(n),new Jr({...u,source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let n=this.applyFailoverHost(t[e]);return dt(n),new es({...u,source:n})}case"DASH_LIVE":{let n=this.applyFailoverHost(t[e]);return dt(n),new $u({...u,source:n,config:{...nf,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let n=this.applyFailoverHost(t[e]);return dt(n),new ts({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 is(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,u={meta:s,container:i,source:t,format:e,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastNewProvider&&this.params.dependencies.chromecastInitializer instanceof it){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return dt(c),new Ci({...u,chromecastConnector:c})}let n=this.params.dependencies.chromecastInitializer.connection$.getValue();return dt(n),new Fi({...u,connection:n})}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 is(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return is(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 is(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 sl,t=!1,i=0;return e.add(sf(this.providerOutput.error$.pipe(il(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Jc({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(rf(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(il(({to:s})=>s==="playing"),af()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{console.error(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("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===Ma.NETWORK,n=r.category===Ma.FATAL,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),h=i<this.params.tuning.providerErrorLimit&&!n,l=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,d=c&&!n&&(u&&t||!h);a={...a,isNetworkError:u,isFatalError:n,haveFailoverHost:c,tryFailover:d,canReinitProvider:h},h?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",uo(a)):this.tracer.error("providerError",uo(a))})),e}};import{fromEvent as Ra,once as of,combine as uf,Subscription as al,ValueSubject as co,map as nl,filter as cf,isNonNullable as Da,now as Le,safeStorage as lo}from"@vkontakte/videoplayer-shared/evergreen";var lf=5e3,ol="one_video_throughput",ul="one_video_rtt",ss=window.navigator.connection,cl=()=>{let o=ss?.downlink;if(Da(o)&&o!==10)return o*1e3},ll=()=>{let o=ss?.rtt;if(Da(o)&&o!==3e3)return o},dl=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},ho=class o{constructor(e){this.subscription=new al;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=o.load(ol)||(e.useBrowserEstimation?cl():void 0)||lf,i=o.load(ul)??(e.useBrowserEstimation?ll():void 0)??0;if(this.throughput$=new co(t),this.rtt$=new co(i),this.rttAdjustedThroughput$=new co(dl(t,i,e.rttPenaltyRequestSize)),this.throughput=ot.getSmoothedValue(t,-1,e),this.rtt=ot.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=cl();a&&this.throughput.next(a);let u=ll();Da(u)&&this.rtt.next(u)};ss&&"onchange"in ss&&this.subscription.add(Ra(ss,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{lo.set(ol,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{lo.set(ul,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(nl(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(uf({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(nl(({throughput:r,rtt:s})=>dl(r,s,e.rttPenaltyRequestSize)),cf(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 al;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Ra(e,"progress").pipe(of()).subscribe(s=>{t=s.loaded,i=Le()}));break;case 1:case 0:r.add(Ra(e,"loadstart").subscribe(()=>{t=0,i=Le()}));break}r.add(Ra(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,u=Le(),n=a-t,c=u-i;this.addRawSpeed(n,c,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(()=>{})},c=async({done:h,value:l})=>{if(h)!t&&this.addRawSpeed(r,Le()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let d=Le();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(a,m,1,t),a=l.byteLength,s=Le()}else a+=l.byteLength;u=Le()}else r+=l.byteLength,a+=l.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(c,n)}};this.concurrentDownloads.add(e),i?.read().then(c,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=lo.get(e);if(Da(t))return parseInt(t,10)??void 0}},hl=ho;import{fillWithDefault as df,VideoQuality as Ca}from"@vkontakte/videoplayer-shared/evergreen";var pl={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ca.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ca.Q_720P,trafficSavingLimit:Ca.Q_480P},stallsManager:{enabled:!0,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ca.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastNewProvider:!1,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},ml=o=>({...df(o,pl),configName:[...o.configName??[],...pl.configName]});import{assertNonNullable as mo,combine as ht,ErrorCategory as Ba,filter as re,filterChanged as Q,fromEvent as fo,isNonNullable as Sl,isNullable as Sf,Logger as vf,map as q,mapTo as vl,merge as $t,now as Va,once as ne,Subject as H,Subscription as yl,tap as bo,ValueSubject as $,isHigher as yf,isInvariantQuality as Tl,flattenObject as Pt,throttle as go,getTraceSubscriptionMethod as Il,TracerFactory as Tf,InternalsExposure as If,getPlayerId as Ef}from"@vkontakte/videoplayer-shared/evergreen";import{merge as hf,map as pf,filter as fl,isNonNullable as mf}from"@vkontakte/videoplayer-shared/evergreen";var po=({seekState:o,position$:e})=>hf(o.stateChangeEnded$.pipe(pf(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),fl(mf)),e.pipe(fl(()=>o.getState().state==="none")));import{assertNonNullable as ff}from"@vkontakte/videoplayer-shared/evergreen";var bl=o=>{let e=typeof o.container=="string"?document.getElementById(o.container):o.container;return ff(e,`Wrong container or containerId {${o.container}}`),e};import{filter as bf,once as gf}from"@vkontakte/videoplayer-shared/evergreen";var gl=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(bf(r=>r.length>0),gf()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t?.getValue().find(i))&&e.startTransitionTo(o)};var Oa=class{constructor(e={configName:[]},t=Tf.createRootTracer(!1),i){this.subscription=new yl;this.logger=new vf;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new $(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new $(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new V("stopped"),seekState:new V({state:"none"}),volume:new V({volume:1,muted:!1}),videoTrack:new V(void 0),videoStream:new V(void 0),audioStream:new V(void 0),autoVideoTrackSwitching:new V(!0),autoVideoTrackLimits:new V({}),isLooped:new V(!1),isLowLatency:new V(!1),playbackRate:new V(1),externalTextTracks:new V([]),internalTextTracks:new V([]),currentTextTrack:new V(void 0),textTrackCuesSettings:new V({}),cameraOrientation:new V({x:0,y:0})};this.info={playbackState$:new $(void 0),position$:new $(0),duration$:new $(1/0),muted$:new $(!1),volume$:new $(1),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableQualities$:new $([]),availableQualitiesFps$:new $({}),currentQuality$:new $(void 0),isAutoQualityEnabled$:new $(!0),autoQualityLimitingAvailable$:new $(!1),autoQualityLimits$:new $({}),predefinedQualityLimitType$:new $("unknown"),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),isAudioAvailable$:new $(!0),currentPlaybackRate$:new $(1),currentBuffer$:new $({start:0,end:0}),isBuffering$:new $(!0),isStalled$:new $(!1),isEnded$:new $(!1),isLooped$:new $(!1),isLive$:new $(void 0),isLiveEnded$:new $(null),canPlayLiveTailBuffer$:new $(!1),canChangePlaybackSpeed$:new $(void 0),atLiveEdge$:new $(void 0),atLiveDurationEdge$:new $(void 0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),liveLatency$:new $(void 0),currentFormat$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),throughputEstimation$:new $(void 0),rttEstimation$:new $(void 0),videoBitrate$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),surface$:new $("none"),chromecastState$:new $("NOT_AVAILABLE"),chromecastDeviceName$:new $(void 0),intrinsicVideoSize$:new $(void 0),availableSources$:new $(void 0),is3DVideo$:new $(!1),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willReady$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,fetcherRecoverableError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,manifestRequested$:new H,firstBytesManifest$:new H,manifestReceived$:new H,firstBytesRequested$:new H,firstBytesReceived$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H,fetcherError$:new H,severeStallOccured$:new H};this.experimental={element$:new $(void 0),tuningConfigName$:new $([]),enableDebugTelemetry$:new $(!1),dumpTelemetry:su,getCurrentTime$:new $(null)};this.initLogs(),this.tuning=ml(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(s=>s.setSuppressErrors(!0)),Object.values(this.events).forEach(s=>s.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastNewProvider?new it(r):new fs(r),this.throughputEstimator=new hl(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new If("core",Ef(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(s,a,u)=>{let n=Reflect.get(s,a,u);return typeof n!="function"?n:(...c)=>{try{return n.apply(s,c)}catch(h){let l=c.map(m=>JSON.stringify(m,(f,b)=>{let g=typeof b;return["number","string","boolean"].includes(g)?b:b===null?null:`<${g}>`})),d=`Player.${String(a)}`,p=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Ba.WTF,message:p,thrown:h}),h}}}})}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",Pt(a)),this.domContainer=bl(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new rs({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?R.isInited$.pipe(re(s=>!!s),ne()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),fo(document,"visibilitychange").pipe(ne()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(re(t=>!!t),ne()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof it)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof it)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{mo(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),ne()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",Pt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",Pt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{gl(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Sf(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Sl(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($t(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(nu(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),ne()).subscribe(()=>{this.initedAt=Va(),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",Pt(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:Ba.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ne()).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",Pt(a)),a.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(q(a=>a.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(q(a=>a.destination),Q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ht({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,c)=>Tl(n)?1:Tl(c)?-1:yf(c,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(Q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(re(a=>Sl(a))).subscribe(a=>{this.info.currentQuality$.next(a?.quality),this.info.videoBitrate$.next(a?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Q((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Q((a,u)=>Math.round(a)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(a=>{this.desiredState.autoVideoTrackLimits.setState(a??{})})).add(e.providerOutput.currentBuffer$.pipe(q(a=>a?{start:a.from,end:a.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(bo(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(ht({hasLiveOffsetByPaused:$t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(q(a=>a.to),Q(),q(a=>a==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:a,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),a){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add(ht({atLiveEdge:ht({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:po({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(q(({isLive:a,position:u,isLowLatency:n})=>{let c=this.getActiveLiveDelay(n);return a&&Math.abs(u)<c/1e3}),Q(),bo(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(q(({atLiveEdge:a,hasPausedTimeoutCase:u})=>a&&!u)).subscribe(this.info.atLiveEdge$)).add(ht({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),Q(),bo(a=>a&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(q(a=>a.muted),Q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(q(a=>a.volume),Q()).subscribe(this.info.volume$)).add(po({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add($t(e.providerOutput.endedEvent$.pipe(vl(!0)),e.providerOutput.seekedEvent$.pipe(vl(!1))).pipe(Q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(q(a=>({id:a?`No${a}`:"NoProviders",category:Ba.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(ne()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(ne()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(ne()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(ne()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(ne()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(ne(),q(a=>a??Va()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ne(),q(()=>Va()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ne(),q(()=>Va()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new $(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new $(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:a})=>a==="playing"),ne()).subscribe(()=>i.next(!1)));let r=0,s=$t(e.providerOutput.isBuffering$,t,i).pipe(q(()=>{let a=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return a&&!u}),Q());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add($t(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($t(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(),c=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue(),l;h==="CONNECTED"?l="second_screen":n?c?a?l="pip":u?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new yl;this.subscription.add(t),this.subscription.add(e.current$.pipe(Q((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),ne()).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=Ke(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($t(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;mo(this.providerContainer),mo(e),ru(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>iu(t)),this.providerContainer.current$.subscribe(({type:t})=>Hi("provider",t)),e.duration$.subscribe(t=>Hi("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),ne()).subscribe(t=>Hi("tracks",t)),this.events.fatalError$.subscribe(new Se("fatalError")),this.events.managedError$.subscribe(new Se("managedError")),e.position$.subscribe(new Se("position")),e.currentVideoTrack$.pipe(q(t=>t?.quality)).subscribe(new Se("quality")),this.info.currentBuffer$.subscribe(new Se("buffer")),e.isBuffering$.subscribe(new Se("isBuffering"))].forEach(t=>this.subscription.add(t)),Hi("codecs",R.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(Q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(ht({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Q((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(i=>i>0),Q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(i=>i>0),Q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(ht({currentBuffer:this.info.currentBuffer$.pipe(re(i=>i.end>0),Q((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Q())}).pipe(go(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Q()).subscribe(e("canChangePlaybackSpeed"))).add(ht({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),go(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Q(),re(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Q(),re(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Q()).subscribe(e("muted"))).add(this.info.volume$.pipe(Q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Q(),re(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ht({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:i,rtt:r})=>!!i&&!!r),go(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Q(),re(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ba.DOM,message:String(r)})})};this.subscription.add($t(fo(document,"visibilitychange"),fo(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",Pt({quality:t,availableTracks:Pt(e),track:Pt(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&&!Yi()}};import{Subscription as dB,Observable as hB,Subject as pB,ValueSubject as mB,VideoQuality as fB}from"@vkontakte/videoplayer-shared/evergreen";var bB=`@vkontakte/videoplayer-core@${vo}`;export{Mi as ChromecastState,Na as HttpConnectionType,hB as Observable,fe as PlaybackState,Oa as Player,ps as PredefinedQualityLimits,bB as SDK_VERSION,pB as Subject,dB as Subscription,Ua as Surface,vo as VERSION,mB as ValueSubject,tt as VideoFormat,fB as VideoQuality,Wl as areValidLiveRecordSources,R as clientChecker,Ri as isMobile};
177
+ `;var Si=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new ea(this.params.fov,this.params.orientation),this.cameraRotationManager=new ta(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Ou,this.gl.VERTEX_SHADER),i=this.createShader(Fu,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,a=t-r,u=e+i,n=t-r,l=e+i,h=t+r,d=e-i,c=t+r;return[s,a,u,n,l,h,d,c]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as Th,now as wr,once as Ih,Subscription as Eh,ValueSubject as pn,isNonNullable as xh,safeStorage as mn,filterChanged as wh}from"@vkontakte/videoplayer-shared/evergreen";var ia="stalls_manager_metrics",fn="stalls_manager_abr_params",_u="stalls_manager_default_tuning_abr_params",bn=class{constructor(){this.isSeeked$=new pn(!1);this.isBuffering$=new pn(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Eh;this.severeStallOccurred$=new pn(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(fn):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=wr(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(wr()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(_u)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===a||(this.removeStoredData(fn),this.setStoredData(_u,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(ia,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,a)=>s+a.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let a=t.reduce((u,n)=>u+n.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(a,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((a,u)=>a+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(ia,[]),this.setStoredData(fn,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:a,significantTvt:u}=this.tuning,n=a*Math.min(t/u,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-n,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-n,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+n,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+n,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+n,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-n,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(mn.get(e)??t)}setStoredData(e,t){mn.set(e,JSON.stringify(t))}removeStoredData(e){mn.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(ia,"[]"),r=t/e,s=i.length?at(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,a={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(a),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(ia,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(Ih()).subscribe(t=>this.providerStartWatchingTimestamp=wr())),this.subscription.add(this.currentStallDuration$.pipe(wh()).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(),l=this.videoLastDataObtainedTimestamp$.getValue(),h=wr(),d=r&&this.currentStallsCount>=r,c=i&&h-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&h-l>=i+u&&t>=i;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,xh(this.lastUniqueVideoTrackSelected.bitrate)&&n>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&wr()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},ra=bn;import{combine as kh,map as Ah,observeElementSize as $h,Subscription as Ph,ValueSubject as gn,noop as Lh}from"@vkontakte/videoplayer-shared/evergreen";var sa=class{constructor(){this.subscription=new Ph;this.pipSize$=new gn(void 0);this.videoSize$=new gn(void 0);this.elementSize$=new gn(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(kh({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()}};import{filter as Nu,map as Rh,once as Uu}from"@vkontakte/videoplayer-shared/evergreen";var vi=({subscription:o,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!M.browser.isSafari)return;let r=0,s=!1;o.add(e.volume.stateChangeStarted$.pipe(Rh(()=>{let a=e.volume.getTransition(),u=t.getValue();return!u||!a?!1:!a.to.muted&&u.muted}),Nu(a=>!!a),Uu()).subscribe(()=>{r=performance.now(),s=!0})),o.add(i.playbackRateState$.pipe(Nu(()=>s),Uu()).subscribe(()=>{let a=t.getValue(),u=e.playbackRate.getState();a&&u!==a.playbackRate&&performance.now()-r<1e3&&(a.playbackRate=u)}))};var Ut=class{constructor(e){this.subscription=new _h;this.videoState=new C("stopped");this.observableVideo=null;this.droppedFramesManager=new oi;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 St;this.audioTrackSwitchHistory=new St;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return Dh(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Si(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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;Fh(this.observableVideo)&&(this.observableVideo=xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:Hu.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,u)=>this.subscription.add(a.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Sn(d=>!!d.length),Qu()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ar(d=>d.to.state!=="none"),kr());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Sn(ju),Qu()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ar(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),vi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(Bh(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of c.audio){f.push(tn(b));let g=[];for(let S of b.representations){let y=xu(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of c.video){m.push(rn(f));let b=[];for(let g of f.representations){let S=br({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of c.text)for(let b of f.representations){let g=wu(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let u=$r(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Oh(this.video,"progress")).pipe(Sn(()=>this.videoTracksMap.size>0)),{abrThrottle:n}=this.params.tuning.dash;n&&(u=u.pipe(Nh(n))),this.subscription.add(u.subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===m.id);ju(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")await this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(Vh({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:$r(aa([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Ar(d=>d.to)))}).pipe(Ar(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),kr()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(kr()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(rn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(kr()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(tn(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Ar(({to:d})=>d==="ready"),kr());this.subscription.add($r(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,aa(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add($r(l,this.player.state$.stateChangeEnded$,aa(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=$r(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,aa(["init"])).pipe(Ch(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),l=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=[...this.videoStreamsMap.keys()].find(({id:x})=>x===h.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let p=ce(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),S=[...this.audioStreamsMap.keys()].find(({id:x})=>x===g?.id)??this.audioStreamsMap.keys().next().value,y=0;if(S){if(n&&!a){let x=e(n,c,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,x?.bitrate??-1/0)}if(l){let x=e(l,c,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,x?.bitrate??-1/0)}}let v=n;(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:y,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=S&&t(v,c,this.audioStreamsMap.get(S)??[],{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}),A=this.videoTracksMap.get(v)?.representation,L=w&&this.audioTracksMap.get(w)?.representation;if(A&&L)return[A,L];if(A&&!L&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var Pr=class extends Ut{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as vn,merge as Wu,filter as qu,filterChanged as zu,isNullable as yn,map as Gu,ValueSubject as Tn,isNonNullable as Uh}from"@vkontakte/videoplayer-shared/evergreen";var Lr=class extends Ut{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let u=new Tn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(zu()).subscribe(n=>{let l=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!n&&!l&&d?e=!0:n&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(Gu(n=>n.to)).subscribe(this.player.isLowLatency$)).add(vn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Gu(({liveBufferTime:n,liveAvailabilityStartTime:l})=>n&&l?n+l:void 0)).subscribe(i.liveTime$)).add(vn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Wu(r.playbackRateState$,new Tn(1))}).pipe(qu(({liveStreamStatus:n,liveDuration:l})=>n==="active"&&!!l)).subscribe(({liveDuration:n,playbackRate:l})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||yn(h)||(t=n-h)})).add(vn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Wu(r.playbackRateState$,new Tn(1))}).pipe(zu((n,l)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===l.liveDuration:n.time===l.time)).subscribe(({time:n,liveDuration:l,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-c||yn(n)||yn(l))return;let p=-1*(l-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let l=ku(n);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(qu(n=>Uh(n))).subscribe(n=>i.isLiveEnded$.next(n==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as fp,assertNonNullable as bp,combine as gp,debounce as Sp,ErrorCategory as ll,filter as Vn,filterChanged as Nr,fromEvent as vp,isNonNullable as dl,isNullable as yp,map as Ur,merge as Hr,observableFrom as ma,once as cl,Subscription as Tp}from"@vkontakte/videoplayer-shared/evergreen";import{abortable as Ln,assertNonNullable as Ti,combine as Ii,ErrorCategory as Ue,filter as ca,filterChanged as Or,flattenObject as Fr,fromEvent as Je,getTraceSubscriptionMethod as sp,interval as Rn,isNonNullable as _r,isNullable as ol,map as Ei,merge as qt,now as Mn,Subject as lt,Subscription as Dn,SubscriptionRemovable as ap,tap as np,throttle as ul,ValueSubject as K}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=M.browser.isSafari&&!!M.browser.safariVersion&&M.browser.safariVersion<=jh}catch(o){console.error(o)}var In=class{constructor(e){this.bufferFull$=new Ku;this.error$=new Ku;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Yu.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Xu&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Yu.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Hh(t)}}},Ju=In;import{abortable as xt,assertNonNullable as ve,ErrorCategory as jt,fromEvent as kn,getExponentialDelay as An,isHigher as Gh,isNonNullable as wt,isNullable as ie,now as ua,once as Yh,Subject as Kh,Subscription as Xh,ValueSubject as Qt}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Qh,throttleFn as Wh}from"@vkontakte/videoplayer-shared/evergreen";var Rr=({id:o,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:a})=>{let u=(s?gt(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}),el=({language:o,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),tl=({language:o,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:o,label:e}),En=({id:o,language:e,label:t,codecs:i,isDefault:r})=>({id:o,language:e,label:t,codec:i.split(".").at(0),isDefault:r}),xn=({id:o,language:e,label:t,hdr:i,codecs:r})=>({id:o,language:e,hdr:i,label:t,codec:r.split(".").at(0)}),wn=o=>"url"in o,Pe=o=>o.type==="template";var il=o=>{o.sort((t,i)=>t.from-i.from);let e=[o[0]];for(let t=1;t<o.length;t++){let{from:i,to:r}=o[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(o[t])}return e},Ht=(o,e)=>{for(let t of o)if(e(t))return t;return null},rl=o=>{let e=!1,t=Wh(()=>{e=!0},o);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as qh,Subscription as zh}from"@vkontakte/videoplayer-shared/evergreen";var na=o=>{let e=[];for(let t=0;t<o.length;t++){let i=Math.floor(o.start(t)*1e3),r=Math.ceil(o.end(t)*1e3);e.push(i,r)}return e};var oa=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new zh;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(qh(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!B(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=na(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],a=t[i],u=t[i+1];if(a>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Mr=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:a,isActiveLowLatency:u,compatibilityMode:n=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Qt(0);this.currentLowLatencySegmentLength$=new Qt(0);this.currentSegmentLength$=new Qt(0);this.onLastSegment$=new Qt(!1);this.fullyBuffered$=new Qt(!1);this.playingRepresentation$=new Qt(void 0);this.playingRepresentationInit$=new Qt(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=xt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ju(this.sourceBuffer),this.sourceBufferBufferedDiff=new oa(this.mediaSource,this.sourceBuffer),this.subscription.add(kn(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(kn(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:jt.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,ui(this.sourceBuffer.buffered)*.8);this.bufferLimit=n;let l=ce(this.sourceBuffer.buffered,u),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,a*2,l<h).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(a=>this.error$.next(a))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ve(i,"No init buffer for starting representation"),ve(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=xt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let a=this.getCurrentPosition();wt(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=xt(this.destroyAbortController.signal,async function*(e,t=!1){if(!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ve(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(ie(s)||ie(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),ve(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let a=this.getCurrentPosition();wt(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=xt(this.destroyAbortController.signal,async function*(e){let t=e.flatMap(n=>n.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let n of this.representations.keys()){let l=t.find(c=>c.id===n);l&&this.representations.set(n,l);let h=this.representations.get(n);if(!h||!Pe(h.segmentReference)){this.isSeekingLive=!1;return}let d=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);ve(r,`Representation not found by id ${i}`);let s=this.segments.get(i);ve(s,"No segments for starting representation");let a=this.initData.get(i);if(ve(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=a,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!B(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new AbortController,xt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);ve(s,`No such representation ${i}`);let a=this.segments.get(i),u=this.initData.get(i);if(ie(u)||ie(a)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),a=this.segments.get(i),ve(a,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let n=this.getCurrentPosition();wt(n)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(n,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ie(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ie(e)||ie(this.downloadingRepresentationId)||ie(this.playingRepresentationId)||ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||wt(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(ve(t,`No such representation ${this.downloadingRepresentationId}`),ve(i,`No such representation ${this.playingRepresentationId}`),ie(r)||ie(s))return;let a=r.find(c=>e>=c.time.from&&e<c.time.to);wt(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let u=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=Rr(i),m=Rr(t),f=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&wt(p)&&wt(m)&&Gh(p.quality,m.quality),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(f||b?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+n&&(u=a?a.time.to+n:-1/0),this.tuning.dash.useNewRepresentationSwitch){let S=[...this.segments.entries()].map(([y,v])=>{let w=v.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:y,status:w?.status}}).find(y=>y.status==="fed")?.representationId;S&&(this.playingRepresentationId=S,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&ui(this.sourceBuffer.buffered)>=this.bufferLimit){let c=ce(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let h=null;if(!this.activeSegments.size&&(h=this.selectForwardBufferSegments(r,t.segmentReference.type,u),h?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(h.includes(a))c="high";else{let p=h.at(0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(h,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!h?.length&&ce(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=r.at(-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-ce(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-d.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;wt(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,a=t.length-1;do r.unshift(t[a]),s+=t[a].time.to-t[a].time.from,a--;while(s<i&&a>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=t.flatMap(s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=e.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Pe(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,a=this.segments.get(i.id)??[],u=a.at(-1)?.time.to??0,n=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(n===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(n+1);this.segments.set(i.id,[...a,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ve(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Pe(r))return;let s=this.segments.get(i.id);if(!s)continue;let a=s.find(n=>Math.floor(n.time.from)===Math.floor(e.time.from));if(a&&!isFinite(a.time.to)&&(a.time.to=e.time.to,t=a.time.to-a.time.from),!!!s.find(n=>Math.floor(n.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let n=Math.round(e.time.to*r.timescale/1e3).toString(10),l=Ne(r.segmentTemplateUrl,{segmentTime:n});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:c,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+S||r<S&&m-p>=S||m<=i+S;return(c==="none"||c==="partially_ejected"&&g&&y&&this.sourceBuffer&&B(this.mediaSource,this.sourceBuffer)&&!(he(this.sourceBuffer.buffered,p)&&he(this.sourceBuffer.buffered,m)))&&g&&y});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let a=e,u=0,n=0,l=[],h=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<a.length&&(u<=h||n<=d);c++){let p=a[c];if(u+=p.byte.to+1-p.byte.from,n+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Pe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:a,signal:u,onProgress:n,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await xt(u,async function*(){let h=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,h))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let h=await this.fetcher.fetch(a,{range:s,signal:u,onProgress:n,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=ua(),!h)return;let d=new DataView(h),c=Ke(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(d,f)}n&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,u);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(h){this.abortActiveSegments([e]),Xe(h)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Pe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let n of e)n.status="downloading",this.activeSegments.add({segment:n,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:a,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&a&&(await xt(a,async function*(){let n=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,n),kn(window,"online").pipe(Yh()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),a.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:a,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=ua(),this.failedDownloads=0}catch(n){this.abortActiveSegments(e),Xe(n)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Pe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,n)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ua(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:n,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:jt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Pe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,a=[],n=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,h)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=ua();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:h,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});a.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:jt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:n,onProgressTasks:a}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let a=this.representations.get(t);if(a)for(let u of this.activeSegments){let{segment:n}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),h=Ke(a.mime).parseFeedableSegmentChunk(l,this.isLive);h?.byteLength&&(n.status="partially_fed",u.feedingBytes+=h.byteLength,await this.sourceBufferTaskQueue.append(h),u.fedBytes+=h.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:a}){if(!this.activeSegments.size||!B(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let n of this.activeSegments){if(n.representationId!==t)continue;if(s.aborted){await a();continue}let{segment:l}=n,h=l.byte.from-i,d=l.byte.to-i,c=d-h+1,p=h<r,m=d<=r;if(p){if(l.status==="downloading"&&m){l.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+h,c);await this.sourceBufferTaskQueue.append(f,s)&&!s.aborted?this.onSegmentFullyAppended(n,t):await a()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(n.loadedBytes=Math.min(c,r-h),n.loadedBytes>n.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+h+n.feedingBytes,n.loadedBytes-n.feedingBytes),b=n.loadedBytes===c?f:Ke(u.mime).parseFeedableSegmentChunk(f);b?.byteLength&&(l.status="partially_fed",n.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(n.fedBytes+=b.byteLength,n.fedBytes===c&&this.onSegmentFullyAppended(n,t)):await a())}}}}onSegmentFullyAppended(e,t){if(!(ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer))){!this.isLive&&M.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(he(this.sourceBuffer.buffered,e.segment.time.from,100)&&he(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:jt.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?xt(this.destroyAbortController.signal,async function*(){let u=An(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(n=>setTimeout(n,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ke(e.mime),r)).then(u=>{if(!u)return;let{init:n,dataView:l,segments:h}=u,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let c=h;this.isLive&&Pe(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),n&&this.parsedInitData.set(e.id,n)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:jt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,a),a}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ie(e))return!1;this.checkEjectedSegments();let r=[],s=0,a=u=>{if(s>=t)return;r.push({...u.time});let n=wn(u)?u.size??0:u.byte.to-u.byte.from;s+=n};for(let u of this.segments.values())for(let n of u){let l=n.time.to<=e-this.tuning.dash.bufferPruningSafeZone,h=n.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||h)&&n.status==="fed"&&a(n)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let n=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,h=0;for(let d of this.segments.values())for(let c of d)["none","partially_ejected"].includes(c.status)&&Math.round(c.time.from)<=Math.round(n)&&Math.round(c.time.to)>=Math.round(l)&&h++;if(h===this.segments.size){let d={time:{from:n,to:l},url:"",status:"none"};a(d)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let n of this.segments.values())for(let l of n)l.time.from>=e+u&&l.status==="fed"&&a(l)}return r.length?(r=il(r),(await Promise.all(r.map(n=>this.sourceBufferTaskQueue.remove(n.from,n.to)))).reduce((n,l)=>n||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!B(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ie(e)?0:ce(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:jt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(ie(this.sourceBuffer)||!B(this.mediaSource,this.sourceBuffer)||ie(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=na(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let a=Math.floor(r.time.from),u=Math.ceil(r.time.to),n=!1,l=0;for(let h=0;h<e.length;h+=2){let d=e[h],c=e[h+1];n||(n=d-t<=a&&c+t>=u),(a>=d&&a<c-t||u>d+t&&u<=c)&&(l+=1)}n||(l===1?r.status="partially_ejected":this.gaps.some(h=>h.from===r.time.from||h.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:jt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?e.at(-1)?.time.to:0)||0}};import{abortable as Dr,assertNever as sl,fromEvent as al,merge as Jh,now as Br,Subject as Wt,ValueSubject as $n,flattenObject as yi,ErrorCategory as Vr,SubscriptionRemovable as Zh}from"@vkontakte/videoplayer-shared/evergreen";var da=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new Wt;this.firstBytesManifest$=new Wt;this.manifestReceived$=new Wt;this.firstBytesRequested$=new Wt;this.firstBytesReceived$=new Wt;this.lastConnectionType$=new $n(void 0);this.lastConnectionReused$=new $n(void 0);this.lastRequestFirstBytes$=new $n(void 0);this.recoverableError$=new Wt;this.error$=new Wt;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=It(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Us(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal},"manifest").catch(la);return r?(t.log("success",yi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.manifestReceived$.next(),r.text()):(t.error("error",yi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Dr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:a,measureThroughput:u=!0,isLowLatency:n=!1,bufferOptimisation:l=!1}={}){let h=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(h,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),h=I.toString();break}default:sl(t)}this.requestQuic&&(h=It(h));let p=this.abortAllController.signal,m;if(a){let I=new AbortController;if(m=Jh(al(this.abortAllController.signal,"abort"),al(a,"abort")).subscribe(()=>{try{I.abort()}catch(T){la(T)}}),this.subscription.add(m),this.abortAllController.signal.aborted||a.aborted)try{I.abort()}catch(T){la(T)}p=I.signal}let f=0,b=Br();c.log("startRequest",yi({url:h,priority:s,rangeMethod:t,range:i,isLowLatency:n,requestStartedAt:b})),this.firstBytesRequested$.next();let g=yield this.doFetch(h,{priority:s,headers:d,signal:p}),S=Br();if(!g)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(S-b),!g.ok||!g.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${g.status}: ${g.statusText}`;return c.error("error",{message:I}),c.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let I=Br(),T={requestStartedAt:b,requestEndedAt:I,duration:I-b};return c.log("endRequest",yi(T)),c.end(),g.arrayBuffer()}let y=g.body;if(u){let I;[y,I]=g.body.tee(),this.throughputEstimator?.trackStream(I,n)}let v=y.getReader(),w,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(w=A),!w&&i&&(w=i.to-i.from+1);let L=w?new Uint8Array(w):new Uint8Array(0),x=!1,R=I=>{this.unsubscribeAbortSubscription(m),x=!0,la(I)},E=Dr(p,async function*({done:I,value:T}){if(f===0&&(this.lastRequestFirstBytes$.next(Br()-b),this.firstBytesReceived$.next()),p.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&T){if(l&&w)L.set(T,f),f+=T.byteLength;else{let F=new Uint8Array(L.length+T.length);F.set(L),F.set(T,L.length),L=F,f+=T.byteLength}r?.(new DataView(L.buffer),f),yield v?.read().then(E,R)}}.bind(this));yield v?.read().then(E,R),this.unsubscribeAbortSubscription(m);let O=Br(),D={failed:x,requestStartedAt:b,requestEndedAt:O,duration:O-b};return x?(c.error("endRequest",yi(D)),c.end(),null):(c.log("endRequest",yi(D)),c.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=Dr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,a=r,u=s,n=!1,l,h;e.indexRange&&(l=e.indexRange.from,h=e.indexRange.to,n=s+1===l,n&&(a=Math.min(l,r),u=Math.max(h,s))),a=Math.min(a,0);let d=yield this.fetch(e.url,{range:{from:a,to:u},priority:i,measureThroughput:!1});if(!d)return null;let c=new DataView(d,r-a,s-a+1);if(!t.validateData(c))throw new Error("Invalid media file");let p=t.parseInit(c),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let f;if(n)f=new DataView(d,m.from-a,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!g)return null;f=new DataView(g)}let b=t.parseSegments(f,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=Dr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(a=>({...a,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ns(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:sl(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t,i){let r=await fetch(e,t);if(r.ok)return i==="manifest"&&this.firstBytesManifest$.next(),r;let s=await r.text(),a=parseInt(s);if(!isNaN(a))switch(a){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 (${a})`,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(l=>l.time.from<=e&&l.time.to>=e);!n||this.currentSegment?.time.from===n.time.from&&this.currentSegment.time.to===n.time.to||(this.currentSegment=n,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(n.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=o.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>o.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Pe(t.segmentReference))}};var op=["progress","play","seeked","stalled","waiting"],up=["timeupdate","progress","loadeddata","playing","seeked"];var ha=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Dn;this.subscriptionRemovable=new ap;this.representationSubscription=new Dn;this.state$=new C("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new lt;this.manifestRequested$=new lt;this.firstBytesManifest$=new lt;this.manifestReceived$=new lt;this.firstBytesRequested$=new lt;this.firstBytesReceived$=new lt;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new lt;this.fetcherError$=new lt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new lt;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=Z(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ue.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ln(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ue.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Fs(e??"",this.manifestUrlString)}catch(n){let l=Cs(e)??{id:"ManifestParsing",category:Ue.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(l)}if(!t)return null;let i=(n,l,h)=>!!(this.element?.canPlayType?.(l)&&Ae()?.isTypeSupported?.(`${l}; codecs="${h}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:l,streamIsUnpublished:h,streamIsAlive:d}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]},s,a;for(let n of["video","audio"]){let h=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p));r[n]=h;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=h.map(({codecs:p})=>p);n==="audio"&&(a=Xs(c),d=a[0]),n==="video"&&(s=Ks(c),this.forceVideoCodec&&s.includes(this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[n]=h.filter(({codecs:p})=>mi(p)===d))}else{let c=new Set(h.map(({codecs:p})=>p));d=Ys(c),d&&(r[n]=h.filter(({codecs:p})=>p.startsWith(d)))}if(n==="video"){let c=this.tuning.preferHDR,p=r.video.some(f=>f.hdr),m=r.video.some(f=>!f.hdr);M.display.isHDR&&c&&p?r.video=r.video.filter(f=>f.hdr):m&&(r.video=r.video.filter(f=>!f.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:a}),this.tracer.log("updateManifestEnd",Fr(u)),u}.bind(this));this.initRepresentations=Ln(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Fr({initialVideo:e,initialAudio:t,sourceHls:i})),Ti(this.manifest),Ti(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Dn,this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Je(c,"error").pipe(ca(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ue.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=ms();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ei())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new Mr("video",this.source,u,a),this.bufferManagers=[this.videoBufferManager],_r(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new Mr("audio",this.source,c,a),this.bufferManagers.push(this.audioBufferManager)}Cr.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Cr(this.manifest.streams.text,a)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let n=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(qt(...up.map(c=>Je(this.element,c))).pipe(Ei(c=>this.element?ce(this.element.buffered,this.element.currentTime*1e3):0),Or(),np(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&n()})).subscribe(this.bufferLength$)),this.representationSubscription.add(qt(Je(this.element,"ended"),this.forceEnded$).subscribe(()=>{n()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Or()).subscribe(p=>this.liveStreamEndTimestamp=Mn())),this.subscription.add(Je(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Rn(1e3).subscribe(p=>{let m=ft(this.manifestUrlString,2);this.manifestUrlString=Z(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()||pi(this.element,1)})),this.representationSubscription.add(Ii({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ca(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(p=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!p)return;let m=this.liveSeekableDuration$.getValue()-p/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+p/1e3)})),this.representationSubscription.add(Ii({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ca(({isLive:p})=>p),Or((p,m)=>m.bufferLength<p.bufferLength),Ei(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=ft(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,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=p-b;if(this.isManualDecreasePlaybackInLive())return;let v=1;Math.abs(y)>g&&(v=1+Math.sign(y)*S),pi(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 c=0;this.representationSubscription.add(Ii({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ul(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,b=ft(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,w=isFinite(p)?p:m,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let x="none";if(A?x="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(R=>R.proceedLowLatencyLive()),x="active_low_latency"):b!==0&&w<S?x="live_forward_buffering":w<S+v&&(x="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),x==="live_forward_buffering"||x==="live_with_target_offset"){let R=c-(S+y),E=this.normolizeLiveOffset(Math.trunc(b+R/f)),O=Math.abs(E-b),D=0;!p||O<=this.tuning.dashCmafLive.offsetCalculationError?D=b:E>0&&O>this.tuning.dashCmafLive.offsetCalculationError&&(D=E),this.manifestUrlString=Z(this.manifestUrlString,D,2)}(x==="live_with_target_offset"||x==="live_forward_buffering")&&(c=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:Ue.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=qt(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Ei(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),h=qt(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Ei(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),d=Ii({allBuffersFull:l,someBufferEnded:h}).pipe(Or(),Ei(({allBuffersFull:c,someBufferEnded:p})=>c&&p),ca(c=>c));if(this.representationSubscription.add(qt(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(qt(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(p=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){p();return}this.error$.next({id:"OpenOfStream",category:Ue.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),p()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let m=[];return p.duration&&m.push(p.duration),Pe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&_r(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Rn(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ue.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new da({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.manifestReceived$.subscribe(this.manifestReceived$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=nt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Ti(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Mn()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Z(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){Ti(this.element),this.state$.setState("running");let e=Je(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(ul(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(qt(...op.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&&he(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=Mn(),a=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let n=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,h=this.audioBufferManager?.getForwardBufferDuration()??0,d=l<a&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&h<a&&s-n>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(m=>{this.error$.next({id:"stallIntervalCallback",category:Ue.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),r.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",Fr(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Rn(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ue.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){Ti(this.element),Ti(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),he(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(ol(this.element)||ol(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Fr({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){_r(this.element)&&_r(this.source)&&_r(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=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 l of n.gaps)(l.persistent||n.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?a=1/0:(a===null||l.to>a)&&(a=l.to));if(a!==null){let n=a+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,this.tracer.log("jumpGap",Fr({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:n,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as lp,map as dp,observeElementSize as cp,Subscription as hp,ValueSubject as Bn,noop as pp}from"@vkontakte/videoplayer-shared/evergreen";var pa=class{constructor(){this.subscription=new hp;this.pipSize$=new Bn(void 0);this.videoSize$=new Bn(void 0);this.elementSize$=new Bn(void 0);this.pictureInPictureWindowRemoveEventListener=pp}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(cp(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(lp({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 zt=class{constructor(e){this.subscription=new Tp;this.videoState=new C("stopped");this.observableVideo=null;this.droppedFramesManager=new oi;this.stallsManager=new ra;this.elementSizeManager=new pa;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new St;this.audioTrackSwitchHistory=new St;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return fp(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Si(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 ha({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;yp(this.observableVideo)&&(this.observableVideo=xe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=a=>{e.error$.next({id:i,category:ll.WTF,message:`${i} internal logic error`,thrown:a})},s=(a,u)=>this.subscription.add(a.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Vn(d=>!!d.length),cl()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let a=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ur(d=>d.to.state!=="none"),Nr());this.stallsManager.init({isSeeked$:a,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Vn(dl),cl()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Ur(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if(bp(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of c.audio){f.push(En(b));let g=[];for(let S of b.representations){let y=Zu(S);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of c.video){m.push(xn(f));let b=[];for(let g of f.representations){let S=Rr({...g,streamId:f.id});S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}this.params.output.availableVideoStreams$.next(m);for(let f of c.text)for(let b of f.representations){let g=el(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,n=u&&rl(u)||null;this.subscription.add(Hr(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,vp(this.video,"progress")).pipe(Vn(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c||d==="running"&&n&&!n())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:m}=this.selectedRepresentations;if(!p)return;let f=Ht(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===p.id);dl(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},r)),this.subscription.add(gp({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Hr(ma([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Ur(d=>d.to)))}).pipe(Ur(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),Nr()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Nr()).subscribe(d=>{let c=Ht(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(xn(m));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Nr()).subscribe(d=>{let c=Ht(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(En(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Ur(({to:d})=>d==="ready"),Nr());this.subscription.add(Hr(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ma(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Hr(l,this.player.state$.stateChangeEnded$,ma(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let h=Hr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ma(["init"])).pipe(Sp(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=Ht(this.videoTracksMap.keys(),x=>x.id===u),l=s.currentVideoTrack$.getValue(),h=r.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!h)return;let d=Ht(this.videoStreamsMap.keys(),x=>x.id===h.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let p=ce(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),S=g?.id&&Ht(this.audioStreamsMap.keys(),x=>x.id===g.id)||this.audioStreamsMap.keys().next().value,y=0;if(S){if(n&&!a){let x=e(n,c,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,x?.bitrate??-1/0)}if(l){let x=e(l,c,this.audioStreamsMap.get(S)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,x?.bitrate??-1/0)}}let v=n;(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:y,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let w=S&&t(v,c,this.audioStreamsMap.get(S)??[],{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}),A=this.videoTracksMap.get(v)?.representation,L=w&&this.audioTracksMap.get(w)?.representation;A&&L?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=L):A&&!L&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ll.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ie(this.video),this.tracer.end()}};var jr=class extends zt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Cn,merge as hl,filter as pl,filterChanged as ml,isNullable as On,map as fl,ValueSubject as Fn,isNonNullable as Ip}from"@vkontakte/videoplayer-shared/evergreen";var Qr=class extends zt{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),a(r.timeUpdate$,i.liveBufferTime$),a(this.player.liveSeekableDuration$,i.duration$),a(this.player.liveLatency$,i.liveLatency$);let u=new Fn(1);a(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(ml()).subscribe(n=>{let l=i.position$.getValue(),h=i.volume$.getValue(),d=!h.volume||h.muted;!n&&!l&&d?e=!0:n&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(fl(n=>n.to)).subscribe(this.player.isLowLatency$)).add(Cn({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fl(({liveBufferTime:n,liveAvailabilityStartTime:l})=>n&&l?n+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(pl(n=>Ip(n))).subscribe(n=>i.isLiveEnded$.next(n!=="active"&&i.position$.getValue()===0))).add(Cn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:hl(r.playbackRateState$,new Fn(1))}).pipe(pl(({liveStreamStatus:n,liveDuration:l})=>n==="active"&&!!l)).subscribe(({liveDuration:n,playbackRate:l})=>{let h=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||On(h)||(t=n-h)})).add(Cn({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:hl(r.playbackRateState$,new Fn(1))}).pipe(ml((n,l)=>this.player.liveStreamStatus$.getValue()==="active"?n.liveDuration===l.liveDuration:n.time===l.time)).subscribe(({time:n,liveDuration:l,playbackRate:h})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&h>=1-c||On(n)||On(l))return;let p=-1*(l-n-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(n=>{if(n){let l=tl(n);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var bl="X-Playback-Duration",_n=async o=>{let e=await fetch(o),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(bl)?parseInt(e.headers.get(bl),10):void 0};import{assertNever as Dp,combine as Bp,debounce as Vp,ErrorCategory as ga,filter as Cp,filterChanged as Op,isNonNullable as vl,isNullable as Sa,map as yl,merge as Fp,observableFrom as _p,Subscription as Np,ValueSubject as Un,VideoQuality as Up}from"@vkontakte/videoplayer-shared/evergreen";import{videoSizeToQuality as Ep,getExponentialDelay as xp}from"@vkontakte/videoplayer-shared/evergreen";var wp=o=>{let e=null;if(o.QUALITY&&(e=gt(o.QUALITY)),!e&&o.RESOLUTION){let[t,i]=o.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Ep({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 l=Object.fromEntries(u[1].split(",").map(b=>b.split("="))),h=l.QUALITY??`stream-${l.BANDWIDTH}`,d=wp(l),c;l.BANDWIDTH&&(c=parseInt(l.BANDWIDTH,10)/1e3||void 0),!c&&l["AVERAGE-BANDWIDTH"]&&(c=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[b,g]=l.RESOLUTION.split("x").map(S=>parseInt(S,10));b&&g&&(m={width:b,height:g})}let f=new URL(t[++s],e).toString();d&&i.push({id:h,quality:d,url:f,bandwidth:c,size:m,fps:p})}if(n){let l=Object.fromEntries(n[1].split(",").map(p=>{let m=p.indexOf("=");return[p.substring(0,m),p.substring(m+1)]}).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),h=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,c=l.NAME;h&&d&&r.push({type:"internal",id:d,label:c,language:d,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Ap=o=>new Promise(e=>{setTimeout(()=>{e()},o)}),Nn=0,gl=async(o,e=o,t,i)=>{let s=await(await fetch(o,i)).text();Nn+=1;try{let{qualityManifests:a,textTracks:u}=kp(s,e);return{qualityManifests:a,textTracks:u}}catch{if(Nn<=t.manifestRetryMaxCount)return await Ap(xp(Nn-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),gl(o,e,t)}return{qualityManifests:[],textTracks:[]}},fa=gl;import{isNonNullable as $p,Subscription as Pp,throttle as Lp,ValueSubject as Sl,Subject as Rp,ErrorCategory as Mp}from"@vkontakte/videoplayer-shared/evergreen";var ba=class{constructor(e,t,i,r,s){this.subscription=new Pp;this.abortControllers={destroy:new AbortController,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Sl(null);this.getCurrentTime$=new Sl(null);this.error$=new Rp;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(Lp(1e3)).subscribe(a=>{this.processLiveTime(a)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),a=await(await fetch(r,{signal:this.abortControllers.destroy.signal})).text(),u=this.parsePlaylist(a,r);return{textTrack:i,playlist:u}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
179
+ `),s=0;for(let a=0;a<r.length;++a){let u=r[a];switch(!0){case u.startsWith("#EXTINF:"):{let n=r[++a],l=new URL(n,t).toString(),h=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+h},url:l}),s=s+h,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),c=new Date(i.programDateTime).valueOf();i.segmentStartTime=c-d}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let n=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=n;let l=new Date(n);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if($p(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let a of t)if(a.time.from<=e&&a.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:a.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new AbortController;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Mp.WTF,thrown:t,message:e})}};var Wr=class{constructor(e){this.subscription=new Np;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Un([]);this.liveOffset=new Bt;this.manifestStartTime$=new Un(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else r?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Dp(t)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Up.INVARIANT,url:this.params.source.url};let t=(i,r)=>fa(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new ba(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Be(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ga.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ga.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Un(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),a.find(n=>n.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:ga.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe(Op(),yl(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),n=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&vl(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let c=this.manifests$.getValue().find(p=>p.id===d);c&&(this.params.output.currentVideoTrack$.next(c),this.params.output.hostname$.next(de(c.url)))}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),n&&n.from==="changing_manifest"&&this.videoState.setState(n.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add(Bp({startTime:this.manifestStartTime$.pipe(Cp(vl)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:n})=>this.params.output.liveTime$.next(u+n*1e3),i)),this.subscription.add(this.manifests$.pipe(yl(u=>u.map(({id:n,quality:l,size:h,bandwidth:d,fps:c})=>({id:n,quality:l,size:h,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let a=Fp(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,_p(["init"])).pipe(Vp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Sa(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:u,min:n}=t?.to??i??{};for(let[l,h]of[[u,"mq"],[n,"lq"]]){let d=String(parseFloat(l||""));h&&l&&r.searchParams.set(h,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,a=Z(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(a),this.video.setAttribute("src",a),this.video.load(),_n(a).then(u=>{if(!Sa(u))this.maxSeekBackTime$.next(u);else{let n=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Sa(n)||!isFinite(n))&&fetch(a).then(l=>l.text()).then(l=>{let h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(h){let d=new URL(h,a).toString();_n(d).then(c=>{Sa(c)||this.maxSeekBackTime$.next(c)})}}).catch(()=>{})}})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ga.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Z(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 Hp,debounce as jp,ErrorCategory as Hn,fromEvent as jn,isNonNullable as Qp,isNullable as Wp,map as Tl,merge as Il,observableFrom as El,Subscription as qp,ValueSubject as xl,VideoQuality as zp}from"@vkontakte/videoplayer-shared/evergreen";var qr=class{constructor(e){this.subscription=new qp;this.videoState=new C("stopped");this.manifests$=new xl([]);this.unmuteAfterBrowserResetsHappened=new xl(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||a||u){let h=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(h);let{currentTime:d}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Hp(t)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:zp.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(),fa(Z(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.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",a=this.manifests$.getValue();if(!a.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),a.find(n=>n.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:Hn.WTF,message:"HlsProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Tl(u=>u.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),vi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),n=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Qp(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(f=>f.id===p);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(de(m.url)))}let d=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),n&&n.from==="changing_manifest"&&this.videoState.setState(n.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(Tl(u=>u.map(({id:n,quality:l,size:h,bandwidth:d,fps:c})=>({id:n,quality:l,size:h,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!M.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add(Il(jn(u,"addtrack"),jn(u,"removetrack"),jn(u,"change"),El(["init"])).subscribe(()=>{for(let n=0;n<u.length;n++)u[n].mode="hidden"},i))}let a=Il(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,El(["init"])).pipe(jp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.selectManifest();if(Wp(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:a}=t?.to??i??{};for(let[u,n]of[[s,"mq"],[a,"lq"]]){let l=String(parseFloat(u||""));n&&u&&r.searchParams.set(n,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Gp,assertNonNullable as wl,debounce as Yp,ErrorCategory as kl,isHigherOrEqual as Kp,isLowerOrEqual as Xp,isNonNullable as Jp,merge as Zp,observableFrom as em,Subscription as tm,map as im}from"@vkontakte/videoplayer-shared/evergreen";var zr=class{constructor(e){this.subscription=new tm;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Be;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!a){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){let{currentTime:n}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:n*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return Gp(e)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"MpegProvider",category:kl.WTF,message:"MpegProvider internal logic error",thrown:u})},r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(u,n)=>this.subscription.add(u.subscribe(n,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(im(u=>u.to)),this.params.output.playbackState$),this.subscription.add(qe(this.video,t.isLooped,i)),vi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ve(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&Jp(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let n=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(n!==l){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(n),h.playbackRate=n)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let a=Zp(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,em(["init"])).pipe(Yp(0));this.subscription.add(a.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ie(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;wl(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wl(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=It(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:kl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let h=Ye(a,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(h)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),a=Object.values(this.trackUrls).map(l=>l.track);if(!r||!s||ri(e,a[0].quality,a.at(-1)?.quality)){i();return}let u=e.max?Xp(r,e.max):!0,n=e.min?Kp(r,e.min):!0;u&&n||i(e)}};import{assertNever as $l,debounce as nm,merge as Pl,observableFrom as om,Subscription as um,map as Ll,ValueSubject as lm,ErrorCategory as Wn,VideoQuality as dm}from"@vkontakte/videoplayer-shared/evergreen";import{ErrorCategory as rm}from"@vkontakte/videoplayer-shared/evergreen";var Al=["stun:videostun.mycdn.me:80"],sm=1e3,am=3,Qn=()=>null,va=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Qn;this.externalStopCallback=Qn;this.externalErrorCallback=Qn;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Al}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:rm.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),sm)}normalizeOptions(e={}){let t={stunServerList:Al,maxRetryNumber:am,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Gr=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new lm(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return $l(e)}};this.subscription=new um,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Te(e.container,e.tuning),this.liveStreamClient=new va(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=a=>{e.error$.next({id:"WebRTCLiveProvider",category:Wn.WTF,message:"WebRTCLiveProvider internal logic error",thrown:a})};this.subscription.add(Pl(this.videoState.stateChangeStarted$.pipe(Ll(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ll(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(a)}`})}));let r=xe(this.video);this.subscription.add(()=>r.destroy());let s=(a,u)=>this.subscription.add(a.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ve(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(a=>{e.duration$.next(a===1/0?0:a)})).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ee(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return $l(a.to)}},i)).add(Pl(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,om(["init"])).pipe(nm(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,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Wn.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wn.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xi=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Yr,assertNonNullable as kt,ErrorCategory as ya,filter as Cl,isNonNullable as Ol,isNullable as gm,map as Sm,merge as vm,once as ym,Subject as X,Subscription as Fl,ValueSubject as V,flattenObject as qn}from"@vkontakte/videoplayer-shared/evergreen";import{Observable as cm,map as Rl,Subscription as hm,Subject as pm}from"@vkontakte/videoplayer-shared/evergreen";var Ml=o=>new cm(e=>{let t=new hm,i=o.desiredPlaybackState$.stateChangeStarted$.pipe(Rl(({from:l,to:h})=>`${l}-${h}`)),r=o.desiredPlaybackState$.stateChangeEnded$,s=o.providerChanged$.pipe(Rl(({type:l})=>l!==void 0)),a=new pm,u=0,n="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),n=l,u=window.setTimeout(()=>a.next(l),o.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),n="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>a.next(n),o.maxTransitionInterval)))})),t.add(a.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});import{ErrorCategory as mm,Subscription as fm,combine as bm,filter as Bl,once as Vl}from"@vkontakte/videoplayer-shared/evergreen";function Dl(){return new(window.AudioContext||window.webkitAudioContext)}var wi=class o{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new AbortController;this.subscriptions=new fm;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Bl(s=>!!s.type),Vl()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){M.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(bm({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Bl(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),Vl()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=Dl();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:o.errorId,category:mm.VIDEO_PIPELINE,message:e?.message??`${o.errorId} exception`,thrown:e})}};var Tm={chunkDuration:5e3,maxParallelRequests:5},Kr=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new X;this.noAvailableProvidersError$=new X;this.volumeMultiplierError$=new X;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 X,fetcherError$:new X,fetcherRecoverableError$:new X,warning$:new X,willSeekEvent$:new X,soundProhibitedEvent$:new X,seekedEvent$:new X,loopedEvent$:new X,endedEvent$:new X,manifestRequested$:new X,firstBytesManifest$:new X,manifestReceived$:new X,firstBytesRequested$:new X,firstBytesReceived$:new X,firstBytesEvent$:new X,loadedMetadataEvent$:new X,firstFrameEvent$:new X,canplay$:new X,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 X,availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new Fl;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Ba([...Du(this.params.tuning),...Mu(this.params.tuning)]).filter(l=>Ol(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",qn(s)),this.screenFormatsIterator=new xi(s);let a=[...ln(!0),...ln(!1)];this.chromecastFormatsIterator=new xi(a.filter(l=>Ol(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:n}}=this.params;n&&u!==1&&wi.isSupported()&&(this.volumeMultiplierManager=new wi(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new xi(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(gm(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:ya.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let a=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:a.x,y:a.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Yr(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,a=this.providerOutput,u={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let n=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return kt(n),this.params.tuning.useNewDashProvider?new jr({...u,source:n,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Pr({...u,source:n,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return kt(n),this.params.tuning.useNewDashProvider?new Qr({...u,source:n}):new Lr({...u,source:n})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let n=this.applyFailoverHost(t[e]);return kt(n),new qr({...u,source:n})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let n=this.applyFailoverHost(t[e]);return kt(n),new Wr({...u,source:n,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let n=this.applyFailoverHost(t[e]);return kt(n),new zr({...u,source:n})}case"DASH_LIVE":{let n=this.applyFailoverHost(t[e]);return kt(n),new uu({...u,source:n,config:{...Tm,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let n=this.applyFailoverHost(t[e]);return kt(n),new Gr({container:i,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yr(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,a=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return kt(u),new Ri({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Yr(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Yr(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Yr(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new Fl,t=!1,i=0;return e.add(vm(this.providerOutput.error$.pipe(Cl(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),Ml({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Sm(r=>({id:`ProviderHangup:${r}`,category:ya.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Cl(({to:s})=>s==="playing"),ym()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,a={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===ya.NETWORK,n=r.category===ya.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),h=i<this.params.tuning.providerErrorLimit&&!n,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,c=l&&!n&&(u&&t||!h);a={...a,isNetworkError:u,isFatalError:n,haveFailoverHost:l,tryFailover:c,canReinitProvider:h},h?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",qn(a)):this.tracer.error("providerError",qn(a))})),e}};import{fromEvent as Ta,once as Im,combine as Em,Subscription as _l,ValueSubject as zn,map as Nl,filter as xm,isNonNullable as Ia,now as Le,safeStorage as Gn}from"@vkontakte/videoplayer-shared/evergreen";var wm=5e3,Ul="one_video_throughput",Hl="one_video_rtt",Xr=window.navigator.connection,jl=()=>{let o=Xr?.downlink;if(Ia(o)&&o!==10)return o*1e3},Ql=()=>{let o=Xr?.rtt;if(Ia(o)&&o!==3e3)return o},Wl=(o,e,t)=>{let i=t*8,r=i/o;return i/(r+e)},Yn=class o{constructor(e){this.subscription=new _l;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=o.load(Ul)||(e.useBrowserEstimation?jl():void 0)||wm,i=o.load(Hl)??(e.useBrowserEstimation?Ql():void 0)??0;if(this.throughput$=new zn(t),this.rtt$=new zn(i),this.rttAdjustedThroughput$=new zn(Wl(t,i,e.rttPenaltyRequestSize)),this.throughput=nt.getSmoothedValue(t,-1,e),this.rtt=nt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let a=jl();a&&this.throughput.next(a);let u=Ql();Ia(u)&&this.rtt.next(u)};Xr&&"onchange"in Xr&&this.subscription.add(Ta(Xr,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Gn.set(Ul,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Gn.set(Hl,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(Nl(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Em({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Nl(({throughput:r,rtt:s})=>Wl(r,s,e.rttPenaltyRequestSize)),xm(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Le(),r=new _l;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Ta(e,"progress").pipe(Im()).subscribe(s=>{t=s.loaded,i=Le()}));break;case 1:case 0:r.add(Ta(e,"loadstart").subscribe(()=>{t=0,i=Le()}));break}r.add(Ta(e,"loadend").subscribe(s=>{if(e.status===200){let a=s.loaded,u=Le(),n=a-t,l=u-i;this.addRawSpeed(n,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Le(),a=0,u=Le(),n=h=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${h}`).catch(()=>{})},l=async({done:h,value:d})=>{if(h)!t&&this.addRawSpeed(r,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let c=Le();if(c-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||c-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(a,m,1,t),a=d.byteLength,s=Le()}else a+=d.byteLength;u=Le()}else r+=d.byteLength,a+=d.byteLength,a>=this.tuningConfig.streamMinSampleSize&&Le()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,Le()-u,this.concurrentDownloads.size),a=0,u=Le());await i?.read().then(l,n)}};this.concurrentDownloads.add(e),i?.read().then(l,n)}addRawSpeed(e,t,i=1,r=!1){if(o.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Gn.get(e);if(Ia(t))return parseInt(t,10)??void 0}},ql=Yn;import{fillWithDefault as km,VideoQuality as Ea}from"@vkontakte/videoplayer-shared/evergreen";var zl={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ea.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ea.Q_720P,trafficSavingLimit:Ea.Q_480P},stallsManager:{enabled:!0,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ea.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},Gl=o=>({...km(o,zl),configName:[...o.configName??[],...zl.configName]});import{assertNonNullable as Xn,combine as dt,ErrorCategory as xa,filter as re,filterChanged as W,fromEvent as Jn,isNonNullable as Jl,isNullable as Dm,Logger as Bm,map as Q,mapTo as Zl,merge as At,now as wa,once as ne,Subject as H,Subscription as ed,tap as Zn,ValueSubject as $,isHigher as Vm,isInvariantQuality as td,flattenObject as $t,throttle as eo,getTraceSubscriptionMethod as id,TracerFactory as Cm,InternalsExposure as Om,getPlayerId as Fm}from"@vkontakte/videoplayer-shared/evergreen";import{merge as Am,map as $m,filter as Yl,isNonNullable as Pm}from"@vkontakte/videoplayer-shared/evergreen";var Kn=({seekState:o,position$:e})=>Am(o.stateChangeEnded$.pipe($m(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Yl(Pm)),e.pipe(Yl(()=>o.getState().state==="none")));import{assertNonNullable as Lm}from"@vkontakte/videoplayer-shared/evergreen";var Kl=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 Xl=(o,e,t,i)=>{o!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(Rm(r=>r.length>0),Mm()).subscribe(r=>{r.find(i)&&e.startTransitionTo(o)}):(o===void 0||t?.getValue().find(i))&&e.startTransitionTo(o)};var ka=class{constructor(e={configName:[]},t=Cm.createRootTracer(!1),i){this.subscription=new ed;this.logger=new Bm;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new $(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new $(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new $(void 0),position$:new $(0),duration$:new $(1/0),muted$:new $(!1),volume$:new $(1),availableVideoStreams$:new $([]),currentVideoStream$:new $(void 0),availableQualities$:new $([]),availableQualitiesFps$:new $({}),currentQuality$:new $(void 0),isAutoQualityEnabled$:new $(!0),autoQualityLimitingAvailable$:new $(!1),autoQualityLimits$:new $({}),predefinedQualityLimitType$:new $("unknown"),availableAudioStreams$:new $([]),currentAudioStream$:new $(void 0),availableAudioTracks$:new $([]),isAudioAvailable$:new $(!0),currentPlaybackRate$:new $(1),currentBuffer$:new $({start:0,end:0}),isBuffering$:new $(!0),isStalled$:new $(!1),isEnded$:new $(!1),isLooped$:new $(!1),isLive$:new $(void 0),isLiveEnded$:new $(null),canPlayLiveTailBuffer$:new $(!1),canChangePlaybackSpeed$:new $(void 0),atLiveEdge$:new $(void 0),atLiveDurationEdge$:new $(void 0),liveTime$:new $(void 0),liveBufferTime$:new $(void 0),liveLatency$:new $(void 0),currentFormat$:new $(void 0),availableTextTracks$:new $([]),currentTextTrack$:new $(void 0),throughputEstimation$:new $(void 0),rttEstimation$:new $(void 0),videoBitrate$:new $(void 0),hostname$:new $(void 0),httpConnectionType$:new $(void 0),httpConnectionReused$:new $(void 0),surface$:new $("none"),chromecastState$:new $("NOT_AVAILABLE"),chromecastDeviceName$:new $(void 0),intrinsicVideoSize$:new $(void 0),availableSources$:new $(void 0),is3DVideo$:new $(!1),currentVideoSegmentLength$:new $(0),currentAudioSegmentLength$:new $(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willReady$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,fetcherRecoverableError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,manifestRequested$:new H,firstBytesManifest$:new H,manifestReceived$:new H,firstBytesRequested$:new H,firstBytesReceived$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H,fetcherError$:new H,severeStallOccured$:new H};this.experimental={element$:new $(void 0),tuningConfigName$:new $([]),enableDebugTelemetry$:new $(!1),dumpTelemetry:Fo,getCurrentTime$:new $(null)};if(this.initLogs(),this.tuning=Gl(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&(Object.values(this.info).forEach(r=>r.setSuppressErrors(!0)),Object.values(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ls({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ql(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Om("core",Fm(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,s,a)=>{let u=Reflect.get(r,s,a);return typeof u!="function"?u:(...n)=>{try{return u.apply(r,n)}catch(l){let h=n.map(p=>JSON.stringify(p,(m,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${h.join(", ")})`;throw this.events.fatalError$.next({id:d,category:xa.WTF,message:c,thrown:l}),l}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...a}=e;this.tracer.log("initVideo",$t(a)),this.domContainer=Kl(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?M.isInited$.pipe(re(s=>!!s),ne()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Jn(document,"visibilitychange").pipe(ne()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(re(t=>!!t),ne()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:a,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Xn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),ne()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",$t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",$t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Xl(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Dm(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Jl(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(No(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),ne()).subscribe(()=>{this.initedAt=wa(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let a=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",$t(a)),a.state==="requested"?this.desiredState.seekState.setState({...a,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${a.state}`,category:xa.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ne()).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),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(dt({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,l)=>td(n)?1:td(l)?-1:Vm(l,n)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(a=>{let u={};for(let n of a)n.fps&&(u[n.quality]=n.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(W()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(re(a=>Jl(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(dt({hasLiveOffsetByPaused:At(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(dt({atLiveEdge:dt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Kn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:a,position:u,isLowLatency:n})=>{let l=this.getActiveLiveDelay(n);return a&&Math.abs(u)<l/1e3}),W(),Zn(a=>a&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:a,hasPausedTimeoutCase:u})=>a&&!u)).subscribe(this.info.atLiveEdge$)).add(dt({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),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(Kn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(At(e.providerOutput.endedEvent$.pipe(Zl(!0)),e.providerOutput.seekedEvent$.pipe(Zl(!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:xa.VIDEO_PIPELINE,message:a?`${a} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(ne()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(ne()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(ne()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(ne()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(ne()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(ne(),Q(a=>a??wa()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ne(),Q(()=>wa()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ne(),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 $(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new $(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:a})=>a==="playing"),ne()).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}),W());this.subscription.add(s.subscribe(a=>{a?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(At(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let a=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.videoWidth,height:a?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(a=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:a?.size?.width,height:a?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(At(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let a=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),n=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),h=this.chromecastInitializer.castState$.getValue(),d;h==="CONNECTED"?d="second_screen":n?l?a?d="pip":u?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Q(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new ed;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),ne()).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;Xn(this.providerContainer),Xn(e),Oo(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Co(t)),this.providerContainer.current$.subscribe(({type:t})=>Vi("provider",t)),e.duration$.subscribe(t=>Vi("duration",t)),e.availableVideoTracks$.pipe(re(t=>!!t.length),ne()).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",M.video.supportedCodecs)}initTracerSubscription(){let e=id(this.tracer.log.bind(this.tracer)),t=id(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(dt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(re(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(re(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(re(i=>i>0),W()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(dt({currentBuffer:this.info.currentBuffer$.pipe(re(i=>i.end>0),W((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(W())}).pipe(eo(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(dt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(re(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),eo(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),re(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),re(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),re(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(dt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(re(({throughputEstimation:i,rtt:r})=>!!i&&!!r),eo(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),re(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:xa.DOM,message:String(r)})})};this.subscription.add(At(Jn(document,"visibilitychange"),Jn(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",a=!!e&&!e?.released;r&&s?a||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",$t({quality:t,availableTracks:$t(e),track:$t(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Hi()}};import{Subscription as ND,Observable as UD,Subject as HD,ValueSubject as jD,VideoQuality as QD}from"@vkontakte/videoplayer-shared/evergreen";var WD=`@vkontakte/videoplayer-core@${io}`;export{ns as ChromecastState,Pa as HttpConnectionType,UD as Observable,ye as PlaybackState,ka as Player,os as PredefinedQualityLimits,WD as SDK_VERSION,HD as Subject,ND as Subscription,La as Surface,io as VERSION,jD as ValueSubject,et as VideoFormat,QD as VideoQuality,Id as areValidLiveRecordSources,M as clientChecker,Li as isMobile};